diff --git a/.codex/scripts/task_guard.sh b/.codex/scripts/task_guard.sh index 72e122699b..6224e99ec2 100644 --- a/.codex/scripts/task_guard.sh +++ b/.codex/scripts/task_guard.sh @@ -7,17 +7,14 @@ usage() { Usage: task_guard.sh start --id ID --mode MODE --scope PATH [--scope PATH ...] [--adopt-dirty PATH ...] - task_guard.sh check [--cycle] - task_guard.sh replan --reason TEXT --next TEXT - task_guard.sh checkpoint [--document PATH] --message TEXT --next TEXT + task_guard.sh check task_guard.sh finish --verified EVIDENCE --commit-message MESSAGE task_guard.sh status Modes: quick-fix, standard, assessment, upstream -Exit codes: 0 pass, 2 usage/setup error, 3 checkpoint required, +Exit codes: 0 pass, 2 usage/setup error, 4 safety gate (scope, dirty-file, branch, or HEAD violation), -5 replan required; continue the same task after checkpoint/replan, 6 commit created but recovery-tag creation needs a direct fix and one retry. EOF } @@ -33,12 +30,6 @@ safety_gate() { exit 4 } -replan_required() { - printf 'REPLAN_REQUIRED_CONTINUE: %s\n' "$1" >&2 - printf 'ACTION_REQUIRED: checkpoint if needed, run replan with a materially different next action, then continue the same task.\n' >&2 - exit 5 -} - repo_root="$(git rev-parse --show-toplevel 2>/dev/null)" || fail_usage "not inside a Git worktree" cd "$repo_root" @@ -72,16 +63,26 @@ path_matches_file() { } list_dirty() { - local output="$1" { git diff --name-only git diff --cached --name-only git ls-files --others --exclude-standard - } | LC_ALL=C sort -u > "$output" + } | LC_ALL=C sort -u } list_staged() { - git diff --cached --name-only | LC_ALL=C sort -u > "$1" + git diff --cached --name-only | LC_ALL=C sort -u +} + +check_staged_whitespace() { + local -a paths=() + local path + while IFS= read -r path; do + [[ -n "$path" ]] || continue + [[ "$path" == *.patch ]] && continue + paths+=("$path") + done < <(list_staged) + ((${#paths[@]} == 0)) || git diff --cached --check -- "${paths[@]}" } fingerprint_path() { @@ -106,16 +107,6 @@ write_state() { printf '%s\n' "$2" > "$state_dir/$1" } -mode_defaults() { - case "$1" in - quick-fix) printf '%s %s %s\n' 15 4 2 ;; - standard) printf '%s %s %s\n' 30 8 3 ;; - assessment) printf '%s %s %s\n' 45 6 3 ;; - upstream) printf '%s %s %s\n' 45 16 3 ;; - *) return 1 ;; - esac -} - show_status() { [[ -d "$state_dir" ]] || fail_usage "no task guard state" printf 'Task: %s\n' "$(read_state id)" @@ -123,8 +114,6 @@ show_status() { printf 'Status: %s\n' "$(read_state status)" printf 'Branch: %s\n' "$(read_state branch)" printf 'Base HEAD: %s\n' "$(read_state base_head)" - printf 'Cycles: %s/%s\n' "$(read_state cycles)" "$(read_state max_cycles)" - printf 'Start/interval-end: %s / %s\n' "$(read_state start_epoch)" "$(read_state interval_end_epoch)" printf '%s\n' 'Scope:' sed 's/^/ - /' "$state_dir/scope" if [[ -s "$state_dir/adopted" ]]; then @@ -134,15 +123,10 @@ show_status() { } scope_check() { - local enforce_interval="$1" - local count_cycle="$2" local expected_branch local expected_head local current_branch local current_head - local current_dirty="$state_dir/current-dirty.tmp" - local current_staged="$state_dir/current-staged.tmp" - local task_dirty="$state_dir/task-dirty.tmp" local path local saved_hash local current_hash @@ -166,8 +150,6 @@ scope_check() { fi done < "$state_dir/protected-fingerprints" - list_dirty "$current_dirty" - : > "$task_dirty" while IFS= read -r path; do [[ -n "$path" ]] || continue if path_matches_file "$path" "$state_dir/protected"; then @@ -178,66 +160,22 @@ scope_check() { violations=$((violations + 1)) continue fi - printf '%s\n' "$path" >> "$task_dirty" - done < "$current_dirty" - LC_ALL=C sort -u "$task_dirty" -o "$task_dirty" + done < <(list_dirty) - list_staged "$current_staged" while IFS= read -r path; do [[ -n "$path" ]] || continue if path_matches_file "$path" "$state_dir/protected" || ! path_matches_file "$path" "$state_dir/scope"; then printf 'SCOPE_VIOLATION: staged path is not task-owned: %s\n' "$path" >&2 violations=$((violations + 1)) fi - done < "$current_staged" + done < <(list_staged) if ((violations > 0)); then - safety_gate "$violations scope/worktree violation(s); checkpoint and reconcile before continuing" + safety_gate "$violations scope/worktree violation(s); reconcile the declared scope or worktree before continuing" fi - local changed_count - local max_files - changed_count="$(wc -l < "$task_dirty" | tr -d ' ')" - max_files="$(read_state max_files)" - if ((changed_count > max_files)); then - safety_gate "task-owned changed files $changed_count exceed mode limit $max_files" - fi - - if [[ "$count_cycle" == "1" ]]; then - local cycles - cycles=$(( $(read_state cycles) + 1 )) - write_state cycles "$cycles" - fi - - local now - local start - local interval_end - local threshold - local cycles - local max_cycles - now="$(date +%s)" - start="$(read_state start_epoch)" - interval_end="$(read_state interval_end_epoch)" - threshold="$(read_state checkpoint_threshold_epoch)" - cycles="$(read_state cycles)" - max_cycles="$(read_state max_cycles)" - - if [[ "$enforce_interval" == "1" ]]; then - if ((cycles > max_cycles)); then - replan_required "diagnosis/edit cycles $cycles exceed the current route limit $max_cycles; checkpoint and choose a materially different path" - fi - if ((now >= threshold)); then - local checkpoint_epoch - checkpoint_epoch="$(read_state checkpoint_epoch)" - if ((checkpoint_epoch < threshold)); then - printf 'CHECKPOINT_REQUIRED: 70%% of the review interval has elapsed; persist state before more exploration\n' >&2 - exit 3 - fi - fi - fi - - printf 'PASS: task=%s elapsed=%sm changed=%s/%s cycles=%s/%s\n' \ - "$(read_state id)" "$(( (now - start) / 60 ))" "$changed_count" "$max_files" "$cycles" "$max_cycles" + printf 'PASS: task=%s branch/HEAD, protected dirty paths, scope, and staged paths are safe\n' \ + "$(read_state id)" } start_task() { @@ -259,8 +197,10 @@ start_task() { [[ "$id" =~ ^[A-Za-z0-9._-]+$ ]] || fail_usage "task id must use letters, digits, dot, underscore, or hyphen" [[ ${#scopes[@]} -gt 0 ]] || fail_usage "at least one --scope is required" - local defaults - defaults="$(mode_defaults "$mode")" || fail_usage "unknown mode: $mode" + case "$mode" in + quick-fix|standard|assessment|upstream) ;; + *) fail_usage "unknown mode: $mode" ;; + esac if [[ -d "$state_dir" && -f "$state_dir/status" ]]; then local previous_status @@ -269,17 +209,6 @@ start_task() { fail_usage "another task guard is unfinished: $(sed -n '1p' "$state_dir/id") ($previous_status)" fi fi - mkdir -p "$state_root" - if [[ -d "$state_dir" ]]; then - local archive_dir - local previous_id="partial" - if [[ -f "$state_dir/id" ]]; then - previous_id="$(sed -n '1p' "$state_dir/id")" - fi - archive_dir="$state_root/archive/$previous_id-$(TZ=Asia/Shanghai date +%Y%m%d%H%M%S)-$$" - mkdir -p "$state_root/archive" - mv -- "$state_dir" "$archive_dir" - fi mkdir -p "$state_dir" : > "$state_dir/scope" : > "$state_dir/adopted" @@ -300,8 +229,8 @@ start_task() { done LC_ALL=C sort -u "$state_dir/adopted" -o "$state_dir/adopted" - list_dirty "$state_dir/initial-dirty" - list_staged "$state_dir/initial-staged" + list_dirty > "$state_dir/initial-dirty" + list_staged > "$state_dir/initial-staged" local adopted_match while IFS= read -r value; do [[ -n "$value" ]] || continue @@ -340,96 +269,16 @@ start_task() { fi done < "$state_dir/initial-dirty" - local minutes max_files max_cycles now - read -r minutes max_files max_cycles <<< "$defaults" - now="$(date +%s)" write_state id "$id" write_state mode "$mode" write_state status active write_state branch "$(git branch --show-current)" write_state base_head "$(git rev-parse HEAD)" - write_state start_epoch "$now" - write_state interval_end_epoch "$((now + minutes * 60))" - write_state checkpoint_threshold_epoch "$((now + minutes * 60 * 70 / 100))" - write_state checkpoint_epoch 0 - write_state max_files "$max_files" - write_state max_cycles "$max_cycles" - write_state cycles 0 show_status printf 'PASS: task guard started; protected %s pre-existing dirty path(s)\n' "$(wc -l < "$state_dir/protected" | tr -d ' ')" } -checkpoint_task() { - local document="" - local message="" - local next_action="" - while (($# > 0)); do - case "$1" in - --document) (($# >= 2)) || fail_usage "--document needs a value"; document="$2"; shift 2 ;; - --message) (($# >= 2)) || fail_usage "--message needs a value"; message="$2"; shift 2 ;; - --next) (($# >= 2)) || fail_usage "--next needs a value"; next_action="$2"; shift 2 ;; - *) fail_usage "unknown checkpoint option: $1" ;; - esac - done - [[ -n "$message" && -n "$next_action" ]] || fail_usage "checkpoint message and next action are required" - if [[ -n "$document" ]]; then - document="$(normalize_path "$document")" || fail_usage "unsafe checkpoint document path" - path_matches_file "$document" "$state_dir/scope" || safety_gate "checkpoint document is outside declared scope: $document" - [[ -f "$document" ]] || safety_gate "checkpoint document does not exist: $document" - rg -Fq -- "$message" "$document" || safety_gate "checkpoint document does not contain the supplied completion message" - rg -Fq -- "$next_action" "$document" || safety_gate "checkpoint document does not contain the supplied next action" - else - document="-" - fi - scope_check 0 0 - local now - local minutes - now="$(date +%s)" - case "$(read_state mode)" in - quick-fix) minutes=15 ;; - standard) minutes=30 ;; - assessment|upstream) minutes=45 ;; - *) fail_usage "invalid stored mode" ;; - esac - write_state checkpoint_epoch "$now" - write_state start_epoch "$now" - write_state interval_end_epoch "$((now + minutes * 60))" - write_state checkpoint_threshold_epoch "$((now + minutes * 60 * 70 / 100))" - printf '%s\t%s\t%s\t%s\n' "$now" "$document" "$message" "$next_action" >> "$state_dir/checkpoints.log" - printf 'PASS: checkpoint recorded from %s; review cadence reset and task remains active\n' "$document" -} - -replan_task() { - local reason="" - local next_action="" - while (($# > 0)); do - case "$1" in - --reason) (($# >= 2)) || fail_usage "--reason needs a value"; reason="$2"; shift 2 ;; - --next) (($# >= 2)) || fail_usage "--next needs a value"; next_action="$2"; shift 2 ;; - *) fail_usage "unknown replan option: $1" ;; - esac - done - [[ -n "$reason" && -n "$next_action" ]] || fail_usage "replan reason and next action are required" - scope_check 0 0 - local now - local minutes - now="$(date +%s)" - case "$(read_state mode)" in - quick-fix) minutes=15 ;; - standard) minutes=30 ;; - assessment|upstream) minutes=45 ;; - *) fail_usage "invalid stored mode" ;; - esac - printf '%s\t%s\t%s\n' "$now" "$reason" "$next_action" >> "$state_dir/replans.log" - write_state start_epoch "$now" - write_state interval_end_epoch "$((now + minutes * 60))" - write_state checkpoint_threshold_epoch "$((now + minutes * 60 * 70 / 100))" - write_state checkpoint_epoch "$now" - write_state cycles 0 - printf 'PASS: review interval reset after replan; next=%s\n' "$next_action" -} - create_recovery_tag() { local commit="$1" local verified="$2" @@ -475,34 +324,31 @@ finish_task() { create_recovery_tag "$(read_state committed_head)" "$(read_state verification)" return fi - scope_check 0 0 + scope_check - local task_dirty="$state_dir/task-dirty.tmp" - [[ -s "$task_dirty" ]] || safety_gate "no task-owned changes to commit" local path + local task_change_count=0 while IFS= read -r path; do [[ -n "$path" ]] || continue + path_matches_file "$path" "$state_dir/protected" && continue + path_matches_file "$path" "$state_dir/scope" || continue git add -A -- "$path" - done < "$task_dirty" + task_change_count=$((task_change_count + 1)) + done < <(list_dirty) + ((task_change_count > 0)) || safety_gate "no task-owned changes to commit" - git diff --cached --check || safety_gate "staged task diff failed git diff --cached --check" - local staged="$state_dir/finish-staged.tmp" - list_staged "$staged" - [[ -s "$staged" ]] || safety_gate "task changes did not produce a staged diff" + check_staged_whitespace || safety_gate "staged non-patch diff failed whitespace validation" + local staged_count=0 while IFS= read -r path; do [[ -n "$path" ]] || continue + staged_count=$((staged_count + 1)) if ! path_matches_file "$path" "$state_dir/scope" || path_matches_file "$path" "$state_dir/protected"; then safety_gate "automatic commit would include non-task path: $path" fi - done < "$staged" + done < <(list_staged) + ((staged_count > 0)) || safety_gate "task changes did not produce a staged diff" - local message_file="$state_dir/commit-message.txt" - { - printf '%s\n\n' "$commit_message" - printf 'Verification: %s\n' "$verified" - printf 'Task-Guard: %s\n' "$(read_state id)" - } > "$message_file" - git commit -F "$message_file" + git commit -m "$commit_message" -m "Verification: $verified" -m "Task-Guard: $(read_state id)" local commit commit="$(git rev-parse HEAD)" write_state committed_head "$commit" @@ -518,16 +364,7 @@ shift case "$command_name" in start) start_task "$@" ;; - check) - count_cycle=0 - if (($# > 0)); then - [[ "$1" == "--cycle" && $# == 1 ]] || fail_usage "check accepts only --cycle" - count_cycle=1 - fi - scope_check 1 "$count_cycle" - ;; - checkpoint) checkpoint_task "$@" ;; - replan) replan_task "$@" ;; + check) (($# == 0)) || fail_usage "check accepts no options"; scope_check ;; finish) finish_task "$@" ;; status) (($# == 0)) || fail_usage "status accepts no options"; show_status ;; -h|--help|help) usage ;; diff --git a/.codex/skills/upstream-integration-governor/SKILL.md b/.codex/skills/upstream-integration-governor/SKILL.md index 302f2c31c2..66d524b443 100644 --- a/.codex/skills/upstream-integration-governor/SKILL.md +++ b/.codex/skills/upstream-integration-governor/SKILL.md @@ -1,6 +1,6 @@ --- name: upstream-integration-governor -description: Evaluate and implement upstream dependency integrations safely, efficiently, and reversibly. Use when Codex is asked to inspect, compare, port, merge, cherry-pick, rebase, rebuild, or update upstream commits, forks, locks, patches, AARs, native libraries, or binary dependency packages—especially WebHTV FFmpeg, AndroidX media/Media3/nextlib, mpv, mpv-android, libplacebo, IJK, JNI, Exo, MPV, or cross-repository player work; also use for regression, performance, provenance, rollback, commit/tag, staged rollout, and durable checkpoint planning around those changes. +description: Inventory related upstream repositories, generate or refresh exhaustive commit-ledger assessment documents, and evaluate or implement dependency integrations safely, efficiently, and reversibly. Use when Codex is asked to inspect, compare, assess, port, merge, cherry-pick, rebase, rebuild, or update upstream commits, forks, locks, patches, AARs, native libraries, or binary dependency packages—especially WebHTV FFmpeg, AndroidX media/Media3/nextlib, mpv, mpv-android, libplacebo, IJK, JNI, Exo, MPV, or cross-repository player work; also use for regression, performance, provenance, rollback, commit/tag, staged rollout, and durable checkpoint planning around those changes. --- # Upstream Integration Governor @@ -24,6 +24,36 @@ Start `bash .codex/scripts/task_guard.sh` using the matching lane. Check it afte - A started task owns exactly one `docs/-.md`. Put research, alternatives, recommendation, approval, implementation, repeated corrections, validation, full commit/tag records, rollback, current status, and the one next action in that file. - Never create additional `plans/`, assessment, implementation, fix, or dated continuation documents for the same task. Continue appending to its unique file. The master assessment is the only exception and only supplies the cross-task index and complete commit ledger. +## Build or refresh an upstream assessment ledger + +Use this mode when the user asks to梳理 new upstream updates, rebuild the player dependency merge plan, or produce a document comparable to the existing dated assessment. + +1. Discover the repository graph from the prior assessment, `.gitmodules`, lock files, source/version manifests, Gradle/native build scripts, patch directories, artifact provenance, and repository documentation. Include direct upstreams, WebHTV forks, dependency/source repositories, and packaging repositories that can change the shipped player behavior; record why each repository is in scope and how revisions flow between them. +2. Freeze exact local and upstream baselines before judging commits: repository URL/path, branch, previous assessed head, current head, ancestry, relevant lock or artifact hash, access date, and any proxy or source-access limitation. Never infer a missing hash from conversation memory. +3. Enumerate the complete commit range in each repository using full 40-character IDs. Inspect actual diffs, parents, tests, follow-ups, reverts, rebases/equivalents, downstream consumers, and final-tree behavior. Give every commit one explicit disposition such as already implemented, partially implemented, superseded, irrelevant, candidate, blocked, or implemented; do not omit merge, cleanup, or low-value commits merely because they are inconvenient. +4. Map cross-repository chains rather than presenting isolated lists. Show which source commit feeds which fork/lock/patch/artifact/App change, which commits are companions, and which ordering or binary rebuild dependency makes them one functional stage. +5. Compare the ledger with current WebHTV code and Git history before creating tasks. Existing local behavior is the baseline contract; detect equivalent implementations, later fixes, partial coverage, and code paths that make an upstream change unreachable. Mark covered or meaningless work as ignored instead of manufacturing a task. +6. Preserve a closed historical assessment. When a materially new upstream wave begins, create `docs/upstream-player-dependency-merge-assessment-YYYY-MM-DD.md`, link its predecessor, and record the new baselines; when continuing the same active wave, update its existing dated document. The document must remain the exhaustive cross-task index and link each actionable item to its single `docs/-.md` file. +7. Organize actionable work into reversible `Exo`, `MPV`, and `common` stages with the selection order `Exo -> MPV -> common`. For every stage record the user-visible playback capability, repository/commit chain, current coverage, benefits, risks and disadvantages, compatibility/performance/package-size impact, best-practice evidence, WebHTV adaptation, recommendation, acceptance criteria, verification, rollout, rollback, and next action. + +For a request that only asks for the next task, do not mutate the ledger or code. Recover the current state, identify exactly one unambiguous next candidate, and return the following decision packet in ordinary user-facing language: + +```text +任务编号和名称: +所属分类:Exo / MPV / 通用 +要实现的实际能力: +当前项目已有实现: +涉及仓库及完整 commit ID: +收益: +缺点与风险: +与现有功能的关系: +建议:实施 / 暂缓 / 忽略 +最小实施步骤: +预计需要的验证: +``` + +Stop after that packet. Do not implement until the user explicitly approves the candidate. When estimating approved work, report current-agent wall-clock execution time and separate code work, native/Gradle build time, device or user-dependent validation, and commit/tag/document closure when those phases apply. + ## Mandatory best-practice review before implementation This gate applies to every proposed upstream merge stage and every material new player/dependency requirement. It is not optional merely because a commit appears small or its upstream title sounds authoritative. diff --git a/AGENTS.md b/AGENTS.md index ec89f14f50..edd8acccf7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,10 +1,12 @@ # WebHTV Agent Contract -This file applies to the whole repository. Keep work correct, narrow, reversible, and fast. A nested `AGENTS.md` may add path-specific rules but may not weaken the safety, scope, time, or rollback rules here. +This file applies to the whole repository. Keep work correct, narrow, reversible, and fast. A nested `AGENTS.md` may add path-specific rules but may not weaken the safety, scope, or rollback rules here. ## 1. Start with a bounded lane -Before the first edit, state one completion sentence, the allowed paths, protected pre-existing dirty paths, and the cheapest decisive verification. Use the smallest applicable lane: +Before the first edit, state one completion sentence, the allowed paths, protected pre-existing dirty paths, the current local time and timezone, a realistic total-duration estimate with expected finish time, and the cheapest decisive verification. For multi-phase work, give a short estimate for each phase. Treat these estimates as execution targets rather than guard gates; when the estimate is reached or slips materially, stop optional work, state the cause, and continue with the narrowest completion path or a materially different shortest route. Do not let a stale estimate justify repeated checks, open-ended research, or an unfinished handoff. Use the smallest applicable lane: + +Estimate elapsed wall-clock time for the current Codex agent in this workspace, not the time a human engineer or team would need. Base the estimate on the actual repository state, available tools, warm caches, ABI/build scope, device availability, and unavoidable network/build/user wait; split those phases when they materially differ and give the expected local finish time. Do not quote person-days or staffing estimates unless the user explicitly asks for them. ### Governance-maintenance fast path @@ -16,20 +18,14 @@ When the task only edits `AGENTS.md`, `.codex/skills/**`, `.codex/scripts/**`, o - The repository task guard is not required for maintenance of the guard itself or its instruction files. Preserve unrelated dirty files and do not commit/tag unless the user explicitly requests it or this maintenance is already an isolated task-owned change. - Maximum normal tool sequence: one inspection call, one patch call, one combined validation call. A fourth call requires a failed validation or a concrete blocker, and the reason must be stated before running it. -| Lane | Efficiency-review cadence | File limit per logical unit | Same-route cycle threshold | -| --- | ---: | ---: | --- | -| `quick-fix` | 15 minutes | 4 task-owned files | 2 diagnosis cycles | -| `standard` | 30 minutes | 8 task-owned files | 3 diagnosis cycles | -| `assessment` | 45 minutes per batch | 6 task-owned files | one bounded evidence question or commit cluster | -| `upstream` | 45 minutes per approved unit | 16 task-owned files | one approved functional unit | - - A small bug is `quick-fix` by default. Do not promote it to architecture, broad research, or native work merely because more investigation is possible. -- A simple rule/document/Skill edit should finish in a few minutes; 5 minutes triggers immediate removal of every optional step, and 10 minutes is already abnormal. A localized bug should also take the shortest evidence-backed path. These are efficiency escalation points, not permission to abandon incomplete work: after escalation perform only the necessary edit, one cheapest decisive verification, commit/tag when authorized, and hand off. Continue longer only when a named required operation inherently takes longer or a concrete blocker prevents completion; state that reason immediately. -- These cadences are progress-review reminders, never task budgets, deadlines, or caps on total duration/review count. At a boundary, checkpoint and judge convergence: continue a productive route with one bounded next action, or replace an unproductive/repeated route. The task remains active until complete or genuinely blocked. +- Lane names describe risk and workflow only. They do not impose elapsed-time, changed-file, cycle-count, checkpoint, or replan gates. - Optimize for shortest elapsed time by removing redundant exploration, repeated commands, speculative scope, and low-value validation. Never gain speed by dropping required behavior, risk-driven verification, rollback, or the requested completion target. +- Under a user-stated time constraint, never repeat a successful or otherwise conclusive check, and never expand research after the available evidence can decide the approved implementation. A retry requires a relevant edit or an inconclusive result; broader research requires one named unresolved fact that can materially change the decision. +- When the user states a time budget or deadline, treat it as the execution target for the current turn and reserve roughly the final quarter for verification, documentation, commit, tag, and handoff. Choose one shortest evidence-backed route, run each expensive build/test at most once unless a relevant edit or an inconclusive result requires a retry, and stop optional research or cleanup before the budget is exhausted. Keep all code, lock, artifact, and task-document changes for one approved unit in one guard session and one commit when possible; only make a second documentation-only closure commit when an unavoidable post-commit ID/tag must be recorded, with no extra build or research pass. This routing rule never lowers correctness, rollback, or completion requirements. +- Classify command failures before asking for approval: a repository file-mode or invocation error is fixed by using the correct in-scope invocation once (for example `bash ./gradlew`), while sandbox/network/permission errors are the cases that warrant an escalation request. Do not spend a second attempt or approval round on the wrong failure class. - Do not widen declared behavior or paths without explicit user approval. Split genuinely large work into independently useful units while preserving the original completion target. -- Except for the governance-maintenance fast path above, run `bash .codex/scripts/task_guard.sh start --id --mode --scope ...` before code edits. Run `check` after each diagnosis/edit cycle and before any expensive command. -- A nonzero guard result is a gate, not task termination. On `CHECKPOINT_REQUIRED`, persist state, then continue. On `REPLAN_REQUIRED_CONTINUE`, record why the current route is not converging, choose a materially different shortest path, run `replan`, and immediately continue the same task. There is no maximum number of replans. +- Except for the governance-maintenance fast path above, run `bash .codex/scripts/task_guard.sh start --id --mode --scope ...` before code edits. `check` is an optional read-only safety audit; it is not required after each cycle, and `finish` performs the final safety check itself. - A timeout may bound one potentially hung command; it must not bound the task. Diagnose the timeout and continue with a safer, narrower, or resumable command. ## 2. Scope is closed by default @@ -37,7 +33,7 @@ When the task only edits `AGENTS.md`, `.codex/skills/**`, `.codex/scripts/**`, o - Modify only the declared paths and behavior needed for the completion sentence. No unrelated refactor, cleanup, formatting sweep, dependency upgrade, generated-file churn, or speculative abstraction. - A failing unrelated test, warning, or nearby defect is not part of the task. Report it; do not fix it unless it blocks the requested result and the user approves the expansion. - Preserve every file dirty before task start. Never include an initially dirty path in task scope or a task commit unless the user explicitly assigns that work and it has been isolated safely. -- If the proposed fix crosses a new module, changes public behavior/API, changes dependency or binary ownership, or exceeds the current logical-unit limits, checkpoint and replan the smallest next unit. Ask the user only when that next unit expands the authorized behavior or paths. +- If the proposed fix crosses a new module, changes public behavior/API, or changes dependency or binary ownership, narrow it to the smallest useful unit. Ask the user only when that unit expands the authorized behavior or paths. ## 3. Search and diagnosis must earn their cost @@ -46,7 +42,7 @@ When the task only edits `AGENTS.md`, `.codex/skills/**`, `.codex/scripts/**`, o - Expand search only when the current evidence cannot decide the next action. Use at most two query reformulations for a quick fix and three for one material upstream question; prefer primary code/docs/issues over repetitive posts. - Capture a command's full output once and filter/read that saved result. Do not rerun the same test or build with different output filters. - Run each final syntax/lint/test check once. Repeat it only after a relevant edit or when the first result is inconclusive; never re-check an unchanged successful result for reassurance. -- After two failed attempts with the same hypothesis, discard it and replan a materially different path. Repetition without new evidence is prohibited; task completion remains required. +- After two failed attempts with the same hypothesis, discard it and choose a materially different path. Repetition without new evidence is prohibited; task completion remains required. ## 4. Verification is risk-based and minimal @@ -56,22 +52,28 @@ When the task only edits `AGENTS.md`, `.codex/skills/**`, `.codex/scripts/**`, o - Do not weaken a failing gate. Classify the failure as regression, environment, or stale expectation. Expand work only if fixing it is within the declared scope. - Quality floor: do not trade away existing behavior, correctness, security, compatibility, material performance, or task completion merely to meet the clock. Time pressure removes redundant work; it never authorizes an unverified shortcut. -## 5. Context and elapsed-time recovery +## 5. Context recovery -- Codex cannot reliably inspect its exact remaining context tokens. Use hard proxies: elapsed time, completed cycles, changed-file count, and anticipated output size. -- Checkpoint after every verified logical unit, at 70% of a review cadence, before a command likely to run over 10 minutes or emit over roughly 200 lines, and before changing functional stage/repository. +- Create a durable checkpoint only when a task is genuinely likely to cross a session/compaction boundary, before a risky long-running operation, or when changing functional stage/repository. Never require it because of elapsed minutes, cycle count, or changed-file count. - A checkpoint records objective, lane/scope, branch/HEAD, protected dirty paths, completed evidence, files changed, verification/result, unresolved risk, rollback anchor, and exactly one next action. -- For long-lived work, update the relevant tracked document with `apply_patch`, then run `bash .codex/scripts/task_guard.sh checkpoint --document --message --next `. -- After compaction or resumption, read the latest checkpoint and reconcile it with `git status`, branch, and HEAD before doing new work. Never reconstruct exact hashes or decisions from memory. +- For long-lived work, update the relevant tracked document with `apply_patch`; the task guard does not own or force progress checkpoints. +- For a task expected to survive session/compaction, create one task-owned `docs/-.md`. Keep a short top or tail `Recovery anchor` containing the objective and acceptance criteria, plan status, current files/symbols, completed actions and results, unverified worktree edits, unresolved risks, and exactly one next action. +- Update the recovery anchor when material state changes or immediately before a likely compaction/long-running operation. The conversation plan is transient; the task document is the durable execution state. +- After compaction or resumption, recover in this order: workspace and Git evidence (`git status`, branch/HEAD, scoped diff) -> the latest recovery anchor/task document -> the compaction summary -> older conversation plan. Reconcile discrepancies and preserve existing unverified changes. +- Once recovery is reconciled, execute the documented single next action. Do not restart planning, repeat completed repository-wide searches, reread completed code paths, or discard partial edits unless the workspace or task document proves they are invalid. Never reconstruct exact hashes or decisions from memory. ## 6. Commit and recovery tag are part of code completion - One task guard session equals one atomic logical change. If a task needs another logical commit, finish this unit and start a new guard session. - A code change is not complete until its targeted verification is recorded, its task-owned files are committed atomically, and that commit has a unique annotated local recovery tag. +- **Explicit closure fast path:** when the user confirms the tested behavior is acceptable (for example, “没问题”, “通过”, or equivalent) and asks to commit or create a tag, that confirmation closes optional verification for the approved scenario. Stop immediately; do not capture more logs or screenshots, run adjacent-media/device cases, start another build/test, inspect upstream, perform reassurance checks, or broaden documentation before closing. +- After an explicit closure request, the next tool call must perform the closure unless one concrete unknown safety fact makes that impossible. The normal sequence is at most: one minimal patch to the existing task document only when required to record already-known results, then one `task_guard.sh finish` call that commits and tags, then report the commit and tag. Do not run a separate guard `check`, status/diff review, or tag verification because `finish` already enforces scope and tag creation. If the verified change is already committed, create the requested annotated tag immediately without reopening documentation. +- Treat this as a latency-critical execution target: normally complete the requested local commit/tag within 60 seconds and start the tag-producing command in the first possible tool round trip. A direct command failure or genuine safety blocker is the only reason to exceed this target; report and fix only that direct cause. User confirmation never authorizes skipping an actually failed required gate, but a missing optional or neighboring test is not a blocker after the user accepts the observed behavior. +- When the same message also authorizes a push, push only the named/current branch and newly created tag after local closure. Do not fetch, compare, or revalidate first unless the push itself reports a conflict or rejection. - Finish with `bash .codex/scripts/task_guard.sh finish --verified --commit-message `. The script must stage only task-owned paths and create `recovery//`; never hand-stage unrelated dirty work. - After the commit succeeds, create its recovery tag immediately with one local, non-interactive `git tag -a` command with tag signing disabled. The tag phase should normally finish within 5 seconds; do not insert builds, tests, searches, network calls, repeated diff reviews, or redundant tag checks between commit and tag. - Treat a successful tag command as sufficient. If it fails, capture the error once, fix its direct cause, and retry only after the command materially changes; never loop an unchanged tag command. -- If verification fails, scope overlaps pre-existing dirty work, or a safe atomic commit cannot be formed, do not commit/tag. Checkpoint and report the exact blocker. +- If verification fails, scope overlaps pre-existing dirty work, or a safe atomic commit cannot be formed, do not commit/tag. Record durable state when needed and report the exact blocker. - Assessment-only work does not authorize production edits. Tags point only to committed, verified states. Never push commits/tags, move a published tag, rewrite history, or publish artifacts without explicit authorization. ## 7. Best-practice design research @@ -82,6 +84,17 @@ The mandatory design-research gate below applies repository-wide to every materi For FFmpeg, media/Media3/nextlib, Exo, mpv, mpv-android, libplacebo, JNI, native binaries, locks, patches, or binary packaging, read and follow `.codex/skills/upstream-integration-governor/SKILL.md` and only the references it marks for the current lane. +`.codex/skills/upstream-integration-governor/` is the runtime canonical copy for this repository. `webhome-devkit/skills/upstream-integration-governor/` is a reference/distribution mirror for other developers and is not an additional instruction authority or loading path. Whenever the canonical Skill changes, update the mirror in the same governance-maintenance task and validate that the mirrored files are byte-identical; never let the two copies evolve independently. + +### New-session routing for the upstream merge plan + +- The user does not need to paste a bootstrap prompt. Treat short requests such as `下一个任务`, `继续上游播放器依赖合并计划`, `梳理新的上游更新`, or equivalent wording as sufficient invocation of the upstream Skill. The expected branch for this repository plan is `fongmi-sync`; inspect the actual branch/HEAD and preserve every pre-existing dirty path before any mutation. +- Unless the newest user message explicitly approves implementation, the first response is assessment-only and read-only. Fully read `README.md`, this file, the active `docs/upstream-player-dependency-merge-assessment-*.md`, and only the task documents directly related to the candidate. Use the assessment ledger, Git history, and current code to choose the next genuinely unfinished and unimplemented task in the order `Exo -> MPV -> common`. +- Before proposing work, determine whether another commit already implemented it, partially covered it, superseded it, or made it irrelevant. Recommend `忽略` directly when it is already covered or has no current product value; do not relabel it as new implementation work. +- Explain the user-visible playback capability in ordinary language. Include all related repositories and full 40-character commit IDs, cross-repository relationships, benefits, disadvantages and risks, effects on existing behavior, compatibility, performance and package size, best-practice status, required WebHTV adaptation, a clear `实施`/`暂缓`/`忽略` recommendation, and the smallest staged implementation and verification plan. +- Use this first-response shape and then stop for explicit approval: `任务编号和名称`, `所属分类`, `要实现的实际能力`, `当前项目已有实现`, `涉及仓库及完整 commit ID`, `收益`, `缺点与风险`, `与现有功能的关系`, `建议`, `最小实施步骤`, `预计需要的验证`. Do not modify code, locks, patches, artifacts, or runtime behavior during this selection response. +- A later explicit `开始实施` authorizes only the unambiguous currently recommended task. Treat all existing behavior, compatibility and material performance as acceptance contracts: the implementation must not knowingly cause direct or indirect regressions or reduce current performance. Adapt or reject the upstream design when needed, use the narrowest risk-proportionate verification, and do not claim completion while a material regression risk remains unresolved. + - Assessment and implementation are separate authorities. Enumerate every in-scope upstream commit with a full 40-character ID and a disposition; never implement an unapproved stage. - Group related cross-repository behavior into independently reversible `Exo`, `MPV`, or `common` stages. Preserve the decision/implementation order `Exo -> MPV`. - Continue the active assessment from `docs/upstream-player-dependency-merge-assessment-2026-08-20.md`; do not redo completed analysis unless source heads or material evidence changed. @@ -102,4 +115,4 @@ Before changing code, locks, build scripts, patches, artifacts, or runtime behav ## 9. Enforcement boundary -`AGENTS.md` is an instruction layer, not a security boundary. The task guard can enforce progress reviews, declared paths, protected dirty files, atomic task commits, and recovery tags only when invoked. It must never convert elapsed time, token estimates, review count, or cycle count into permission to abandon a task or lower its completion criteria. Git hooks are not the primary mechanism because ordinary clones do not reliably enable tracked hooks and client hooks can be bypassed. CI remains the correct place for organization-wide mandatory checks. +`AGENTS.md` is an instruction layer, not a security boundary. The task guard only enforces declared paths, protected initial dirty files, branch/HEAD stability, atomic task commits, and recovery tags when invoked. It does not enforce elapsed time, cycle counts, changed-file limits, checkpoints, replans, or state archives. Git hooks are not the primary mechanism because ordinary clones do not reliably enable tracked hooks and client hooks can be bypassed. CI remains the correct place for organization-wide mandatory checks. diff --git a/README.md b/README.md index ee26d508c1..300612a8e7 100644 --- a/README.md +++ b/README.md @@ -76,8 +76,8 @@ WebHome 主页、扩展、模板、示例和 AI skills 统一放在 [webhome-dev ### 环境要求 -- Android Studio 仅是可选 IDE,不是项目依赖。命令行构建不读取 Android Studio 的安装目录或内置 JBR,只需要 `JAVA_HOME`/`PATH` 中可用的 JDK 和独立配置的 Android SDK。 -- JDK 21。不要使用 JDK 17;当前 `sourceCompatibility` / `targetCompatibility` 均为 Java 21。 +- 项目使用纯命令行工具链,不依赖任何 IDE。必须在 `JAVA_HOME`/`PATH` 中配置独立 JDK 21,并单独配置 Android SDK Command-line Tools。 +- 需要 JDK 21;当前 `sourceCompatibility` / `targetCompatibility` 均为 Java 21。 - Python 3.10。Chaquo 运行时和构建时 Python 均固定为 3.10,仅安装 Python 3.11/3.12/3.13 会失败。 - Android SDK Platform 37 和 Build Tools 37.0.0。当前 `compileSdk=37`、`minSdk=24`、`targetSdk=28`。 - Android NDK 29.0.14206865(r29)用于重建 MPV/FFmpeg/libplacebo 和 MPV JNI;NDK 28.2.13676358(r28c)继续用于 IJK/DVD。普通 Gradle 打包直接使用仓库已提交二进制,不要求安装 NDK。`scripts/build_mpv_player_jni.sh` 只重建 JNI 桥接库 `libplayer.so`,不会重编 `libmpv.so`、FFmpeg 或 libplacebo。 @@ -101,7 +101,7 @@ export all_proxy=socks5://127.0.0.1:7897 ### 从零 clone 到打包 -先安装或确认 Android SDK Command-line Tools,并通过 `ANDROID_HOME`、`ANDROID_SDK_ROOT` 或根目录 `local.properties` 告诉构建系统 SDK 的位置。`local.properties` 是普通文本配置,直接在仓库根目录创建即可,不需要 Android Studio。macOS 常见 SDK 路径示例: +先安装或确认 Android SDK Command-line Tools,并通过 `ANDROID_HOME`、`ANDROID_SDK_ROOT` 或根目录 `local.properties` 告诉构建系统 SDK 的位置。`local.properties` 是普通文本配置,直接在仓库根目录创建即可。macOS 常见 SDK 路径示例: ```bash export ANDROID_HOME="$HOME/Library/Android/sdk" @@ -109,7 +109,7 @@ export ANDROID_HOME="$HOME/Library/Android/sdk" Linux 常见路径是 `$HOME/Android/Sdk`;Windows 可手动创建 `local.properties`,内容类似 `sdk.dir=C\:\\Users\\你的用户名\\AppData\\Local\\Android\\Sdk`。 -如 SDK 未安装 API 37、Build Tools 或 Platform Tools,使用 Android SDK 自带的 `sdkmanager` 安装;Android Studio 的 SDK Manager 只是可选的图形界面: +如 SDK 未安装 API 37、Build Tools 或 Platform Tools,使用 Android SDK Command-line Tools 自带的 `sdkmanager` 安装: ```bash "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" \ @@ -192,13 +192,13 @@ bash gradlew :app:assembleMobileArm64_v8aDebug :app:assembleLeanbackArmeabi_v7aD | ABI | MPV | FFmpeg | libplacebo | 网络后端 | 说明 | | --- | --- | --- | --- | --- | --- | -| `arm64-v8a` | `0.41.0-940-gcca559b41` | `04482c8d13ac`(9.0-fongmi) | `7.375.0` / `b694a21bf2dc` | curl 8.21.0 + nghttp2 1.69.0 | 截至 2026-08-17,当前 assets 已通过能力、ELF 与打包规则校验 | -| `armeabi-v7a` | `0.41.0-940-gcca559b41` | `04482c8d13ac`(9.0-fongmi) | `7.375.0` / `b694a21bf2dc` | curl 8.21.0 + nghttp2 1.69.0 | 截至 2026-08-17,当前 assets 已通过能力、ELF 与打包规则校验 | +| `arm64-v8a` | `0.41.0-940-gcca559b41` | `177f090e0503`(9.0.1-fongmi) | `7.375.0` / `b694a21bf2dc` | curl 8.21.0 + nghttp2 1.69.0 | C0-M 双 ABI、ELF、APK 和 arm64 手机播放/生命周期验证通过 | +| `armeabi-v7a` | `0.41.0-940-gcca559b41` | `177f090e0503`(9.0.1-fongmi) | `7.375.0` / `b694a21bf2dc` | curl 8.21.0 + nghttp2 1.69.0 | C0-M 独立重建及 ELF/资产验证通过,不能跨 ABI 复制 | 替换或升级 MPV native 时必须遵守: - `libmpv.so`、FFmpeg(codec/device/filter/format/util/swresample/swscale)、静态链接进 MPV 的 libplacebo、curl、nghttp2、MbedTLS 和 `libc++_shared.so` 必须按同一 ABI、同一 lock 成套构建,不能再混用旧 `libmpv.so` 与新依赖作为正式方案。 -- 当前 native lock 使用 MPV `cca559b41ceb0bb7731cf6ef2e1f33276cd30c42`、FFmpeg 9.0-fongmi `04482c8d13ac27b2a9fe93f5d388929eef8af5f4`、libplacebo `b694a21bf2dc176c1e98b8a13c6421a0de5f3da5`(7.375.0/API 375)、mpv-android `99a60ad2141d5ace94453590903c2c6b9a0a2443` 和 NDK r29/API 24。curl 使用 MbedTLS 3.6.7,只启用 HTTP/HTTPS 与 HTTP/2,不包含 HTTP/3、ngtcp2、nghttp3 或 quiche。 +- 当前 native lock 使用 MPV `cca559b41ceb0bb7731cf6ef2e1f33276cd30c42`、FFmpeg 9.0.1-fongmi `177f090e0503b7e013922ca903bde14b1c375f18`、libplacebo `b694a21bf2dc176c1e98b8a13c6421a0de5f3da5`(7.375.0/API 375)、mpv-android `99a60ad2141d5ace94453590903c2c6b9a0a2443` 和 NDK r29/API 24。C0-M 不启用 `dovi_rpu convert=p81`,并继续保留本地 Range、MediaCodec、DV、Vulkan、AudioTrack 和 JNI 保护。curl 使用 MbedTLS 3.6.7,只启用 HTTP/HTTPS 与 HTTP/2,不包含 HTTP/3、ngtcp2、nghttp3 或 quiche。 - 最新 FongMi MPV 分支已经内建重写后的 AImageReader/AHardwareBuffer OpenGL/Vulkan 后端、异步 fence、HDR/Dolby Vision、双 Surface OSD 和 Android helper scheme;旧的 `fd679c81` 不是新分支祖先,原 `mpv-aimagereader-transient-buffer.patch` 已删除,不能在新分支上重复叠加。 - curl 与 nghttp2 静态链接进 `libmpv.so`,APK 不新增独立网络 `.so`。它增强 MPV 直接远程 HTTP/HTTPS 输入;App 自己处理的本地 HLS 代理、`stream_cb` 和 FFmpeg/lavf 路径仍按各自实现工作,不能把启用 curl 理解为所有播放请求都强制走同一后端。 - FFmpeg 文件名、ELF `SONAME` 和所有 `DT_NEEDED` 都要从 `libav*`/`libsw*` 等长改为 `libmv*`/`libmw*`,不能只重命名文件,否则会和 `nextlib-media3ext` 内置 FFmpeg 发生 Android linker 复用冲突。 @@ -366,7 +366,7 @@ keyPassword=your_key_password - `third_party/patches/nextlib-*.patch`:在 `anilbeesetti/nextlib@6ff6cf9d0820382b3c233d018c52e4163b09d345` 上叠加 FFmpeg 软解负载控制和 AV3A/libarcdav3a 支持。 - `third_party/mpv-player-jni`:MPV `libplayer.so` JNI 桥接源码,修改后用 `scripts/build_mpv_player_jni.sh` 重建。 - `app/src/*/assets/mpv-libs/*`:随 APK 打包的 MPV native 库和 JNI 桥接库。 -- `nextlib-media3ext`:`io.github.anilbeesetti:nextlib-media3ext:1.10.0-0.12.1-fongmi-softload-av3a-ffmpeg901-r1`,提供 FFmpeg renderer;内置 FongMi FFmpeg `177f090e0503b7e013922ca903bde14b1c375f18`(9.0.1)和静态链接的 `libarcdav3a`,Exo 可软解 `audio/av3a`,并在输出设备不接受源多声道 PCM 时下混到立体声。MPV native 仍按其独立 lock 使用旧 FFmpeg,不能共用该 AAR 内的 `.so`。 +- `nextlib-media3ext`:`io.github.anilbeesetti:nextlib-media3ext:1.10.0-0.12.1-fongmi-softload-av3a-ffmpeg901-r1`,提供 FFmpeg renderer;内置 FongMi FFmpeg `177f090e0503b7e013922ca903bde14b1c375f18`(9.0.1)和静态链接的 `libarcdav3a`,Exo 可软解 `audio/av3a`,并在输出设备不接受源多声道 PCM 时下混到立体声。MPV C0-M 现在使用同一 FFmpeg 源 revision,但仍独立构建 `libmv*`/`libmw*`,不能共用该 AAR 内的 `.so`。 - `ExoplayerHdrUtils`:`com.suyashbelekar:exoplayerhdrutils:0.4.0`,提供基于 libdovi 的实时 HEVC RPU 转换。Exo 按“原生 DV7 硬解 → P8.1 转换硬解 → HDR10/HEVC 硬解”选择整次播放路径:原生 DV7 可用时保持原码流;原生 DV7 不可用但 P8.1 可用时使用 mode 2 转换并移除增强层;两者都不可用而设备支持 HDR10/HEVC 时,起播前直接使用 HDR10 基底层。能力查询误报或 P8.1 实际初始化/解码失败时,同一会话最多回退 HDR10 一次,不自动切软解或循环重试;用户选择 HDR10 模式时仍整次使用 HDR10 基底层。 `settings.gradle` 中的依赖顺序是仓库本地 `third_party/maven`、Maven Central、Google Maven、`app/libs` 和 JitPack。`app/build.gradle` 会强制所有 `androidx.media3` 依赖使用 `1.11.0-alpha01-fongmi`,避免传递依赖拉回官方版本。 @@ -422,7 +422,7 @@ other/ Logo 图片和辅助工具 | 仓库 | 分支 | Commit | | --- | --- | --- | | [TV](https://github.com/FongMi/TV) | `fongmi` | `1a19fee278fa2234da725d61a53bf59b69fe9127`(`560 / 5.6.0`) | -| [FFmpeg](https://github.com/FongMi/FFmpeg) | `release-9.0-fongmi` | `04482c8d13ac27b2a9fe93f5d388929eef8af5f4` | +| [FFmpeg](https://github.com/FongMi/FFmpeg) | `release-9.0-fongmi` | `177f090e0503b7e013922ca903bde14b1c375f18` | | [mpv-android](https://github.com/FongMi/mpv-android) | `fongmi` | `99a60ad2141d5ace94453590903c2c6b9a0a2443` | | [media](https://github.com/FongMi/media) | `release` | `2bc207851df311340767e913931ca7b28cab1794` | | [mpv](https://github.com/FongMi/mpv) | `fongmi` | `cca559b41ceb0bb7731cf6ef2e1f33276cd30c42` | diff --git a/app/build.gradle b/app/build.gradle index 16d8d071d2..dbccf2e946 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -21,6 +21,7 @@ android { namespace = 'com.fongmi.android.tv' compileSdk libs.versions.compileSdk.get().toInteger() + ndkVersion "29.0.14206865" defaultConfig { applicationId "com.silent.android.webhtv" @@ -36,6 +37,12 @@ android { arguments = ["room.schemaLocation": "$projectDir/schemas".toString(), "eventBusIndex": "com.fongmi.android.tv.event.EventIndex"] } } + externalNativeBuild { + cmake { + arguments "-DANDROID_PLATFORM=android-26" + cppFlags "-std=c++20", "-Wall", "-Wextra", "-Werror=return-type" + } + } } flavorDimensions = ["mode", "abi"] @@ -108,6 +115,13 @@ android { sourceCompatibility JavaVersion.VERSION_21 targetCompatibility JavaVersion.VERSION_21 } + + externalNativeBuild { + cmake { + path file("src/main/cpp/CMakeLists.txt") + version "3.22.1" + } + } } androidComponents { diff --git a/app/schemas/com.fongmi.android.tv.db.AppDatabase/44.json b/app/schemas/com.fongmi.android.tv.db.AppDatabase/44.json new file mode 100644 index 0000000000..138f420ba6 --- /dev/null +++ b/app/schemas/com.fongmi.android.tv.db.AppDatabase/44.json @@ -0,0 +1,690 @@ +{ + "formatVersion": 1, + "database": { + "version": 44, + "identityHash": "2868d4276f9718c3102b142c99dfd3e3", + "entities": [ + { + "tableName": "Keep", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`key` TEXT NOT NULL, `siteName` TEXT, `vodName` TEXT, `vodPic` TEXT, `createTime` INTEGER NOT NULL, `type` INTEGER NOT NULL, `cid` INTEGER NOT NULL, PRIMARY KEY(`key`))", + "fields": [ + { + "fieldPath": "key", + "columnName": "key", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "siteName", + "columnName": "siteName", + "affinity": "TEXT" + }, + { + "fieldPath": "vodName", + "columnName": "vodName", + "affinity": "TEXT" + }, + { + "fieldPath": "vodPic", + "columnName": "vodPic", + "affinity": "TEXT" + }, + { + "fieldPath": "createTime", + "columnName": "createTime", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "cid", + "columnName": "cid", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "key" + ] + } + }, + { + "tableName": "Site", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`key` TEXT NOT NULL, `searchable` INTEGER, `changeable` INTEGER, PRIMARY KEY(`key`))", + "fields": [ + { + "fieldPath": "key", + "columnName": "key", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "searchable", + "columnName": "searchable", + "affinity": "INTEGER" + }, + { + "fieldPath": "changeable", + "columnName": "changeable", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "key" + ] + } + }, + { + "tableName": "Live", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`name` TEXT NOT NULL, `keep` TEXT, `boot` INTEGER NOT NULL, `pass` INTEGER NOT NULL, PRIMARY KEY(`name`))", + "fields": [ + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "keep", + "columnName": "keep", + "affinity": "TEXT" + }, + { + "fieldPath": "boot", + "columnName": "boot", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "pass", + "columnName": "pass", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "name" + ] + } + }, + { + "tableName": "Track", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `type` INTEGER NOT NULL, `key` TEXT, `name` TEXT, `format` TEXT, `selected` INTEGER NOT NULL)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "key", + "columnName": "key", + "affinity": "TEXT" + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT" + }, + { + "fieldPath": "format", + "columnName": "format", + "affinity": "TEXT" + }, + { + "fieldPath": "selected", + "columnName": "selected", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Track_key_type", + "unique": true, + "columnNames": [ + "key", + "type" + ], + "orders": [], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_Track_key_type` ON `${TABLE_NAME}` (`key`, `type`)" + } + ] + }, + { + "tableName": "Config", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `type` INTEGER NOT NULL, `time` INTEGER NOT NULL, `url` TEXT, `json` TEXT, `name` TEXT, `logo` TEXT, `home` TEXT, `parse` TEXT)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "time", + "columnName": "time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "url", + "columnName": "url", + "affinity": "TEXT" + }, + { + "fieldPath": "json", + "columnName": "json", + "affinity": "TEXT" + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT" + }, + { + "fieldPath": "logo", + "columnName": "logo", + "affinity": "TEXT" + }, + { + "fieldPath": "home", + "columnName": "home", + "affinity": "TEXT" + }, + { + "fieldPath": "parse", + "columnName": "parse", + "affinity": "TEXT" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Config_url_type", + "unique": true, + "columnNames": [ + "url", + "type" + ], + "orders": [], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_Config_url_type` ON `${TABLE_NAME}` (`url`, `type`)" + } + ] + }, + { + "tableName": "Device", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `uuid` TEXT, `name` TEXT, `ip` TEXT, `type` INTEGER NOT NULL)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER" + }, + { + "fieldPath": "uuid", + "columnName": "uuid", + "affinity": "TEXT" + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT" + }, + { + "fieldPath": "ip", + "columnName": "ip", + "affinity": "TEXT" + }, + { + "fieldPath": "type", + "columnName": "type", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_Device_uuid_name", + "unique": true, + "columnNames": [ + "uuid", + "name" + ], + "orders": [], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_Device_uuid_name` ON `${TABLE_NAME}` (`uuid`, `name`)" + } + ] + }, + { + "tableName": "History", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`key` TEXT NOT NULL, `vodPic` TEXT, `wallPic` TEXT, `vodName` TEXT, `vodFlag` TEXT, `vodRemarks` TEXT, `episodeUrl` TEXT, `revSort` INTEGER NOT NULL, `revPlay` INTEGER NOT NULL, `createTime` INTEGER NOT NULL, `opening` INTEGER NOT NULL, `ending` INTEGER NOT NULL, `position` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `speed` REAL NOT NULL, `speedOverride` INTEGER NOT NULL DEFAULT 0, `scale` INTEGER NOT NULL, `cid` INTEGER NOT NULL, `typeName` TEXT, `area` TEXT, `actor` TEXT, `director` TEXT, `year` TEXT, `tmdbId` INTEGER NOT NULL DEFAULT 0, `mediaType` TEXT DEFAULT '', `legacyKey` TEXT DEFAULT '', `tmdbSeasonNumber` INTEGER NOT NULL DEFAULT 0, `tmdbEpisodeNumber` INTEGER NOT NULL DEFAULT 0, `player` INTEGER NOT NULL DEFAULT -1, PRIMARY KEY(`key`))", + "fields": [ + { + "fieldPath": "key", + "columnName": "key", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "vodPic", + "columnName": "vodPic", + "affinity": "TEXT" + }, + { + "fieldPath": "wallPic", + "columnName": "wallPic", + "affinity": "TEXT" + }, + { + "fieldPath": "vodName", + "columnName": "vodName", + "affinity": "TEXT" + }, + { + "fieldPath": "vodFlag", + "columnName": "vodFlag", + "affinity": "TEXT" + }, + { + "fieldPath": "vodRemarks", + "columnName": "vodRemarks", + "affinity": "TEXT" + }, + { + "fieldPath": "episodeUrl", + "columnName": "episodeUrl", + "affinity": "TEXT" + }, + { + "fieldPath": "revSort", + "columnName": "revSort", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "revPlay", + "columnName": "revPlay", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "createTime", + "columnName": "createTime", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "opening", + "columnName": "opening", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "ending", + "columnName": "ending", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "position", + "columnName": "position", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "speed", + "columnName": "speed", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "speedOverride", + "columnName": "speedOverride", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "scale", + "columnName": "scale", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "cid", + "columnName": "cid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "typeName", + "columnName": "typeName", + "affinity": "TEXT" + }, + { + "fieldPath": "area", + "columnName": "area", + "affinity": "TEXT" + }, + { + "fieldPath": "actor", + "columnName": "actor", + "affinity": "TEXT" + }, + { + "fieldPath": "director", + "columnName": "director", + "affinity": "TEXT" + }, + { + "fieldPath": "year", + "columnName": "year", + "affinity": "TEXT" + }, + { + "fieldPath": "tmdbId", + "columnName": "tmdbId", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "mediaType", + "columnName": "mediaType", + "affinity": "TEXT", + "defaultValue": "''" + }, + { + "fieldPath": "legacyKey", + "columnName": "legacyKey", + "affinity": "TEXT", + "defaultValue": "''" + }, + { + "fieldPath": "tmdbSeasonNumber", + "columnName": "tmdbSeasonNumber", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "tmdbEpisodeNumber", + "columnName": "tmdbEpisodeNumber", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "player", + "columnName": "player", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "-1" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "key" + ] + } + }, + { + "tableName": "PlaybackDeleteTombstone", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `configKey` TEXT NOT NULL, `scope` TEXT NOT NULL, `historyKey` TEXT NOT NULL, `siteKey` TEXT NOT NULL, `vodId` TEXT NOT NULL, `mediaType` TEXT NOT NULL DEFAULT '', `tmdbId` INTEGER NOT NULL DEFAULT 0, `seasonNumber` INTEGER NOT NULL DEFAULT -1, `deletedAt` INTEGER NOT NULL, PRIMARY KEY(`id`))", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "configKey", + "columnName": "configKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "scope", + "columnName": "scope", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "historyKey", + "columnName": "historyKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "siteKey", + "columnName": "siteKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "vodId", + "columnName": "vodId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "mediaType", + "columnName": "mediaType", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "tmdbId", + "columnName": "tmdbId", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "seasonNumber", + "columnName": "seasonNumber", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "-1" + }, + { + "fieldPath": "deletedAt", + "columnName": "deletedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_PlaybackDeleteTombstone_deletedAt", + "unique": false, + "columnNames": [ + "deletedAt" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_PlaybackDeleteTombstone_deletedAt` ON `${TABLE_NAME}` (`deletedAt`)" + } + ] + }, + { + "tableName": "TmdbSeasonProgress", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`cid` INTEGER NOT NULL, `mediaType` TEXT NOT NULL, `tmdbId` INTEGER NOT NULL, `seasonNumber` INTEGER NOT NULL, `episodeNumber` INTEGER NOT NULL, `position` INTEGER NOT NULL, `duration` INTEGER NOT NULL, `sourceFlag` TEXT NOT NULL, `sourceEpisodeName` TEXT NOT NULL, `sourceEpisodeUrl` TEXT NOT NULL, `sourceHistoryKey` TEXT NOT NULL, `sourceBindingKey` TEXT NOT NULL, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`cid`, `mediaType`, `tmdbId`, `seasonNumber`))", + "fields": [ + { + "fieldPath": "cid", + "columnName": "cid", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "mediaType", + "columnName": "mediaType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "tmdbId", + "columnName": "tmdbId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "seasonNumber", + "columnName": "seasonNumber", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "episodeNumber", + "columnName": "episodeNumber", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "position", + "columnName": "position", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "sourceFlag", + "columnName": "sourceFlag", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sourceEpisodeName", + "columnName": "sourceEpisodeName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sourceEpisodeUrl", + "columnName": "sourceEpisodeUrl", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sourceHistoryKey", + "columnName": "sourceHistoryKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "sourceBindingKey", + "columnName": "sourceBindingKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "updatedAt", + "columnName": "updatedAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "cid", + "mediaType", + "tmdbId", + "seasonNumber" + ] + }, + "indices": [ + { + "name": "index_TmdbSeasonProgress_cid_mediaType_tmdbId_sourceHistoryKey_updatedAt", + "unique": false, + "columnNames": [ + "cid", + "mediaType", + "tmdbId", + "sourceHistoryKey", + "updatedAt" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_TmdbSeasonProgress_cid_mediaType_tmdbId_sourceHistoryKey_updatedAt` ON `${TABLE_NAME}` (`cid`, `mediaType`, `tmdbId`, `sourceHistoryKey`, `updatedAt`)" + }, + { + "name": "index_TmdbSeasonProgress_cid_sourceHistoryKey", + "unique": false, + "columnNames": [ + "cid", + "sourceHistoryKey" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_TmdbSeasonProgress_cid_sourceHistoryKey` ON `${TABLE_NAME}` (`cid`, `sourceHistoryKey`)" + } + ] + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '2868d4276f9718c3102b142c99dfd3e3')" + ] + } +} \ No newline at end of file diff --git a/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmpv.so b/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmpv.so index 09e09f02b4..664faecf56 100644 Binary files a/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmpv.so and b/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmpv.so differ diff --git a/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmvcodec.so b/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmvcodec.so index 38e284dda1..d2ce15e29a 100644 Binary files a/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmvcodec.so and b/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmvcodec.so differ diff --git a/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmvdevice.so b/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmvdevice.so index 475d6f7a9e..96c2cb6486 100644 Binary files a/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmvdevice.so and b/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmvdevice.so differ diff --git a/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmvfilter.so b/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmvfilter.so index 1262031b63..50816bffd7 100644 Binary files a/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmvfilter.so and b/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmvfilter.so differ diff --git a/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmvformat.so b/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmvformat.so index d388099682..f941a0ee20 100644 Binary files a/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmvformat.so and b/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmvformat.so differ diff --git a/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmvutil.so b/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmvutil.so index 868940bfe7..f593f46e77 100644 Binary files a/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmvutil.so and b/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmvutil.so differ diff --git a/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmwresample.so b/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmwresample.so index c51053d719..53c642c8e4 100644 Binary files a/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmwresample.so and b/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmwresample.so differ diff --git a/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmwscale.so b/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmwscale.so index 94d8f97bc9..893846a48a 100644 Binary files a/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmwscale.so and b/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libmwscale.so differ diff --git a/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libplayer.so b/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libplayer.so index 4a047ea474..f5aa327417 100644 Binary files a/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libplayer.so and b/app/src/arm64_v8a/assets/mpv-libs/arm64-v8a/libplayer.so differ diff --git a/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmpv.so b/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmpv.so index 227aff007a..64701f8a77 100644 Binary files a/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmpv.so and b/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmpv.so differ diff --git a/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmvcodec.so b/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmvcodec.so index 732146e39b..33177fa459 100644 Binary files a/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmvcodec.so and b/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmvcodec.so differ diff --git a/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmvdevice.so b/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmvdevice.so index 683a3919a3..6ff21bbbff 100644 Binary files a/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmvdevice.so and b/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmvdevice.so differ diff --git a/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmvfilter.so b/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmvfilter.so index 0f30041a68..6268b2daac 100644 Binary files a/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmvfilter.so and b/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmvfilter.so differ diff --git a/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmvformat.so b/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmvformat.so index 52f5bd207c..57d5a0f2ac 100644 Binary files a/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmvformat.so and b/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmvformat.so differ diff --git a/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmvutil.so b/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmvutil.so index c66e433eec..65559676fc 100644 Binary files a/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmvutil.so and b/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmvutil.so differ diff --git a/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmwresample.so b/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmwresample.so index 1ece082fa5..4c3f8e3d3b 100644 Binary files a/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmwresample.so and b/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmwresample.so differ diff --git a/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmwscale.so b/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmwscale.so index 0100c8ea3f..4b90858b94 100644 Binary files a/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmwscale.so and b/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmwscale.so differ diff --git a/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libplayer.so b/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libplayer.so index e99bbbd363..2a3435a7f8 100644 Binary files a/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libplayer.so and b/app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libplayer.so differ diff --git a/app/src/leanback/java/com/fongmi/android/tv/ui/activity/HistoryActivity.java b/app/src/leanback/java/com/fongmi/android/tv/ui/activity/HistoryActivity.java index a39ced6171..58195b1e35 100644 --- a/app/src/leanback/java/com/fongmi/android/tv/ui/activity/HistoryActivity.java +++ b/app/src/leanback/java/com/fongmi/android/tv/ui/activity/HistoryActivity.java @@ -3,8 +3,10 @@ package com.fongmi.android.tv.ui.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; +import android.view.View; import androidx.recyclerview.widget.GridLayoutManager; +import androidx.recyclerview.widget.RecyclerView; import androidx.viewbinding.ViewBinding; import com.fongmi.android.tv.Product; @@ -16,6 +18,7 @@ import com.fongmi.android.tv.event.RefreshEvent; import com.fongmi.android.tv.setting.Setting; import com.fongmi.android.tv.ui.adapter.HistoryAdapter; import com.fongmi.android.tv.ui.base.BaseActivity; +import com.fongmi.android.tv.ui.custom.FocusRestorer; import com.fongmi.android.tv.ui.custom.SpaceItemDecoration; import com.fongmi.android.tv.ui.dialog.ViewingReportRangeDialog; @@ -26,6 +29,7 @@ public class HistoryActivity extends BaseActivity implements HistoryAdapter.OnCl private ActivityHistoryBinding mBinding; private HistoryAdapter mAdapter; + private final FocusRestorer mFocusRestorer = new FocusRestorer(); public static void start(Activity activity) { activity.startActivity(new Intent(activity, HistoryActivity.class)); @@ -72,7 +76,34 @@ public class HistoryActivity extends BaseActivity implements HistoryAdapter.OnCl } private void getHistory() { - mAdapter.setItems(History.getForDisplay(), () -> mBinding.progressLayout.showContent(true, mAdapter.getItemCount())); + int position = focusedPosition(); + History focused = position < 0 || position >= mAdapter.getItemCount() ? null : mAdapter.getItem(position); + mAdapter.setItems(History.getForDisplay(), () -> { + mBinding.progressLayout.showContent(true, mAdapter.getItemCount()); + if (mAdapter.getItemCount() == 0) mAdapter.setDelete(false); + else if (focused != null) restoreFocus(reposition(focused, position)); + }); + } + + // 刷新会按 createTime 重排,优先按条目身份重新定位;条目已不在新列表里(被别处删掉) + // 就退回原位置,让焦点留在附近而不是掉给右上角的删除按钮 + private int reposition(History focused, int position) { + int found = mAdapter.getItems().indexOf(focused); + if (found >= 0) return found; + return FocusRestorer.nextPosition(position, mAdapter.getItemCount(), Product.getColumn()); + } + + private int focusedPosition() { + if (isFinishing() || isDestroyed() || !mBinding.recycler.hasFocus()) return RecyclerView.NO_POSITION; + View focus = mBinding.recycler.getFocusedChild(); + return focus == null ? RecyclerView.NO_POSITION : mBinding.recycler.getChildAdapterPosition(focus); + } + + // 只在列表原本持有焦点时恢复:条目被移除时 RecyclerView 已 clearFocus, + // 焦点被窗口兜底给了右上角的删除按钮,需要主动交回列表 + private void restoreFocus(int position) { + if (isFinishing() || isDestroyed()) return; + mFocusRestorer.restore(mBinding.recycler, position); } @Subscribe(threadMode = ThreadMode.MAIN) @@ -93,21 +124,32 @@ public class HistoryActivity extends BaseActivity implements HistoryAdapter.OnCl } @Override - public void onItemDelete(History item) { + public void onItemDelete(History item, int position) { + // diff 挂起时 holder 的绑定下标会失效,退回当前聚焦位置(遥控下点击必然带焦点) + int target = position >= 0 ? position : focusedPosition(); mAdapter.remove(item.deleteDisplayItem(), () -> { mBinding.progressLayout.showContent(true, mAdapter.getItemCount()); if (mAdapter.getItemCount() == 0) mAdapter.setDelete(false); + else restoreFocus(FocusRestorer.nextPosition(target, mAdapter.getItemCount(), Product.getColumn())); }); } @Override public boolean onLongClick() { + mFocusRestorer.cancel(); mAdapter.setDelete(!mAdapter.isDelete()); return true; } + @Override + protected void onStop() { + mFocusRestorer.cancel(); + super.onStop(); + } + @Override protected void onBackInvoked() { + mFocusRestorer.cancel(); if (mAdapter.isDelete()) mAdapter.setDelete(false); else super.onBackInvoked(); } diff --git a/app/src/leanback/java/com/fongmi/android/tv/ui/activity/VideoActivity.java b/app/src/leanback/java/com/fongmi/android/tv/ui/activity/VideoActivity.java index 6a41a774e9..6a3bf557c2 100644 --- a/app/src/leanback/java/com/fongmi/android/tv/ui/activity/VideoActivity.java +++ b/app/src/leanback/java/com/fongmi/android/tv/ui/activity/VideoActivity.java @@ -453,6 +453,7 @@ private long mInitialPlaybackPosition = C.TIME_UNSET; private boolean tmdbHistoryResumePending; private boolean pendingLutImport; private boolean playerKernelSwitchRefreshing; + private int mPendingPlayerKernel = PlayerSetting.NONE; private final ActivityResultLauncher mLutDir = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> { if (result.getResultCode() != Activity.RESULT_OK || result.getData() == null || result.getData().getData() == null) return; @@ -1251,6 +1252,7 @@ private long mInitialPlaybackPosition = C.TIME_UNSET; SpiderDebug.log("video-flow", "service ready sinceLaunch=%dms key=%s id=%s", getLaunchCost(System.currentTimeMillis()), getKey(), getId()); player().setDanmakuController(mBinding.exo.getDanmakuController()); player().setDanmakuEnabled(DanmakuSetting.isShow()); + applyPendingPlayerKernel(); setPlayerKernel(); setDecode(); setLut(); @@ -1288,6 +1290,7 @@ private long mInitialPlaybackPosition = C.TIME_UNSET; getIntent().removeExtra(EXTRA_RESUME_HISTORY_CID); getIntent().removeExtra(EXTRA_RESUME_HISTORY_KEY); getIntent().putExtras(intent); + resetPlaybackOwnership(); setAudioStageVisible(false); restoreImmersiveAudioRequest(); resetDetailForNewIntent(); @@ -1563,7 +1566,7 @@ private long mInitialPlaybackPosition = C.TIME_UNSET; } private void setPlayer() { - mBinding.control.action.player.setText(service() == null ? ResUtil.getStringArray(R.array.select_player)[PlayerSetting.getPlayer()] : player().getPlayerText()); + mBinding.control.action.player.setText(service() == null ? ResUtil.getStringArray(R.array.select_player)[PlayerSetting.getActivePlayer()] : player().getPlayerText()); } private void setupActionButtons() { @@ -1656,6 +1659,50 @@ private long mInitialPlaybackPosition = C.TIME_UNSET; mBinding.control.action.player.setText(player().getPlayerText()); } + /** + * 起播前把内核切到本剧记住的选择,并返回该内核给取址用——取播放地址要按内核区分线路。 + * 没有记录时 getPlayerOrDefault 会退回设置页的全局默认。 + * 播放服务还没连上时先只记会话内核(取址在工作线程上读它),引擎由 onServiceConnected 补齐。 + */ + private int applyHistoryPlayerKernel() { + int kernel = mHistory == null ? PlayerSetting.getPlayer() : mHistory.getPlayerOrDefault(); + PlayerSetting.putActivePlayer(kernel); + if (service() == null) { + mPendingPlayerKernel = kernel; + return kernel; + } + mPendingPlayerKernel = PlayerSetting.NONE; + player().preparePlayer(kernel); + setPlayerKernel(); + setDecode(); + return kernel; + } + + /** + * 服务连上后补齐本页在等的内核。 + * 服务可能是上一次播放留活下来的,它建 PlayerManager 时读到的还是上一部剧的内核, + * 所以本页在服务就绪前定下的选择要在这里落到引擎上;没有待办时不动引擎。 + */ + private void applyPendingPlayerKernel() { + int kernel = mPendingPlayerKernel; + mPendingPlayerKernel = PlayerSetting.NONE; + if (!PlayerSetting.isPlayer(kernel)) return; + player().preparePlayer(kernel); + } + + /** + * 把用户刚选定的内核写回本剧历史并落盘。 + * 只在用户显式换内核时调用,且用用户选的值而不是会话/引擎状态: + * 播放页可能重叠存在(上一部剧的 Activity 还没销毁),若挂在每次存历史上, + * 上一部剧的收尾存档会用别人的会话内核覆盖本剧记住的选择; + * 而引擎类型还会被播放失败后的自动回退改掉,也不代表用户改了选择。 + */ + private void rememberPlayerKernel(int type) { + if (mHistory == null || !PlayerSetting.isPlayer(type)) return; + mHistory.setPlayer(type); + syncHistory(); + } + private void setScale(int scale) { if (mHistory != null) mHistory.setScale(scale); if (SiteApi.PUSH.equals(getKey())) PlayerSetting.putScale(scale); @@ -1819,7 +1866,7 @@ private long mInitialPlaybackPosition = C.TIME_UNSET; resetAdFeedback(); prepareFastTmdbPlaybackHistory(item, flag, episode); SpiderDebug.log("video-flow", "fast tmdb playback start cost=%dms key=%s flag=%s episode=%s url=%s", System.currentTimeMillis() - start, getKey(), flag.getFlag(), episode.getName(), episode.getUrl()); - mViewModel.playerContent(getKey(), flag.getFlag(), episode.getUrl()); + mViewModel.playerContent(getKey(), flag.getFlag(), episode.getUrl(), applyHistoryPlayerKernel()); mBinding.getRoot().post(() -> hydrateFastTmdbPlaybackDetail(item)); applyFastTmdbPlaybackFullDetailNextFrame(item); } @@ -2559,16 +2606,23 @@ private long mInitialPlaybackPosition = C.TIME_UNSET; * 含 parse=1 二次解析)。解析结果经 NovelRouter.routeReaderEngine 回传给前台阅读页。 */ @Override - public void labPlayEpisode(String chapterUrl) { - if (chapterUrl == null || chapterUrl.isEmpty()) return; + public boolean labPlayEpisode(String chapterUrl) { + if (chapterUrl == null || chapterUrl.isEmpty()) return false; + // 宿主已在销毁中:解析结果不会再回到阅读器,直接报「没发出」让它立刻收尾。 + // 另外 SiteViewModel 被清理后 playerContent 会抛 RejectedExecutionException, + // 那个异常会顺着阅读器的 runOnUiThread 冒出去导致崩溃。 + if (isFinishing() || isDestroyed()) return false; Flag flag = getFlag(); - if (flag == null || flag.getEpisodes() == null) return; + if (flag == null || flag.getEpisodes() == null) return false; for (Episode ep : flag.getEpisodes()) { if (chapterUrl.equals(ep.getUrl())) { getPlayer(flag, ep); - return; + return true; } } + // 章节不在当前线路:阅读器的章节表跨线路合并,这种情况静默返回, + // 告知调用方没有发出请求,让它立刻收尾在途标记。 + return false; } private void getPlayer(Flag flag, Episode episode) { @@ -2586,7 +2640,7 @@ private long mInitialPlaybackPosition = C.TIME_UNSET; clearLyrics(); clearKaraokeState(); if (shouldUseImmersiveAudio()) setAudioStageVisible(true); - mViewModel.playerContent(getKey(), playFlag, episode.getUrl()); + mViewModel.playerContent(getKey(), playFlag, episode.getUrl(), applyHistoryPlayerKernel()); mBinding.widget.title.setSelected(true); updateHistory(episode); showProgress(); @@ -3916,6 +3970,7 @@ private long mInitialPlaybackPosition = C.TIME_UNSET; player().switchPlayer(type); setPlayerKernel(); setDecode(); + rememberPlayerKernel(type); } private boolean onPlayerKernelLong() { @@ -3963,7 +4018,8 @@ private long mInitialPlaybackPosition = C.TIME_UNSET; if (result == null || result.hasMsg() || result.getRealUrl().isEmpty()) { Notify.show(result != null && result.hasMsg() ? result.getMsg() : getString(R.string.error_play_url)); } else { - player().switchPlayer(type, result, getHistoryKey(), metadata, isUseParse(), position, speed, repeat); + player().switchPlayer(type, result, activePlaybackKey(), metadata, isUseParse(), position, speed, repeat); + rememberPlayerKernel(type); } setPlayerKernel(); setDecode(); @@ -5076,6 +5132,23 @@ private long mInitialPlaybackPosition = C.TIME_UNSET; showPlaybackContent(); } + /** + * 加载圈的兜底收口。 + * + *

圈只在 {@code STATE_READY} 分支被收(onStateChanged),而那条回调受 isOwner() 把关。 + * 归属判定一旦因任何原因失配,圈就永久留在屏上——画面在动、圈不走。这里不依赖归属, + * 直接读播放器状态:已在播且已 READY 就收圈。要求 {@code !isEmpty()},避免详情尚未加载完 + * (播放器还空着)时把详情页自己的加载态误收。 + * + *

挂在 mR3(网速刷新,圈可见时每秒一跳)上,圈不可见时该循环本就已停,无额外开销。 + */ + private void hidePlaybackProgressIfStale() { + if (mBinding.progress.getRoot().getVisibility() != View.VISIBLE) return; + if (service() == null || player() == null || player().isReleased() || player().isEmpty()) return; + if (player().getPlaybackState() != Player.STATE_READY) return; + showPlaybackContent(); + } + @Override protected void onSeekStarted() { showProgress(); @@ -8899,6 +8972,7 @@ public void onLutSelected(LutPreset preset) { private void setTraffic() { Traffic.setSpeed(mBinding.progress.traffic, service() == null ? null : player()); + hidePlaybackProgressIfStale(); App.post(mR3, 1000); } diff --git a/app/src/leanback/java/com/fongmi/android/tv/ui/adapter/HistoryAdapter.java b/app/src/leanback/java/com/fongmi/android/tv/ui/adapter/HistoryAdapter.java index 77308ae285..f00838c36e 100644 --- a/app/src/leanback/java/com/fongmi/android/tv/ui/adapter/HistoryAdapter.java +++ b/app/src/leanback/java/com/fongmi/android/tv/ui/adapter/HistoryAdapter.java @@ -28,7 +28,7 @@ public class HistoryAdapter extends BaseDiffAdapter listener.onLongClick()); root.setOnClickListener(view -> { - if (isDelete()) listener.onItemDelete(item); + if (isDelete()) listener.onItemDelete(item, holder.getBindingAdapterPosition()); else listener.onItemClick(item); }); } @@ -78,7 +79,7 @@ public class HistoryAdapter extends BaseDiffAdapter launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> { if (result.getResultCode() != Activity.RESULT_OK || result.getData() == null || result.getData().getData() == null) return; FragmentActivity activity = requireActivity(); - String path = Objects.toString(FileChooser.getPathFromUri(result.getData().getData()), ""); - if (TextUtils.isEmpty(path)) return; + String path = Objects.toString(FileChooser.getPersistentPathFromUri(result.getData().getData()), ""); + if (TextUtils.isEmpty(path)) { + Notify.show(R.string.dialog_config_choose_failed); + return; + } App.post(() -> { if (activity.isFinishing() || activity.isDestroyed()) return; dismissAllowingStateLoss(); diff --git a/app/src/main/assets/reader.html b/app/src/main/assets/reader.html index f887494d75..7daa25659b 100644 --- a/app/src/main/assets/reader.html +++ b/app/src/main/assets/reader.html @@ -335,6 +335,15 @@ function renderContent(){ // 内容被替换 → 作废在途的恢复定位循环,并解除它设下的上报锁 restoreGen++; restoringPage = false; + // 换章即清锚点记忆:PDF 章在 pdfDoc 解析完成前 anchorTotal() 为 0, + // effectiveAnchorIndex() 会在 total<=0 处早退,不经过 currentAnchorIndex() + // 的归零短路 —— 上一章的高位值会残留下来,把新章第 1 页记成上一章的位置。 + lastAnchorIndex = 0; + // PDF 代号在这里也要自增:renderPdf() 只在新章还是 PDF 时才调用, + // 从 PDF 切到漫画时上一章的 pageSettled 仍会跑,把 pdfAppendedCount 加到 + // numPages 后调 appendChapterNav(),翻页按钮就被插到漫画第 5 张图后面。 + pdfGen++; + pdfDoc = null; pdfAppendedCount = 0; var r = document.getElementById('reader'); r.innerHTML = ''; navAppended = false; @@ -496,22 +505,34 @@ function loadMoreComic(){ /* ===================== PDF 漫画渲染(PDF.js) ===================== */ var pdfDoc = null, pdfPageIdx = 0, renderedPdfPages = {}, pdfRendering = false, pdfAppendedCount = 0; +/** PDF 渲染代号:每次换章自增,作废上一章仍在途的渲染回调。 */ +var pdfGen = 0; function renderPdf(){ var r = document.getElementById('reader'); r.innerHTML = ''; + pdfGen++; pdfDoc = null; pdfPageIdx = 0; renderedPdfPages = {}; pdfRendering = false; pdfAppendedCount = 0; if(!DATA.pdfFile){ r.innerHTML = '

未找到 PDF 文件
'; return; } if(!window.pdfjsLib){ r.innerHTML = '
PDF 组件加载失败
'; return; } showLoading(true); + // getDocument 的两个回调也必须带代号:#reader 是所有章节共用的容器, + // 上一章的 PDF 慢加载在用户已切到别章后完成/失败时,会把新章的内容整段替换掉 + // (失败分支写 pdf-error)或把旧章的 canvas 与 pdfDoc 塞进新章。 + var gen = pdfGen; pdfjsLib.getDocument(DATA.pdfFile).promise.then(function(doc){ - pdfDoc = doc; + // 先收遮罩再判代号:遮罩是全屏 z-index:10002,只有这里和首屏注入会隐藏它。 + // 放在代号判定之后,跨类型换章(PDF→漫画)时旧章的 getDocument 早退, + // 遮罩就永久盖在新章上面吞掉所有点击,只能按返回键退出。 showLoading(false); + if(gen !== pdfGen) return; + pdfDoc = doc; renderPdfMore(); // 此时才知道总页数:注入时 pdfDoc 还是 null,anchorTotal() 为 0, // 那一刻的上报会被 ReaderHistory 丢掉,所以这里补一次。 reportProgress(); }).catch(function(e){ showLoading(false); + if(gen !== pdfGen) return; // 用 textContent:本地模式下 DATA.pdfFile 是用户真实路径, // pdf.js 会把它拼进异常消息,走 innerHTML 等于把文件名当 HTML 执行。 var d = document.createElement('div'); @@ -544,15 +565,28 @@ function renderPdfPage(n){ c.style.width = '100%'; c.style.height = 'auto'; c.dataset.page = n; document.getElementById('reader').appendChild(c); + // 代号:换章会把计数清零,上一章仍在途的渲染回调若继续 ++, + // 会把新章的 pdfAppendedCount 撑到 numPages,让「一页未画」也被判成排版完成。 + var gen = pdfGen; + // 无论渲染成功还是失败都要计数:anchorsSettled() 用它判断「整章是否已排版完」, + // 少算一页就会让这一章永远无法记录成读完,进度也永远停在失败页之前。 + function pageSettled(){ + if(gen !== pdfGen) return; // 本次渲染属于已被替换的章节 + updateProgressBar(); + pdfAppendedCount++; + if(pdfDoc && pdfAppendedCount >= pdfDoc.numPages) appendChapterNav(); + } pdfDoc.getPage(n).then(function(p){ - var viewport = p.getViewport({scale:2}); - c.width = viewport.width; c.height = viewport.height; - p.render({canvasContext:c.getContext('2d'), viewport:viewport}).promise.then(function(){ - updateProgressBar(); - pdfAppendedCount++; - if(pdfDoc && pdfAppendedCount >= pdfDoc.numPages) appendChapterNav(); - }); - }); + // fulfillment 里同步抛错(getContext 返回 null、canvas 尺寸分配失败等) + // 不会被同一个 then 的 rejection 处理器捕获,必须自己兜住,否则这一页永不计数。 + try { + var viewport = p.getViewport({scale:2}); + c.width = viewport.width; c.height = viewport.height; + p.render({canvasContext:c.getContext('2d'), viewport:viewport}).promise.then(pageSettled, pageSettled); + } catch(e){ + pageSettled(); + } + }, pageSettled); } function showLoading(v){ var el = document.getElementById('loadingOverlay'); if(el) el.style.display = v ? 'flex' : 'none'; } @@ -844,18 +878,26 @@ document.getElementById('toggleScroll').addEventListener('click', toggleAuto); /* ===================== 书签功能已移除,改用 APP 内播放历史记录 ===================== */ +/** 单调毫秒时钟:不受系统时间校正影响,用于所有时长比较。 */ +function nowMs(){ + return (window.performance && performance.now) ? performance.now() : Date.now(); +} + /* ===================== 进度条 ===================== */ function updateProgressBar(){ var wrap = document.getElementById('progressBar'), fill = document.getElementById('progressFill'), text = document.getElementById('progressText'); if(!wrap || !fill || !text) return; // 与进度记录用同一套锚点,保证进度条读数和恢复位置一致 - var els = anchorEls(), total = anchorTotal(); + var total = anchorTotal(); if(total <= 0) return; wrap.style.display = 'flex'; - var loaded = 0, vh = window.innerHeight; - for(var i = 0; i < els.length; i++){ if(els[i].getBoundingClientRect().top < vh) loaded++; else break; } - var current = Math.min(total, Math.max(1, loaded)); - fill.style.width = Math.min(100, (loaded / total) * 100) + '%'; + // 读数取「当前锚点」而不是「已加载数量」:漫画首批就挂 5 张 DOM, + // 按已加载算会在刚打开时显示 5 / 95,让人以为跳到了第 5 页。 + // 例外是整章第一屏就全部露出来了,此时确实全读到了,读数给总数。 + // 判据用「最后一个锚点的底边落在视口内」,不能用 body 是否可滚动 —— + // #reader 的 min-height:105vh 让页面永远可滚动,那个判据恒为真。 + var current = Math.min(total, effectiveAnchorIndex() + 1); + fill.style.width = Math.min(100, (current / total) * 100) + '%'; text.textContent = current + ' / ' + total; } @@ -863,7 +905,7 @@ function updateProgressBar(){ var lastTap = 0; document.getElementById('reader').addEventListener('click', function(e){ e.stopPropagation(); - var now = Date.now(), delta = now - lastTap; lastTap = now; + var now = nowMs(), delta = now - lastTap; lastTap = now; if(delta > 0 && delta < 300){ if(crystalVisible){ if(panelVisible) hidePanel(); else hideCrystalOverlay(); } else showCrystalOverlay(); @@ -919,15 +961,76 @@ function anchorTotal(){ /** * 视口顶部所在的锚点序号(0 基)。 * 小说取仍露在视口内的第一段(阈值 0);漫画整页很高,取跨过视口中线的那页。 + * + * 只能用 bottom 判断,不能用 height:小说段落带 content-visibility:auto, + * 实测 getBoundingClientRect().height 恒为 0 而 bottom 有效且单调递增, + * 拿 height 当「未就绪」信号会让所有小说章的进度永远停在第 1 段。 + * + * 两道退化保护,缺一个都会把进度虚报到批次末尾(95 页漫画停在第 2 页却记成第 5 页、 + * 33 段小说刚打开就记成第 33 段): + * 1) 停在顶部时当前锚点必然是第 0 个,直接短路,不依赖任何 rect; + * 2) 没有任何锚点跨过阈值时,循环末尾的 `idx = i` 已经推到了最后一个锚点。 + * 只有锚点确已排版完(anchorsSettled)且真的滚到文末,才说明确实读到那里; + * 否则是图未解码/加载失败造成的退化测量 —— 此时文档异常地矮,轻扫就能「到底」, + * 沿用上一次可信值,既不虚报也不倒退。 */ +var lastAnchorIndex = 0; function currentAnchorIndex(){ + var scrolled = window.scrollY || window.pageYOffset || 0; + if(scrolled <= 0) return lastAnchorIndex = 0; var els = anchorEls(); var threshold = DATA.kind === 1 ? 0 : window.innerHeight * 0.5; - var idx = 0; + var idx = 0, found = false; for(var i = 0; i < els.length; i++){ - if(els[i].getBoundingClientRect().bottom > threshold){ idx = i; break; } + if(els[i].getBoundingClientRect().bottom > threshold){ idx = i; found = true; break; } idx = i; } + if(found || (anchorsSettled() && atDocumentEnd())) return lastAnchorIndex = idx; + return lastAnchorIndex; +} + +/** 是否已滚到文档末尾。单独用不可信,必须与 anchorsSettled() 一起判,详见后者注释。 */ +function atDocumentEnd(){ + return (window.scrollY || window.pageYOffset || 0) + window.innerHeight >= document.body.scrollHeight - 2; +} + +/** + * 锚点是否已真正排版完 —— 只有此时才能相信「已滚到文档末尾」这类整体判据。 + * + * 退化态下文档会异常地矮,轻扫就能满足「到底」,把没读到的内容记成读完: + * - 漫画:图加载失败/未解码时高度恒为 0,不占空间。末页有真实高度才算排版完。 + * - PDF:canvas 先按页序插进 DOM 再异步绘制,未绘制的 canvas 不是 0×0 而是固有 + * 300×150(配合 width:100% 后高约为视口宽的一半),有高度但并非真实页高, + * 所以要看真正画完的页数 pdfAppendedCount。 + * - 小说:段落受 content-visibility 影响高度恒为 0,无法据高度判断,只能认已到底。 + */ +function anchorsSettled(){ + var total = anchorTotal(); + var els = anchorEls(); + if(total <= 0 || els.length < total) return false; + if(DATA.kind === 3) return pdfDoc != null && pdfAppendedCount >= pdfDoc.numPages; + if(DATA.kind === 1) return true; + // 漫画看末尾两页:图是一批批各自异步解码的,末页并不保证最后完成 + // (体积小 / 命中缓存 / 是占位错误图时尤其容易先出来)。只看末页时, + // 用户实际停在前几页却可能被记成整章读完。 + for(var i = Math.max(0, total - 2); i < total; i++){ + if(els[i].getBoundingClientRect().height <= 0) return false; + } + return true; +} + +/** + * 落库与进度条共用的锚点序号:两边必须同一个真值,否则会出现 + * 「进度条显示 33/33、退出再进却回到第 30 段」这种读数与记录分叉。 + */ +function effectiveAnchorIndex(){ + var total = anchorTotal(); + if(total <= 0) return 0; + var idx = Math.min(total - 1, currentAnchorIndex()); // 先算,保证 memo 始终被更新 + // 已滚到文档末尾且锚点确已排版完 → 视为读完本章。 + // 不能只靠 currentAnchorIndex():小说正文下方还有 140px 内边距 + 章节导航(约 309px), + // 末段底边永远进不了视口,历史列表就永远到不了 100%。 + if(anchorsSettled() && atDocumentEnd()) return total - 1; return idx; } @@ -935,7 +1038,7 @@ function reportProgress(){ if(!window.AndroidReader || !AndroidReader.saveProgress) return; if(restoringPage || switchingChapter) return; var ch = (DATA.chapters || [])[DATA.current] || {}; - try { AndroidReader.saveProgress(DATA.current|0, ch.url || '', ch.name || DATA.title || '', currentAnchorIndex(), anchorTotal()); } catch(e){} + try { AndroidReader.saveProgress(DATA.current|0, ch.url || '', ch.name || DATA.title || '', effectiveAnchorIndex(), anchorTotal()); } catch(e){} } /** @@ -950,14 +1053,69 @@ function __restoreScroll(pos, total){ restoreAnchor(Math.round(p)); } +/** + * 用户主动触摸/滚轮/按键后立即放弃恢复。 + * + * 百分比恢复与锚点恢复都会在收敛期反复 scrollTo;漫画/PDF 慢源可能持续数秒乃至 60s。 + * 若用户开始手动阅读却继续把视口拉回旧位置,体验等同于页面卡死。用户交互的当前位置 + * 比旧记录优先,作废循环、解锁上报,让下一次 scroll debounce 写入用户真实位置。 + */ +function cancelRestoreForUser(){ + if(!restoringPage) return; + restoreGen++; + restoringPage = false; + updateProgressBar(); + reportProgress(); +} +window.addEventListener('touchstart', cancelRestoreForUser, {passive:true}); +window.addEventListener('pointerdown', cancelRestoreForUser, {passive:true}); +window.addEventListener('wheel', cancelRestoreForUser, {passive:true}); +window.addEventListener('keydown', function(e){ + if(e.key === 'ArrowUp' || e.key === 'ArrowDown' || e.key === 'PageUp' || e.key === 'PageDown' || e.key === ' ') cancelRestoreForUser(); +}); + /** 旧记录兼容:按章节内滚动百分比定位。 */ function restoreScrollPercent(p){ - var tries = 0; + // 代号:内容一旦被替换(切章 / 重新注入),本次恢复立即作废, + // 否则它会继续对新章 scrollTo,并把新章的进度按旧百分比写掉。 + var gen = ++restoreGen; + restoringPage = true; + // 预算给足:漫画要一批批(BATCH 张)催到全部进 DOM 才算排版完,20 次×100ms 不够 + var deadline = nowMs() + 60000; + var lastMax = null, stable = 0; (function seek(){ + if(gen !== restoreGen) return; + // 小说的 content-visibility 估算高度在用户滚动前根本不变,所以「高度稳定」 + // 对它是空护栏(首帧即稳定)。真正的判据是「按目标百分比滚过去之后, + // 换算回来的锚点位置也稳定下来」—— 与 restoreAnchor 一样先滚再收敛。 var max = document.body.scrollHeight - window.innerHeight; - if(max <= 0 && tries++ < 20){ setTimeout(seek, 100); return; } - window.scrollTo(0, max * p); + if(max > 0) window.scrollTo(0, max * p); + var idx = effectiveAnchorIndex(); + var settled = anchorTotal() > 0 && anchorsSettled(); + if(!settled || lastMax === null || lastMax !== idx) stable = 0; + else stable++; + lastMax = idx; + if(stable < 3 && nowMs() < deadline){ + // 漫画 / PDF 要主动催加载:光等不会让剩下的页自己进 DOM, + // anchorsSettled() 就永远为假,旧百分比记录既恢复不了也迁移不了。 + if(DATA.kind === 3) renderPdfMore(); + else if(DATA.kind !== 1) loadMoreComic(); + setTimeout(seek, 60); + return; + } + var ready = stable >= 3; + // 必须解锁:__injectReader 在 DATA.restore 时设了 restoringPage, + // 这条旧记录分支不解锁的话整个会话都不再上报进度,旧记录也永远迁不到新语义。 + restoringPage = false; updateProgressBar(); + // 迁移旧记录时不能盲目上报:短章内容一屏放得下时,滚到 max*p(min-height 撑出的 + // 约 5vh)后当前锚点仍是第 0 个,上报等于把用户存的 90% 覆盖成章首。 + // 只有换算出的锚点不比原百分比对应的位置更靠前,才是一次有意义的迁移。 + if(ready){ + var total = anchorTotal(); + var expected = Math.min(total - 1, Math.floor(p * total)); + if(effectiveAnchorIndex() >= expected) reportProgress(); + } })(); } @@ -973,7 +1131,9 @@ function restoreAnchor(index){ // 代号:内容一旦被替换(切章 / 重新注入),旧的 seek 循环立即作废。 // 否则它会继续对新章执行 scrollTo,并让 restoringPage 一直为真,堵住进度上报。 var gen = ++restoreGen; - var deadline = Date.now() + 60000; // 总预算 60s:远程漫画一批批加载到第 N 页很慢 + // 用 performance.now():Date.now() 会被系统时间校正影响,向前跳会立刻超时(位置恢复不了), + // 向后跳会让循环跑得远超预算。 + var deadline = nowMs() + 60000; // 总预算 60s:远程漫画一批批加载到第 N 页很慢 var lastTop = null, stable = 0; /** 目标页之前尚未撑开高度(未解码)的页数。 */ @@ -985,12 +1145,15 @@ function restoreAnchor(index){ (function seek(){ if(gen !== restoreGen) return; // 内容已被替换,本次恢复作废 - if(Date.now() > deadline){ + if(nowMs() > deadline){ // 超时:停在当前位置,不再纠正(此时至少已滚到已加载部分的目标附近) console.log('[reader] restoreAnchor timeout index=' + index); restoringPage = false; updateProgressBar(); - reportProgress(); + // 只有确实到达(或超过)目标锚点才补报。部分加载时 seek 只能滚到已加载末尾, + // 此刻上报会把「存第 50 页」倒退成「第 9 页」;一次都没滚动成功时更是直接清成开头。 + // 不报的代价仅是本次不刷新记录,用户存的位置原样保留。 + if(effectiveAnchorIndex() >= index) reportProgress(); return; } var els = anchorEls(); diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt new file mode 100644 index 0000000000..01beec0a99 --- /dev/null +++ b/app/src/main/cpp/CMakeLists.txt @@ -0,0 +1,52 @@ +cmake_minimum_required(VERSION 3.22.1) + +project(exo_dovi_renderer LANGUAGES CXX) + +add_library(exo_dovi_renderer SHARED exo_dovi_renderer.cpp) + +set(EXO_DV5_NATIVE_ROOT + "${CMAKE_CURRENT_LIST_DIR}/../../../../third_party/exo-dv5-native") +set(EXO_DV5_NATIVE_LIB_DIR + "${EXO_DV5_NATIVE_ROOT}/prebuilt/${ANDROID_ABI}") + +add_library(exo_dv5_placebo STATIC IMPORTED) +set_target_properties(exo_dv5_placebo PROPERTIES + IMPORTED_LOCATION "${EXO_DV5_NATIVE_LIB_DIR}/libplacebo.a") + +add_library(exo_dv5_shaderc STATIC IMPORTED) +set_target_properties(exo_dv5_shaderc PROPERTIES + IMPORTED_LOCATION "${EXO_DV5_NATIVE_LIB_DIR}/libshaderc.a") + +add_library(exo_dv5_dovi STATIC IMPORTED) +set_target_properties(exo_dv5_dovi PROPERTIES + IMPORTED_LOCATION "${EXO_DV5_NATIVE_LIB_DIR}/libdovi.a") + +target_compile_features(exo_dovi_renderer PRIVATE cxx_std_20) +target_compile_options(exo_dovi_renderer PRIVATE + -fvisibility=hidden + -fvisibility-inlines-hidden) +target_compile_definitions(exo_dovi_renderer PRIVATE + PL_STATIC + PL_HAVE_PTHREAD + PTHREAD_HAS_SETCLOCK) +target_include_directories(exo_dovi_renderer PRIVATE + "${EXO_DV5_NATIVE_ROOT}/include") +target_link_options(exo_dovi_renderer PRIVATE -Wl,--no-undefined) + +find_library(android-lib android REQUIRED) +find_library(log-lib log REQUIRED) +find_library(media-ndk-lib mediandk REQUIRED) +find_library(vulkan-lib vulkan REQUIRED) +find_library(dl-lib dl REQUIRED) +find_library(m-lib m REQUIRED) + +target_link_libraries(exo_dovi_renderer PRIVATE + exo_dv5_placebo + exo_dv5_shaderc + exo_dv5_dovi + ${android-lib} + ${log-lib} + ${media-ndk-lib} + ${vulkan-lib} + ${dl-lib} + ${m-lib}) diff --git a/app/src/main/cpp/exo_dovi_renderer.cpp b/app/src/main/cpp/exo_dovi_renderer.cpp new file mode 100644 index 0000000000..d8c33fffa7 --- /dev/null +++ b/app/src/main/cpp/exo_dovi_renderer.cpp @@ -0,0 +1,1251 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr int kMaxImages = 4; +constexpr size_t kMaxExpectedFrames = 256; +constexpr size_t kMaxPendingRpus = 256; +constexpr int64_t kTimestampMatchToleranceNs = 2'000'000; + +constexpr jint kCapabilityImageReader = 1 << 0; +constexpr jint kCapabilityVulkan12 = 1 << 1; +constexpr jint kCapabilityAhbImport = 1 << 2; +constexpr jint kCapabilityYcbcrConversion = 1 << 3; +constexpr jint kCapabilityForeignQueue = 1 << 4; +constexpr jint kCapabilityLibplacebo375 = 1 << 5; +constexpr jint kCapabilityLibdovi = 1 << 6; + +struct ExpectedFrame { + int64_t imageTimestampNs; + int64_t presentationTimeUs; +}; + +struct RpuMetadata { + int64_t presentationTimeUs; + pl_dovi_metadata dovi; + bool hasMapping = false; + bool hasColor = false; + bool fullRange = true; + bool hasSourceLuma = false; + float sourceMinPq = 0.0f; + float sourceMaxPq = 0.0f; + bool updatesSceneLuma = false; + bool hasSceneLuma = false; + float sceneMaxPq = 0.0f; + float sceneAvgPq = 0.0f; +}; + +struct Renderer { + AImageReader *reader = nullptr; + ANativeWindow *outputWindow = nullptr; + pl_log log = nullptr; + pl_vk_inst vkInstance = nullptr; + pl_vulkan vulkan = nullptr; + pl_swapchain swapchain = nullptr; + pl_renderer renderer = nullptr; + VkSurfaceKHR outputSurface = VK_NULL_HANDLE; + int outputWidth = 0; + int outputHeight = 0; + std::mutex renderMutex; + std::mutex callbackMutex; + std::mutex expectedMutex; + std::mutex rpuMutex; + std::deque expectedFrames; + std::atomic acquiredFrames{0}; + std::atomic ahbFrames{0}; + std::atomic sampledUsageFrames{0}; + std::atomic highDepthFrames{0}; + std::atomic matchedFrames{0}; + std::atomic unmatchedFrames{0}; + std::atomic expectedQueueDrops{0}; + std::atomic lastImageTimestampNs{0}; + std::atomic lastPresentationTimeUs{0}; + std::atomic lastAhbFormat{0}; + std::atomic parsedRpus{0}; + std::atomic malformedRpus{0}; + std::atomic rpuQueueDrops{0}; + std::atomic metadataLogs{0}; + std::atomic inputFormatLogs{0}; + std::atomic renderedFrames{0}; + std::atomic renderFailures{0}; + std::atomic colorPipelineLogs{0}; + std::deque pendingRpus; + bool hasLastDovi = false; + pl_dovi_metadata lastDovi{}; + bool lastFullRange = true; + bool hasSourceLuma = false; + float sourceMinPq = 0.0f; + float sourceMaxPq = 0.0f; + bool hasSceneLuma = false; + float sceneMaxPq = 0.0f; + float sceneAvgPq = 0.0f; +}; + +void placeboLog(void *, enum pl_log_level level, const char *message) { + int priority = ANDROID_LOG_INFO; + if (level <= PL_LOG_ERR) priority = ANDROID_LOG_ERROR; + else if (level == PL_LOG_WARN) priority = ANDROID_LOG_WARN; + __android_log_print(priority, "ExoDv5", "%s", message == nullptr ? "" : message); +} + +bool destroyVulkan(Renderer *renderer); +void resetDoviMetadata(pl_dovi_metadata *metadata); + +bool ensureVulkan(Renderer *renderer) { + if (renderer->swapchain != nullptr && renderer->renderer != nullptr) return true; + if (renderer->outputWindow == nullptr) return false; + std::lock_guard renderLock(renderer->renderMutex); + if (renderer->swapchain != nullptr && renderer->renderer != nullptr) { + return true; + } + pl_log_params logParams{ + .log_cb = placeboLog, + .log_priv = nullptr, + .log_level = PL_LOG_ERR, + }; + renderer->log = pl_log_create(PL_API_VER, &logParams); + if (renderer->log == nullptr) return false; + const char *instanceExtensions[] = {VK_KHR_ANDROID_SURFACE_EXTENSION_NAME}; + pl_vk_inst_params instanceParams{}; + instanceParams.max_api_version = VK_API_VERSION_1_2; + instanceParams.get_proc_addr = vkGetInstanceProcAddr; + instanceParams.extensions = instanceExtensions; + instanceParams.num_extensions = 1; + renderer->vkInstance = pl_vk_inst_create(renderer->log, &instanceParams); + if (renderer->vkInstance == nullptr) { + pl_log_destroy(&renderer->log); + return false; + } + auto createSurface = reinterpret_cast( + vkGetInstanceProcAddr(renderer->vkInstance->instance, + "vkCreateAndroidSurfaceKHR")); + if (createSurface == nullptr) { + pl_vk_inst_destroy(&renderer->vkInstance); + pl_log_destroy(&renderer->log); + return false; + } + VkAndroidSurfaceCreateInfoKHR surfaceInfo{}; + surfaceInfo.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR; + surfaceInfo.window = renderer->outputWindow; + if (createSurface(renderer->vkInstance->instance, &surfaceInfo, nullptr, + &renderer->outputSurface) != VK_SUCCESS) { + pl_vk_inst_destroy(&renderer->vkInstance); + pl_log_destroy(&renderer->log); + return false; + } + pl_vulkan_params vulkanParams = pl_vulkan_default_params; + vulkanParams.instance = renderer->vkInstance->instance; + vulkanParams.get_proc_addr = vkGetInstanceProcAddr; + vulkanParams.surface = renderer->outputSurface; + // AHardwareBuffer import is used for every decoded DV5 frame. The + // capability probe enables these extensions explicitly; the real device + // must use the same contract or vkGetAndroidHardwareBufferPropertiesANDROID + // is unavailable and rendering fails before image import. + const char *deviceExtensions[] = { + VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME, + VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME, + }; + vulkanParams.extensions = deviceExtensions; + vulkanParams.num_extensions = std::size(deviceExtensions); + vulkanParams.async_transfer = false; + vulkanParams.async_compute = false; + vulkanParams.queue_count = 1; + renderer->vulkan = pl_vulkan_create(renderer->log, &vulkanParams); + if (renderer->vulkan == nullptr) { + vkDestroySurfaceKHR(renderer->vkInstance->instance, + renderer->outputSurface, nullptr); + renderer->outputSurface = VK_NULL_HANDLE; + pl_vk_inst_destroy(&renderer->vkInstance); + pl_log_destroy(&renderer->log); + return false; + } + pl_vulkan_swapchain_params swapchainParams{}; + swapchainParams.surface = renderer->outputSurface; + swapchainParams.present_mode = VK_PRESENT_MODE_FIFO_KHR; + swapchainParams.swapchain_depth = 2; + swapchainParams.color_bits = 10; + renderer->swapchain = pl_vulkan_create_swapchain( + renderer->vulkan, &swapchainParams); + renderer->renderer = pl_renderer_create(renderer->log, renderer->vulkan->gpu); + if (renderer->swapchain == nullptr || renderer->renderer == nullptr) { + if (renderer->renderer != nullptr) pl_renderer_destroy(&renderer->renderer); + if (renderer->swapchain != nullptr) pl_swapchain_destroy(&renderer->swapchain); + pl_vulkan_destroy(&renderer->vulkan); + vkDestroySurfaceKHR(renderer->vkInstance->instance, + renderer->outputSurface, nullptr); + renderer->outputSurface = VK_NULL_HANDLE; + pl_vk_inst_destroy(&renderer->vkInstance); + pl_log_destroy(&renderer->log); + return false; + } + renderer->outputWidth = 0; + renderer->outputHeight = 0; + return true; +} + +uint32_t findMemoryType(pl_vulkan vulkan, uint32_t typeBits) { + VkPhysicalDeviceMemoryProperties properties{}; + vkGetPhysicalDeviceMemoryProperties(vulkan->phys_device, &properties); + for (uint32_t i = 0; i < properties.memoryTypeCount; i++) { + if ((typeBits & (uint32_t{1} << i)) != 0 + && (properties.memoryTypes[i].propertyFlags + & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != 0) return i; + } + for (uint32_t i = 0; i < properties.memoryTypeCount; i++) { + if ((typeBits & (uint32_t{1} << i)) != 0) return i; + } + return UINT32_MAX; +} + +bool renderImage(Renderer *renderer, AImage *image, int64_t ptsUs) { + if (!ensureVulkan(renderer)) { + __android_log_print(ANDROID_LOG_ERROR, "ExoDv5", + "render failed stage=ensure-vulkan ptsUs=%" PRId64, + ptsUs); + return false; + } + AHardwareBuffer *buffer = nullptr; + if (AImage_getHardwareBuffer(image, &buffer) != AMEDIA_OK || buffer == nullptr) { + __android_log_print(ANDROID_LOG_ERROR, "ExoDv5", + "render failed stage=get-ahb ptsUs=%" PRId64, + ptsUs); + return false; + } + AHardwareBuffer_Desc desc{}; + AHardwareBuffer_describe(buffer, &desc); + VkAndroidHardwareBufferFormatPropertiesANDROID formatProps{}; + formatProps.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID; + VkAndroidHardwareBufferPropertiesANDROID bufferProps{}; + bufferProps.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID; + bufferProps.pNext = &formatProps; + auto getProperties = reinterpret_cast( + vkGetDeviceProcAddr(renderer->vulkan->device, + "vkGetAndroidHardwareBufferPropertiesANDROID")); + VkResult vkResult = getProperties == nullptr + ? VK_ERROR_EXTENSION_NOT_PRESENT + : getProperties(renderer->vulkan->device, buffer, &bufferProps); + if (vkResult != VK_SUCCESS) { + __android_log_print(ANDROID_LOG_ERROR, "ExoDv5", + "render failed stage=get-ahb-properties result=%d " + "ptsUs=%" PRId64 " ahbFormat=%u usage=0x%" PRIx64, + vkResult, ptsUs, desc.format, desc.usage); + return false; + } + if (formatProps.format == VK_FORMAT_UNDEFINED && formatProps.externalFormat == 0) { + __android_log_print(ANDROID_LOG_ERROR, "ExoDv5", + "render failed stage=missing-vulkan-format ptsUs=%" PRId64 + " ahbFormat=%u usage=0x%" PRIx64, + ptsUs, desc.format, desc.usage); + return false; + } + const int inputFormatLog = renderer->inputFormatLogs.fetch_add( + 1, std::memory_order_relaxed); + if (inputFormatLog < 2) { + __android_log_print( + ANDROID_LOG_INFO, "ExoDv5", + "input format ahb=%u usage=0x%" PRIx64 + " vkFormat=%d external=%" PRIu64 + " model=%d range=%d components=%d/%d/%d/%d" + " chroma=%d/%d features=0x%" PRIx64 + " sourceMap=%d/%d/%d", + desc.format, desc.usage, formatProps.format, + formatProps.externalFormat, + static_cast(formatProps.suggestedYcbcrModel), + static_cast(formatProps.suggestedYcbcrRange), + static_cast(formatProps.samplerYcbcrConversionComponents.r), + static_cast(formatProps.samplerYcbcrConversionComponents.g), + static_cast(formatProps.samplerYcbcrConversionComponents.b), + static_cast(formatProps.samplerYcbcrConversionComponents.a), + static_cast(formatProps.suggestedXChromaOffset), + static_cast(formatProps.suggestedYChromaOffset), + static_cast(formatProps.formatFeatures), + PL_CHANNEL_CR, PL_CHANNEL_Y, PL_CHANNEL_CB); + } + VkExternalFormatANDROID externalFormat{ + .sType = VK_STRUCTURE_TYPE_EXTERNAL_FORMAT_ANDROID, + .pNext = nullptr, + .externalFormat = formatProps.externalFormat, + }; + VkExternalMemoryImageCreateInfo externalMemory{ + .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO, + .pNext = formatProps.externalFormat != 0 ? &externalFormat : nullptr, + .handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID, + }; + VkImageCreateInfo imageInfo{}; + imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + imageInfo.pNext = &externalMemory; + imageInfo.imageType = VK_IMAGE_TYPE_2D; + imageInfo.format = formatProps.externalFormat != 0 + ? VK_FORMAT_UNDEFINED : formatProps.format; + imageInfo.extent = {desc.width, desc.height, 1}; + imageInfo.mipLevels = 1; + imageInfo.arrayLayers = 1; + imageInfo.samples = VK_SAMPLE_COUNT_1_BIT; + imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL; + imageInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT; + imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + VkImage vkImage = VK_NULL_HANDLE; + VkDeviceMemory memory = VK_NULL_HANDLE; + pl_tex texture = nullptr; + bool frameStarted = false; + bool submitted = false; + pl_swapchain_frame swapFrame{}; + pl_frame target{}; + pl_frame source{}; + pl_vulkan_ycbcr_params ycbcr{}; + pl_vulkan_wrap_params wrapParams{}; + pl_vulkan_release_params releaseParams{}; + pl_vulkan_hold_params holdParams{}; + VkSemaphore releaseSemaphore = VK_NULL_HANDLE; + pl_vulkan_sem_params semaphoreParams{}; + VkImportAndroidHardwareBufferInfoANDROID importInfo{}; + VkMemoryDedicatedAllocateInfo dedicatedInfo{}; + VkMemoryAllocateInfo allocInfo{}; + uint32_t memoryType = UINT32_MAX; + int width = static_cast(desc.width); + int height = static_cast(desc.height); + bool rendered = false; + bool imageReleased = false; + bool imageHeld = false; + int colorLog = 0; + size_t pendingRpuCount = 0; + const char *failureStage = "vk-create-image"; + vkResult = vkCreateImage(renderer->vulkan->device, &imageInfo, nullptr, &vkImage); + if (vkResult != VK_SUCCESS) goto cleanup; + failureStage = "find-memory-type"; + memoryType = findMemoryType(renderer->vulkan, bufferProps.memoryTypeBits); + if (memoryType == UINT32_MAX) goto cleanup; + importInfo.sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID; + importInfo.buffer = buffer; + dedicatedInfo.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO; + dedicatedInfo.pNext = &importInfo; + dedicatedInfo.image = vkImage; + allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + allocInfo.pNext = &dedicatedInfo; + allocInfo.allocationSize = bufferProps.allocationSize; + allocInfo.memoryTypeIndex = memoryType; + failureStage = "vk-allocate-memory"; + vkResult = vkAllocateMemory(renderer->vulkan->device, &allocInfo, nullptr, &memory); + if (vkResult != VK_SUCCESS) goto cleanup; + failureStage = "vk-bind-image-memory"; + vkResult = vkBindImageMemory(renderer->vulkan->device, vkImage, memory, 0); + if (vkResult != VK_SUCCESS) goto cleanup; + failureStage = "sampled-format-feature"; + if ((formatProps.formatFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) == 0) { + goto cleanup; + } + failureStage = "create-release-semaphore"; + semaphoreParams.type = VK_SEMAPHORE_TYPE_BINARY; + releaseSemaphore = pl_vulkan_sem_create( + renderer->vulkan->gpu, &semaphoreParams); + if (releaseSemaphore == VK_NULL_HANDLE) goto cleanup; + ycbcr.external_format = formatProps.externalFormat; + ycbcr.components = formatProps.samplerYcbcrConversionComponents; + ycbcr.model = VK_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY; + ycbcr.range = VK_SAMPLER_YCBCR_RANGE_ITU_FULL; + ycbcr.x_chroma_offset = formatProps.suggestedXChromaOffset; + ycbcr.y_chroma_offset = formatProps.suggestedYChromaOffset; + ycbcr.chroma_filter = + (formatProps.formatFeatures + & VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT) + != 0 + ? VK_FILTER_LINEAR : VK_FILTER_NEAREST; + ycbcr.separate_reconstruction_filter = + (formatProps.formatFeatures + & VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT) + != 0; + ycbcr.sample_depth = 10; + wrapParams.image = vkImage; + wrapParams.width = static_cast(desc.width); + wrapParams.height = static_cast(desc.height); + wrapParams.format = formatProps.externalFormat != 0 + ? VK_FORMAT_UNDEFINED : formatProps.format; + wrapParams.usage = VK_IMAGE_USAGE_SAMPLED_BIT; + wrapParams.ycbcr = &ycbcr; + failureStage = "pl-vulkan-wrap"; + texture = pl_vulkan_wrap(renderer->vulkan->gpu, &wrapParams); + if (texture == nullptr) goto cleanup; + releaseParams.tex = texture; + releaseParams.layout = VK_IMAGE_LAYOUT_GENERAL; + releaseParams.qf = VK_QUEUE_FAMILY_FOREIGN_EXT; + pl_vulkan_release_ex(renderer->vulkan->gpu, &releaseParams); + imageReleased = true; + { + std::lock_guard rpuLock(renderer->rpuMutex); + while (!renderer->pendingRpus.empty() + && renderer->pendingRpus.front().presentationTimeUs <= ptsUs) { + const RpuMetadata &metadata = renderer->pendingRpus.front(); + if (!renderer->hasLastDovi && !metadata.hasMapping) { + renderer->pendingRpus.pop_front(); + continue; + } + if (!renderer->hasLastDovi) { + resetDoviMetadata(&renderer->lastDovi); + // Profile 5 uses the fixed IPT-PQ conversion below when an + // RPU carries no explicit (or carries compressed) DM block. + renderer->lastDovi.nonlinear.m[0][0] = 8192.0f / 8192.0f; + renderer->lastDovi.nonlinear.m[0][1] = 799.0f / 8192.0f; + renderer->lastDovi.nonlinear.m[0][2] = 1681.0f / 8192.0f; + renderer->lastDovi.nonlinear.m[1][0] = 8192.0f / 8192.0f; + renderer->lastDovi.nonlinear.m[1][1] = -933.0f / 8192.0f; + renderer->lastDovi.nonlinear.m[1][2] = 1091.0f / 8192.0f; + renderer->lastDovi.nonlinear.m[2][0] = 8192.0f / 8192.0f; + renderer->lastDovi.nonlinear.m[2][1] = 267.0f / 8192.0f; + renderer->lastDovi.nonlinear.m[2][2] = -5545.0f / 8192.0f; + renderer->lastDovi.linear.m[0][0] = 17081.0f / 16384.0f; + renderer->lastDovi.linear.m[0][1] = -349.0f / 16384.0f; + renderer->lastDovi.linear.m[0][2] = -349.0f / 16384.0f; + renderer->lastDovi.linear.m[1][0] = -349.0f / 16384.0f; + renderer->lastDovi.linear.m[1][1] = 17081.0f / 16384.0f; + renderer->lastDovi.linear.m[1][2] = -349.0f / 16384.0f; + renderer->lastDovi.linear.m[2][0] = -349.0f / 16384.0f; + renderer->lastDovi.linear.m[2][1] = -349.0f / 16384.0f; + renderer->lastDovi.linear.m[2][2] = 17081.0f / 16384.0f; + renderer->lastDovi.nonlinear_offset[0] = 0.0f; + renderer->lastDovi.nonlinear_offset[1] = 0.5f; + renderer->lastDovi.nonlinear_offset[2] = 0.5f; + renderer->hasLastDovi = true; + renderer->hasSourceLuma = true; + renderer->sourceMinPq = 62.0f / 4095.0f; + renderer->sourceMaxPq = 3696.0f / 4095.0f; + } + if (metadata.hasMapping) { + for (int c = 0; c < 3; c++) { + renderer->lastDovi.comp[c] = metadata.dovi.comp[c]; + } + } + if (metadata.hasColor) { + memcpy(renderer->lastDovi.nonlinear_offset, + metadata.dovi.nonlinear_offset, + sizeof(renderer->lastDovi.nonlinear_offset)); + renderer->lastDovi.nonlinear = metadata.dovi.nonlinear; + renderer->lastDovi.linear = metadata.dovi.linear; + } + renderer->lastFullRange = metadata.fullRange; + if (metadata.hasSourceLuma) { + renderer->hasSourceLuma = true; + renderer->sourceMinPq = metadata.sourceMinPq; + renderer->sourceMaxPq = metadata.sourceMaxPq; + } + if (metadata.updatesSceneLuma) { + renderer->hasSceneLuma = metadata.hasSceneLuma; + renderer->sceneMaxPq = metadata.sceneMaxPq; + renderer->sceneAvgPq = metadata.sceneAvgPq; + } + renderer->pendingRpus.pop_front(); + } + pendingRpuCount = renderer->pendingRpus.size(); + } + failureStage = "missing-rpu"; + if (!renderer->hasLastDovi) goto cleanup; + source.num_planes = 1; + source.planes[0].texture = texture; + source.planes[0].components = 3; + source.planes[0].component_mapping[0] = PL_CHANNEL_CR; + source.planes[0].component_mapping[1] = PL_CHANNEL_Y; + source.planes[0].component_mapping[2] = PL_CHANNEL_CB; + source.repr.sys = PL_COLOR_SYSTEM_DOLBYVISION; + source.repr.levels = renderer->lastFullRange + ? PL_COLOR_LEVELS_FULL : PL_COLOR_LEVELS_LIMITED; + source.repr.bits.sample_depth = 10; + source.repr.bits.color_depth = 10; + source.repr.dovi = &renderer->lastDovi; + source.color.primaries = PL_COLOR_PRIM_BT_2020; + source.color.transfer = PL_COLOR_TRC_PQ; + if (renderer->hasSourceLuma) { + source.color.hdr.min_luma = pl_hdr_rescale( + PL_HDR_PQ, PL_HDR_NITS, renderer->sourceMinPq); + source.color.hdr.max_luma = pl_hdr_rescale( + PL_HDR_PQ, PL_HDR_NITS, renderer->sourceMaxPq); + } + if (renderer->hasSceneLuma) { + source.color.hdr.max_pq_y = renderer->sceneMaxPq; + source.color.hdr.avg_pq_y = renderer->sceneAvgPq; + } + source.crop = {0, 0, static_cast(desc.width), static_cast(desc.height)}; + // Keep this compatibility path on an explicit SDR swapchain. Advertising + // the 4000-nit source as the target bypasses libplacebo output tone mapping + // and leaves the result dependent on Android's child-surface HDR handling. + // Apply the per-frame DV reshape above, then tone-map into the stable + // sRGB/BT.709 output contract here. + pl_swapchain_colorspace_hint(renderer->swapchain, &pl_color_space_srgb); + failureStage = "swapchain-resize"; + if (!pl_swapchain_resize(renderer->swapchain, &width, &height)) goto cleanup; + failureStage = "swapchain-start-frame"; + if (!pl_swapchain_start_frame(renderer->swapchain, &swapFrame)) goto cleanup; + frameStarted = true; + pl_frame_from_swapchain(&target, &swapFrame); + colorLog = renderer->colorPipelineLogs.fetch_add( + 1, std::memory_order_relaxed); + if (colorLog < 4) { + __android_log_print( + ANDROID_LOG_INFO, "ExoDv5", + "color pipeline source=%d/%d %.3f/%.1f target=%d/%d %.3f/%.1f bits=%d", + source.color.primaries, source.color.transfer, + source.color.hdr.min_luma, source.color.hdr.max_luma, + target.color.primaries, target.color.transfer, + target.color.hdr.min_luma, target.color.hdr.max_luma, + target.repr.bits.color_depth); + } + failureStage = "pl-render-image"; + rendered = pl_render_image(renderer->renderer, &source, &target, nullptr); + if (!rendered) goto cleanup; + failureStage = "swapchain-submit-frame"; + submitted = pl_swapchain_submit_frame(renderer->swapchain); + frameStarted = false; + if (!submitted) goto cleanup; + if (submitted) pl_swapchain_swap_buffers(renderer->swapchain); + pl_gpu_finish(renderer->vulkan->gpu); + holdParams.tex = texture; + holdParams.layout = VK_IMAGE_LAYOUT_GENERAL; + holdParams.qf = VK_QUEUE_FAMILY_FOREIGN_EXT; + holdParams.semaphore = pl_vulkan_sem{.sem = releaseSemaphore, .value = 0}; + failureStage = "pl-vulkan-hold"; + if (!pl_vulkan_hold_ex(renderer->vulkan->gpu, &holdParams)) goto cleanup; + imageHeld = true; + // The semaphore is consumed by the hold operation. Wait for the queue + // transition before returning the AImage to its BufferQueue. + pl_gpu_finish(renderer->vulkan->gpu); + pl_vulkan_sem_destroy(renderer->vulkan->gpu, &releaseSemaphore); + pl_tex_destroy(renderer->vulkan->gpu, &texture); + vkDestroyImage(renderer->vulkan->device, vkImage, nullptr); + vkFreeMemory(renderer->vulkan->device, memory, nullptr); + return submitted; + +cleanup: + __android_log_print( + ANDROID_LOG_ERROR, "ExoDv5", + "render failed stage=%s result=%d ptsUs=%" PRId64 + " ahb=%ux%u format=%u usage=0x%" PRIx64 + " vkFormat=%d externalFormat=%" PRIu64 + " formatFeatures=0x%" PRIx64 + " hasRpu=%d parsedRpu=%" PRId64 + " malformedRpu=%" PRId64 " pendingRpu=%zu", + failureStage, vkResult, ptsUs, desc.width, desc.height, + desc.format, desc.usage, formatProps.format, + formatProps.externalFormat, + static_cast(formatProps.formatFeatures), + renderer->hasLastDovi ? 1 : 0, + renderer->parsedRpus.load(std::memory_order_relaxed), + renderer->malformedRpus.load(std::memory_order_relaxed), + pendingRpuCount); + if (frameStarted) { + pl_swapchain_submit_frame(renderer->swapchain); + pl_gpu_finish(renderer->vulkan->gpu); + } + if (texture != nullptr) { + if (imageReleased && !imageHeld) { + // Reclaim ownership before destroying a wrapper that was handed + // to libplacebo. The normal path always succeeds here; retaining + // the explicit attempt keeps failure cleanup deterministic. + holdParams.tex = texture; + holdParams.layout = VK_IMAGE_LAYOUT_GENERAL; + holdParams.qf = VK_QUEUE_FAMILY_FOREIGN_EXT; + holdParams.semaphore = pl_vulkan_sem{ + .sem = releaseSemaphore, + .value = 0, + }; + if (pl_vulkan_hold_ex(renderer->vulkan->gpu, &holdParams)) { + imageHeld = true; + pl_gpu_finish(renderer->vulkan->gpu); + } + } + pl_tex_destroy(renderer->vulkan->gpu, &texture); + } + if (releaseSemaphore != VK_NULL_HANDLE) { + pl_gpu_finish(renderer->vulkan->gpu); + pl_vulkan_sem_destroy(renderer->vulkan->gpu, &releaseSemaphore); + } + if (vkImage != VK_NULL_HANDLE) vkDestroyImage(renderer->vulkan->device, vkImage, nullptr); + if (memory != VK_NULL_HANDLE) vkFreeMemory(renderer->vulkan->device, memory, nullptr); + return false; +} + +bool destroyVulkan(Renderer *renderer) { + std::lock_guard lock(renderer->renderMutex); + if (renderer->vulkan != nullptr) pl_gpu_finish(renderer->vulkan->gpu); + if (renderer->renderer != nullptr) pl_renderer_destroy(&renderer->renderer); + if (renderer->swapchain != nullptr) pl_swapchain_destroy(&renderer->swapchain); + if (renderer->vulkan != nullptr) pl_vulkan_destroy(&renderer->vulkan); + if (renderer->vkInstance != nullptr && renderer->outputSurface != VK_NULL_HANDLE) { + vkDestroySurfaceKHR(renderer->vkInstance->instance, + renderer->outputSurface, nullptr); + } + renderer->outputSurface = VK_NULL_HANDLE; + if (renderer->vkInstance != nullptr) pl_vk_inst_destroy(&renderer->vkInstance); + if (renderer->log != nullptr) pl_log_destroy(&renderer->log); + return true; +} + +void resetDoviMetadata(pl_dovi_metadata *metadata) { + memset(metadata, 0, sizeof(*metadata)); + metadata->nonlinear = pl_matrix3x3_identity; + metadata->linear = pl_matrix3x3_identity; +} + +float fixedCoefficient(int64_t integer, uint64_t fraction, uint64_t denom) { + const double scale = denom >= 63 + ? 9223372036854775808.0 + : static_cast(uint64_t{1} << denom); + return static_cast(static_cast(integer) + + static_cast(fraction) / scale); +} + +void mapRpuCurve(pl_dovi_metadata::pl_reshape_data *dst, + const DoviReshapingCurve &src, + const DoviRpuDataHeader &header) { + const size_t pivotCount = std::min(9, src.pivots.len); + dst->num_pivots = static_cast(pivotCount); + uint64_t blBits = std::min(23, header.bl_bit_depth_minus8 + 8); + const uint64_t maxPivot = (uint64_t{1} << blBits) - 1; + const float pivotScale = 1.0f / static_cast(maxPivot); + uint64_t pivot = 0; + for (size_t i = 0; i < pivotCount; i++) { + // RPU pred_pivot_value entries are delta-coded. libdovi exposes the + // encoded values, while libplacebo expects absolute normalized pivot + // positions, matching FFmpeg's DOVIContext mapping. + pivot = std::min(maxPivot, pivot + src.pivots.data[i]); + dst->pivots[i] = pivotScale * static_cast(pivot); + } + const size_t pieceCount = pivotCount > 0 ? pivotCount - 1 : 0; + for (size_t i = 0; i < pieceCount && i < 8; i++) { + dst->method[i] = src.mapping_idc; + if (src.mapping_idc == 0 && src.polynomial != nullptr) { + const DoviPolynomialCurve *poly = src.polynomial; + if (i < poly->poly_coef_int.len && poly->poly_coef_int.list != nullptr + && poly->poly_coef_int.list[i] != nullptr) { + const DoviI64Data *coeff = poly->poly_coef_int.list[i]; + for (size_t k = 0; k < 3 && k < coeff->len; k++) { + uint64_t fraction = 0; + if (i < poly->poly_coef.len && poly->poly_coef.list != nullptr + && poly->poly_coef.list[i] != nullptr + && k < poly->poly_coef.list[i]->len) { + fraction = poly->poly_coef.list[i]->data[k]; + } + dst->poly_coeffs[i][k] = fixedCoefficient( + coeff->data[k], fraction, + header.coefficient_log2_denom); + } + } + } else if (src.mapping_idc == 1 && src.mmr != nullptr) { + const DoviMMRCurve *mmr = src.mmr; + if (i < mmr->mmr_order_minus1.len + && mmr->mmr_order_minus1.data != nullptr) { + dst->mmr_order[i] = static_cast( + std::min(3, mmr->mmr_order_minus1.data[i] + 1)); + } + if (i < mmr->mmr_constant_int.len) { + const uint64_t fraction = i < mmr->mmr_constant.len + ? mmr->mmr_constant.data[i] : 0; + dst->mmr_constant[i] = fixedCoefficient( + mmr->mmr_constant_int.data[i], fraction, + header.coefficient_log2_denom); + } + if (i < mmr->mmr_coef_int.len && mmr->mmr_coef_int.list != nullptr + && mmr->mmr_coef_int.list[i] != nullptr) { + const DoviI64Data2D *rows = mmr->mmr_coef_int.list[i]; + for (size_t row = 0; row < 3 && row < rows->len; row++) { + const DoviI64Data *coeff = rows->list[row]; + if (coeff == nullptr) continue; + for (size_t k = 0; k < 7 && k < coeff->len; k++) { + uint64_t fraction = 0; + if (i < mmr->mmr_coef.len && mmr->mmr_coef.list != nullptr + && mmr->mmr_coef.list[i] != nullptr + && row < mmr->mmr_coef.list[i]->len + && mmr->mmr_coef.list[i]->list[row] != nullptr + && k < mmr->mmr_coef.list[i]->list[row]->len) { + fraction = mmr->mmr_coef.list[i]->list[row]->data[k]; + } + dst->mmr_coeffs[i][row][k] = fixedCoefficient( + coeff->data[k], fraction, + header.coefficient_log2_denom); + } + } + } + } + } +} + +bool mapRpuMetadata(const DoviRpuDataHeader *header, + const DoviRpuDataMapping *mapping, + const DoviVdrDmData *dm, + pl_dovi_metadata *out) { + if (header == nullptr || out == nullptr + || header->rpu_type != 2) return false; + resetDoviMetadata(out); + if (mapping != nullptr) { + for (int c = 0; c < 3; c++) { + mapRpuCurve(&out->comp[c], mapping->curves[c], *header); + } + } + // Compressed DM carries only dynamic extension blocks. Its static color + // fields are intentionally zero and must inherit the previous DM state. + if (dm != nullptr && !dm->compressed) { + const float yccScale = 1.0f / 8192.0f; + const float lmsScale = 1.0f / 16384.0f; + const int16_t ycc[] = { + dm->ycc_to_rgb_coef0, dm->ycc_to_rgb_coef1, dm->ycc_to_rgb_coef2, + dm->ycc_to_rgb_coef3, dm->ycc_to_rgb_coef4, dm->ycc_to_rgb_coef5, + dm->ycc_to_rgb_coef6, dm->ycc_to_rgb_coef7, dm->ycc_to_rgb_coef8}; + const int16_t lms[] = { + dm->rgb_to_lms_coef0, dm->rgb_to_lms_coef1, dm->rgb_to_lms_coef2, + dm->rgb_to_lms_coef3, dm->rgb_to_lms_coef4, dm->rgb_to_lms_coef5, + dm->rgb_to_lms_coef6, dm->rgb_to_lms_coef7, dm->rgb_to_lms_coef8}; + for (int i = 0; i < 9; i++) { + out->nonlinear.m[i / 3][i % 3] = yccScale * ycc[i]; + out->linear.m[i / 3][i % 3] = lmsScale * lms[i]; + } + out->nonlinear_offset[0] = dm->ycc_to_rgb_offset0 / 268435456.0f; + out->nonlinear_offset[1] = dm->ycc_to_rgb_offset1 / 268435456.0f; + out->nonlinear_offset[2] = dm->ycc_to_rgb_offset2 / 268435456.0f; + } + if (mapping != nullptr && mapping->nlq != nullptr && !header->disable_residual_flag + && mapping->nlq_method_idc == 0) { + out->nlq_active = false; // Profile 5 is single-layer; never compose FEL. + } + return mapping != nullptr || dm != nullptr || header->use_prev_vdr_rpu_flag; +} + +bool hasExtension(const std::vector &extensions, + const char *name) { + return std::any_of(extensions.begin(), extensions.end(), + [name](const VkExtensionProperties &extension) { + return strcmp(extension.extensionName, name) == 0; + }); +} + +bool isHighDepthFormat(uint32_t format) { + switch (format) { + case AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT: + case AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM: +#ifdef AHARDWAREBUFFER_FORMAT_YCbCr_P010 + case AHARDWAREBUFFER_FORMAT_YCbCr_P010: +#endif +#ifdef AHARDWAREBUFFER_FORMAT_YCbCr_P210 + case AHARDWAREBUFFER_FORMAT_YCbCr_P210: +#endif + return true; + default: + return false; + } +} + +jint probeVulkanDevice(VkInstance instance, VkPhysicalDevice device) { + VkPhysicalDeviceProperties properties{}; + vkGetPhysicalDeviceProperties(device, &properties); + if (VK_VERSION_MAJOR(properties.apiVersion) < 1 + || (VK_VERSION_MAJOR(properties.apiVersion) == 1 + && VK_VERSION_MINOR(properties.apiVersion) < 2)) { + return 0; + } + + uint32_t extensionCount = 0; + if (vkEnumerateDeviceExtensionProperties( + device, nullptr, &extensionCount, nullptr) != VK_SUCCESS) { + return 0; + } + std::vector extensions(extensionCount); + if (vkEnumerateDeviceExtensionProperties( + device, nullptr, &extensionCount, extensions.data()) != VK_SUCCESS) { + return 0; + } + if (!hasExtension(extensions, + VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME) + || !hasExtension(extensions, + VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME)) { + return kCapabilityVulkan12; + } + + auto getFeatures2 = reinterpret_cast( + vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceFeatures2")); + if (getFeatures2 == nullptr) return kCapabilityVulkan12; + VkPhysicalDeviceVulkan11Features features11{}; + features11.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES; + VkPhysicalDeviceFeatures2 features2{}; + features2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2; + features2.pNext = &features11; + getFeatures2(device, &features2); + if (features11.samplerYcbcrConversion != VK_TRUE) { + return kCapabilityVulkan12 | kCapabilityAhbImport + | kCapabilityForeignQueue; + } + + uint32_t queueCount = 0; + vkGetPhysicalDeviceQueueFamilyProperties(device, &queueCount, nullptr); + std::vector queues(queueCount); + vkGetPhysicalDeviceQueueFamilyProperties(device, &queueCount, queues.data()); + uint32_t queueFamily = UINT32_MAX; + for (uint32_t index = 0; index < queueCount; index++) { + if (queues[index].queueCount > 0 + && (queues[index].queueFlags + & (VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT)) != 0) { + queueFamily = index; + break; + } + } + if (queueFamily == UINT32_MAX) return kCapabilityVulkan12; + + float priority = 1.0f; + VkDeviceQueueCreateInfo queueInfo{}; + queueInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; + queueInfo.queueFamilyIndex = queueFamily; + queueInfo.queueCount = 1; + queueInfo.pQueuePriorities = &priority; + const char *enabledExtensions[] = { + VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME, + VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME, + }; + VkPhysicalDeviceVulkan11Features enabledFeatures11{}; + enabledFeatures11.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES; + enabledFeatures11.samplerYcbcrConversion = VK_TRUE; + VkDeviceCreateInfo deviceInfo{}; + deviceInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; + deviceInfo.pNext = &enabledFeatures11; + deviceInfo.queueCreateInfoCount = 1; + deviceInfo.pQueueCreateInfos = &queueInfo; + deviceInfo.enabledExtensionCount = std::size(enabledExtensions); + deviceInfo.ppEnabledExtensionNames = enabledExtensions; + VkDevice logicalDevice = VK_NULL_HANDLE; + if (vkCreateDevice(device, &deviceInfo, nullptr, &logicalDevice) != VK_SUCCESS) { + return kCapabilityVulkan12; + } + auto getAhbProperties = reinterpret_cast< + PFN_vkGetAndroidHardwareBufferPropertiesANDROID>( + vkGetDeviceProcAddr( + logicalDevice, + "vkGetAndroidHardwareBufferPropertiesANDROID")); + vkDestroyDevice(logicalDevice, nullptr); + return getAhbProperties == nullptr ? kCapabilityVulkan12 + : kCapabilityVulkan12 | kCapabilityAhbImport + | kCapabilityYcbcrConversion | kCapabilityForeignQueue; +} + +jint probeVulkan() { + VkApplicationInfo appInfo{}; + appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; + appInfo.pApplicationName = "WebHTV Exo DV5 probe"; + appInfo.applicationVersion = 1; + appInfo.pEngineName = "WebHTV"; + appInfo.engineVersion = 1; + appInfo.apiVersion = VK_API_VERSION_1_2; + VkInstanceCreateInfo instanceInfo{}; + instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; + instanceInfo.pApplicationInfo = &appInfo; + VkInstance instance = VK_NULL_HANDLE; + if (vkCreateInstance(&instanceInfo, nullptr, &instance) != VK_SUCCESS) return 0; + + jint result = 0; + uint32_t deviceCount = 0; + if (vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr) == VK_SUCCESS + && deviceCount > 0) { + std::vector devices(deviceCount); + if (vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data()) == VK_SUCCESS) { + for (VkPhysicalDevice device : devices) { + jint deviceResult = probeVulkanDevice(instance, device); + if (deviceResult == (kCapabilityVulkan12 + | kCapabilityAhbImport + | kCapabilityYcbcrConversion + | kCapabilityForeignQueue)) { + result = deviceResult; + break; + } + } + } + } + vkDestroyInstance(instance, nullptr); + return result; +} + +bool probeImageReader(JNIEnv *env) { + AImageReader *reader = nullptr; + media_status_t status = AImageReader_newWithUsage( + 16, + 16, + AIMAGE_FORMAT_PRIVATE, + AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE, + 2, + &reader); + if (status != AMEDIA_OK || reader == nullptr) return false; + ANativeWindow *window = nullptr; + status = AImageReader_getWindow(reader, &window); + jobject surface = status == AMEDIA_OK && window != nullptr + ? ANativeWindow_toSurface(env, window) : nullptr; + bool available = surface != nullptr; + if (surface != nullptr) env->DeleteLocalRef(surface); + AImageReader_delete(reader); + return available; +} + +bool matchTimestamp(Renderer *renderer, int64_t timestampNs, + int64_t *presentationTimeUs) { + std::lock_guard lock(renderer->expectedMutex); + auto match = renderer->expectedFrames.end(); + int64_t bestDifferenceNs = kTimestampMatchToleranceNs + 1; + for (auto frame = renderer->expectedFrames.begin(); + frame != renderer->expectedFrames.end(); ++frame) { + const int64_t differenceNs = frame->imageTimestampNs >= timestampNs + ? frame->imageTimestampNs - timestampNs + : timestampNs - frame->imageTimestampNs; + if (differenceNs < bestDifferenceNs) { + bestDifferenceNs = differenceNs; + match = frame; + if (differenceNs == 0) break; + } + } + + if (match == renderer->expectedFrames.end()) { + renderer->unmatchedFrames.fetch_add(1, std::memory_order_relaxed); + return false; + } + + *presentationTimeUs = match->presentationTimeUs; + renderer->lastPresentationTimeUs.store( + *presentationTimeUs, std::memory_order_relaxed); + renderer->expectedFrames.erase(renderer->expectedFrames.begin(), + std::next(match)); + renderer->matchedFrames.fetch_add(1, std::memory_order_relaxed); + return true; +} + +void onImageAvailable(void *context, AImageReader *reader) { + auto *renderer = static_cast(context); + if (renderer == nullptr) return; + std::lock_guard callbackLock(renderer->callbackMutex); + for (;;) { + AImage *image = nullptr; + media_status_t status = AImageReader_acquireNextImage(reader, &image); + if (status != AMEDIA_OK || image == nullptr) break; + + int64_t timestampNs = 0; + int64_t presentationTimeUs = 0; + bool timestampMatched = false; + if (AImage_getTimestamp(image, ×tampNs) == AMEDIA_OK) { + renderer->lastImageTimestampNs.store( + timestampNs, std::memory_order_relaxed); + timestampMatched = matchTimestamp( + renderer, timestampNs, &presentationTimeUs); + } + + renderer->acquiredFrames.fetch_add(1, std::memory_order_relaxed); + if (!timestampMatched) { + AImage_delete(image); + continue; + } + AHardwareBuffer *buffer = nullptr; + if (AImage_getHardwareBuffer(image, &buffer) == AMEDIA_OK + && buffer != nullptr) { + AHardwareBuffer_Desc desc{}; + AHardwareBuffer_describe(buffer, &desc); + renderer->ahbFrames.fetch_add(1, std::memory_order_relaxed); + renderer->lastAhbFormat.store(desc.format, std::memory_order_relaxed); + if ((desc.usage & AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE) != 0) { + renderer->sampledUsageFrames.fetch_add(1, std::memory_order_relaxed); + } + if (isHighDepthFormat(desc.format)) { + renderer->highDepthFrames.fetch_add(1, std::memory_order_relaxed); + } + } + if (renderImage(renderer, image, presentationTimeUs)) { + renderer->renderedFrames.fetch_add(1, std::memory_order_relaxed); + } else { + renderer->renderFailures.fetch_add(1, std::memory_order_relaxed); + } + AImage_delete(image); + } +} + +Renderer *fromHandle(jlong handle) { + return reinterpret_cast(static_cast(handle)); +} + +} // namespace + +extern "C" JNIEXPORT jint JNICALL +Java_com_fongmi_android_tv_player_exo_ExoDv5Native_nativeProbeCapabilities( + JNIEnv *env, jclass) { + jint result = probeVulkan(); + if (probeImageReader(env)) result |= kCapabilityImageReader; + const char *placeboVersion = pl_version(); + if (PL_API_VER == 375 && placeboVersion != nullptr + && placeboVersion[0] != '\0') { + result |= kCapabilityLibplacebo375; + } + // Parse a deliberately invalid byte so every ABI verifies both the + // vendored parser link and its failure-containment contract. + const uint8_t invalidRpu = 0; + DoviRpuOpaque *rpu = dovi_parse_unspec62_nalu(&invalidRpu, 1); + if (rpu != nullptr) { + if (dovi_rpu_get_error(rpu) != nullptr) result |= kCapabilityLibdovi; + dovi_rpu_free(rpu); + } + return result; +} + +extern "C" JNIEXPORT jlong JNICALL +Java_com_fongmi_android_tv_player_exo_ExoDv5Native_nativeCreate( + JNIEnv *, jclass, jint width, jint height) { + if (width <= 0 || height <= 0) return 0; + auto *renderer = new (std::nothrow) Renderer(); + if (renderer == nullptr) return 0; + media_status_t status = AImageReader_newWithUsage( + width, + height, + AIMAGE_FORMAT_PRIVATE, + AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE, + kMaxImages, + &renderer->reader); + if (status != AMEDIA_OK || renderer->reader == nullptr) { + delete renderer; + return 0; + } + AImageReader_ImageListener listener{ + .context = renderer, + .onImageAvailable = onImageAvailable, + }; + if (AImageReader_setImageListener(renderer->reader, &listener) != AMEDIA_OK) { + AImageReader_delete(renderer->reader); + delete renderer; + return 0; + } + return static_cast(reinterpret_cast(renderer)); +} + +extern "C" JNIEXPORT jobject JNICALL +Java_com_fongmi_android_tv_player_exo_ExoDv5Native_nativeGetInputSurface( + JNIEnv *env, jclass, jlong handle) { + Renderer *renderer = fromHandle(handle); + if (renderer == nullptr || renderer->reader == nullptr) return nullptr; + ANativeWindow *window = nullptr; + if (AImageReader_getWindow(renderer->reader, &window) != AMEDIA_OK + || window == nullptr) { + return nullptr; + } + return ANativeWindow_toSurface(env, window); +} + +extern "C" JNIEXPORT jboolean JNICALL +Java_com_fongmi_android_tv_player_exo_ExoDv5Native_nativeQueueFrame( + JNIEnv *, jclass, jlong handle, jlong imageTimestampNs, + jlong presentationTimeUs) { + Renderer *renderer = fromHandle(handle); + if (renderer == nullptr) return JNI_FALSE; + std::lock_guard lock(renderer->expectedMutex); + if (renderer->expectedFrames.size() >= kMaxExpectedFrames) { + renderer->expectedFrames.pop_front(); + renderer->expectedQueueDrops.fetch_add(1, std::memory_order_relaxed); + } + renderer->expectedFrames.push_back( + ExpectedFrame{imageTimestampNs, presentationTimeUs}); + return JNI_TRUE; +} + +extern "C" JNIEXPORT void JNICALL +Java_com_fongmi_android_tv_player_exo_ExoDv5Native_nativeClearFrames( + JNIEnv *, jclass, jlong handle) { + Renderer *renderer = fromHandle(handle); + if (renderer == nullptr) return; + { + std::lock_guard lock(renderer->expectedMutex); + renderer->expectedFrames.clear(); + } + { + std::lock_guard lock(renderer->rpuMutex); + renderer->pendingRpus.clear(); + renderer->hasLastDovi = false; + resetDoviMetadata(&renderer->lastDovi); + renderer->lastFullRange = true; + renderer->hasSourceLuma = false; + renderer->sourceMinPq = 0.0f; + renderer->sourceMaxPq = 0.0f; + renderer->hasSceneLuma = false; + renderer->sceneMaxPq = 0.0f; + renderer->sceneAvgPq = 0.0f; + } +} + +extern "C" JNIEXPORT jboolean JNICALL +Java_com_fongmi_android_tv_player_exo_ExoDv5Native_nativeQueueRpu( + JNIEnv *env, jclass, jlong handle, jlong presentationTimeUs, + jbyteArray rpuArray) { + Renderer *renderer = fromHandle(handle); + if (renderer == nullptr || rpuArray == nullptr) return JNI_FALSE; + const jsize length = env->GetArrayLength(rpuArray); + if (length < 2) return JNI_FALSE; + jbyte *bytes = env->GetByteArrayElements(rpuArray, nullptr); + if (bytes == nullptr) return JNI_FALSE; + DoviRpuOpaque *rpu = dovi_parse_unspec62_nalu( + reinterpret_cast(bytes), static_cast(length)); + env->ReleaseByteArrayElements(rpuArray, bytes, JNI_ABORT); + if (rpu == nullptr) { + renderer->malformedRpus.fetch_add(1, std::memory_order_relaxed); + return JNI_FALSE; + } + const DoviRpuDataHeader *header = dovi_rpu_get_header(rpu); + const DoviRpuDataMapping *mapping = dovi_rpu_get_data_mapping(rpu); + const DoviVdrDmData *dm = dovi_rpu_get_vdr_dm_data(rpu); + RpuMetadata metadata{}; + metadata.presentationTimeUs = presentationTimeUs; + metadata.hasMapping = mapping != nullptr; + metadata.hasColor = dm != nullptr && !dm->compressed; + metadata.fullRange = header != nullptr && header->bl_video_full_range_flag; + if (metadata.hasColor) { + metadata.hasSourceLuma = dm->source_max_pq > dm->source_min_pq; + metadata.sourceMinPq = dm->source_min_pq / 4095.0f; + metadata.sourceMaxPq = dm->source_max_pq / 4095.0f; + } + if (dm != nullptr) { + metadata.updatesSceneLuma = true; + const DoviExtMetadataBlockLevel1 *level1 = dm->dm_data.level1; + metadata.hasSceneLuma = level1 != nullptr && level1->max_pq > 0; + if (metadata.hasSceneLuma) { + metadata.sceneMaxPq = level1->max_pq / 4095.0f; + metadata.sceneAvgPq = level1->avg_pq / 4095.0f; + } + } + const int64_t metadataLog = renderer->metadataLogs.fetch_add( + 1, std::memory_order_relaxed); + if (metadataLog < 4) { + __android_log_print( + ANDROID_LOG_INFO, "ExoDv5", + "rpu metadata ptsUs=%" PRId64 + " profile=%u usePrev=%d mapping=%d dm=%d compressed=%d" + " fullRange=%d sourcePq=%.4f/%.4f scenePq=%.4f/%.4f", + static_cast(presentationTimeUs), + header == nullptr ? 0 : header->guessed_profile, + header != nullptr && header->use_prev_vdr_rpu_flag ? 1 : 0, + metadata.hasMapping ? 1 : 0, dm != nullptr ? 1 : 0, + dm != nullptr && dm->compressed ? 1 : 0, + metadata.fullRange ? 1 : 0, + metadata.sourceMinPq, metadata.sourceMaxPq, + metadata.sceneMaxPq, metadata.sceneAvgPq); + } + const bool valid = mapRpuMetadata(header, mapping, dm, &metadata.dovi); + if (dm != nullptr) dovi_rpu_free_vdr_dm_data(dm); + if (mapping != nullptr) dovi_rpu_free_data_mapping(mapping); + if (header != nullptr) dovi_rpu_free_header(header); + const char *error = dovi_rpu_get_error(rpu); + if (!valid || error != nullptr) { + renderer->malformedRpus.fetch_add(1, std::memory_order_relaxed); + dovi_rpu_free(rpu); + return JNI_FALSE; + } + dovi_rpu_free(rpu); + std::lock_guard lock(renderer->rpuMutex); + // Matroska BlockAdditional delivery can batch RPU NALs out of decode order. + // Keep enough ordered metadata for codec pre-roll. If the producer ever + // exceeds the bound, preserve the earliest entries needed by output next. + auto insertAt = std::upper_bound( + renderer->pendingRpus.begin(), renderer->pendingRpus.end(), + metadata.presentationTimeUs, + [](int64_t pts, const RpuMetadata &item) { + return pts < item.presentationTimeUs; + }); + renderer->pendingRpus.insert(insertAt, metadata); + if (renderer->pendingRpus.size() > kMaxPendingRpus) { + renderer->pendingRpus.pop_back(); + renderer->rpuQueueDrops.fetch_add(1, std::memory_order_relaxed); + } + renderer->parsedRpus.fetch_add(1, std::memory_order_relaxed); + return JNI_TRUE; +} + +extern "C" JNIEXPORT void JNICALL +Java_com_fongmi_android_tv_player_exo_ExoDv5Native_nativeSetOutputSurface( + JNIEnv *env, jclass, jlong handle, jobject surface) { + Renderer *renderer = fromHandle(handle); + if (renderer == nullptr) return; + ANativeWindow *newWindow = surface == nullptr + ? nullptr : ANativeWindow_fromSurface(env, surface); + std::lock_guard lock(renderer->callbackMutex); + destroyVulkan(renderer); + if (renderer->outputWindow != nullptr) { + ANativeWindow_release(renderer->outputWindow); + renderer->outputWindow = nullptr; + } + renderer->outputWindow = newWindow; + if (newWindow != nullptr) ensureVulkan(renderer); +} + +extern "C" JNIEXPORT jlongArray JNICALL +Java_com_fongmi_android_tv_player_exo_ExoDv5Native_nativeGetStats( + JNIEnv *env, jclass, jlong handle) { + Renderer *renderer = fromHandle(handle); + if (renderer == nullptr) return nullptr; + int64_t pending = 0; + { + std::lock_guard lock(renderer->expectedMutex); + pending = static_cast(renderer->expectedFrames.size()); + } + int64_t pendingRpus = 0; + { + std::lock_guard lock(renderer->rpuMutex); + pendingRpus = static_cast(renderer->pendingRpus.size()); + } + jlong values[] = { + renderer->acquiredFrames.load(std::memory_order_relaxed), + renderer->ahbFrames.load(std::memory_order_relaxed), + renderer->sampledUsageFrames.load(std::memory_order_relaxed), + renderer->highDepthFrames.load(std::memory_order_relaxed), + renderer->matchedFrames.load(std::memory_order_relaxed), + renderer->unmatchedFrames.load(std::memory_order_relaxed), + renderer->expectedQueueDrops.load(std::memory_order_relaxed), + renderer->lastImageTimestampNs.load(std::memory_order_relaxed), + renderer->lastPresentationTimeUs.load(std::memory_order_relaxed), + renderer->lastAhbFormat.load(std::memory_order_relaxed), + pending, + renderer->parsedRpus.load(std::memory_order_relaxed), + renderer->malformedRpus.load(std::memory_order_relaxed), + renderer->rpuQueueDrops.load(std::memory_order_relaxed), + pendingRpus, + renderer->renderedFrames.load(std::memory_order_relaxed), + renderer->renderFailures.load(std::memory_order_relaxed), + }; + jlongArray result = env->NewLongArray(std::size(values)); + if (result != nullptr) { + env->SetLongArrayRegion(result, 0, std::size(values), values); + } + return result; +} + +extern "C" JNIEXPORT void JNICALL +Java_com_fongmi_android_tv_player_exo_ExoDv5Native_nativeRelease( + JNIEnv *, jclass, jlong handle) { + Renderer *renderer = fromHandle(handle); + if (renderer == nullptr) return; + if (renderer->reader != nullptr) { + AImageReader_setImageListener(renderer->reader, nullptr); + std::lock_guard callbackLock(renderer->callbackMutex); + AImageReader_delete(renderer->reader); + renderer->reader = nullptr; + } + destroyVulkan(renderer); + if (renderer->outputWindow != nullptr) { + ANativeWindow_release(renderer->outputWindow); + renderer->outputWindow = nullptr; + } + delete renderer; +} diff --git a/app/src/main/java/androidx/media3/mpvplayer/MpvOsdSurfacePolicy.java b/app/src/main/java/androidx/media3/mpvplayer/MpvOsdSurfacePolicy.java index 0109f41518..9b1f612417 100644 --- a/app/src/main/java/androidx/media3/mpvplayer/MpvOsdSurfacePolicy.java +++ b/app/src/main/java/androidx/media3/mpvplayer/MpvOsdSurfacePolicy.java @@ -17,6 +17,20 @@ final class MpvOsdSurfacePolicy { || isSelected(secondarySelection); } + static boolean needsCurrentTrackQuery(boolean subtitlesVisible, + String primarySelection, + String secondarySelection) { + if (!subtitlesVisible) return false; + return !isDisabled(primarySelection) || !isDisabled(secondarySelection); + } + + private static boolean isDisabled(String value) { + if (value == null) return false; + String normalized = value.trim(); + return "no".equalsIgnoreCase(normalized) + || "none".equalsIgnoreCase(normalized); + } + private static boolean isSelected(String value) { if (value == null) return false; String normalized = value.trim(); diff --git a/app/src/main/java/androidx/media3/mpvplayer/MpvPauseIntentPolicy.java b/app/src/main/java/androidx/media3/mpvplayer/MpvPauseIntentPolicy.java new file mode 100644 index 0000000000..536af4ed1d --- /dev/null +++ b/app/src/main/java/androidx/media3/mpvplayer/MpvPauseIntentPolicy.java @@ -0,0 +1,19 @@ +package androidx.media3.mpvplayer; + +final class MpvPauseIntentPolicy { + + enum Action { + NONE, + WAIT_FOR_ACTIVE_MEDIA, + REASSERT_REQUESTED_STATE + } + + private MpvPauseIntentPolicy() { + } + + static Action resolve(boolean playWhenReady, boolean observedPaused, boolean activeMedia) { + boolean requestedPaused = !playWhenReady; + if (observedPaused == requestedPaused) return Action.NONE; + return activeMedia ? Action.REASSERT_REQUESTED_STATE : Action.WAIT_FOR_ACTIVE_MEDIA; + } +} diff --git a/app/src/main/java/androidx/media3/mpvplayer/MpvPlayer.java b/app/src/main/java/androidx/media3/mpvplayer/MpvPlayer.java index 32820d1b25..6095e86747 100644 --- a/app/src/main/java/androidx/media3/mpvplayer/MpvPlayer.java +++ b/app/src/main/java/androidx/media3/mpvplayer/MpvPlayer.java @@ -194,6 +194,7 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs private final File subtitleDiagnosticFile; private final File preloadCacheDir; private final long preloadCacheCapacityBytes; + private final MpvSurfaceTeardownPolicy surfaceTeardownPolicy; private MediaItem mediaItem; private SurfaceHolder surfaceHolder; private SurfaceHolder osdSurfaceHolder; @@ -370,6 +371,7 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs config.demuxerHysteresisSeconds()); seekPositionState = new MpvSeekPositionState(); mediaReplacementCoordinator = new MpvMediaReplacementCoordinator(); + surfaceTeardownPolicy = new MpvSurfaceTeardownPolicy(); stateRefreshRunnable = this::refreshPlaybackState; mainThreadHeartbeatPending = new AtomicBoolean(); mainThreadHeartbeatRunnable = () -> { @@ -591,6 +593,7 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs @Override protected ListenableFuture handleRelease() { + prepareTerminalRelease(); released = true; startMainThreadWatchdog(); videoSizeProbeListener = null; @@ -701,6 +704,12 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs applyVideoAspect(); } + public void prepareTerminalRelease() { + if (surfaceTeardownPolicy.requestTerminalRelease()) { + SpiderDebug.log("mpv", "terminal Surface release requested player=%s", identity(this)); + } + } + public String getAudioSpdifCodecs() { return config.audioSpdif(); } @@ -1770,9 +1779,21 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs case "demuxer-cache-state/bof-cached" -> cachedCacheBof = Boolean.TRUE.equals(value); case "demuxer-cache-state/eof-cached" -> cachedCacheEof = Boolean.TRUE.equals(value); case "pause" -> { - if (value instanceof Boolean paused && playWhenReady == paused) { - playWhenReady = !paused; - stateChanged = true; + if (value instanceof Boolean paused) { + boolean activeMedia = fileLoaded + && !stopping + && !eofReached + && playbackState != Player.STATE_IDLE + && playbackState != Player.STATE_ENDED; + MpvPauseIntentPolicy.Action action = MpvPauseIntentPolicy.resolve( + playWhenReady, paused, activeMedia); + if (action == MpvPauseIntentPolicy.Action.REASSERT_REQUESTED_STATE) { + boolean requestedPaused = !playWhenReady; + PlaybackTrace.log("mpv", playbackTraceId, + "pause intent reconcile observed=%s requested=%s state=%d", + paused, requestedPaused, playbackState); + safeSetPropertyBoolean("pause", requestedPaused); + } } } case "paused-for-cache" -> { @@ -1847,12 +1868,14 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs case "vid", "aid", "sid", "secondary-sid", "sub-visibility", "current-tracks/video/id", "current-tracks/audio/id", "current-tracks/sub/id", "current-tracks/sub2/id" -> scheduleTrackRefresh(property); case "chapter" -> { if (value instanceof Number number) currentChapter = number.intValue(); - scheduleChapterRefresh(); + if (!shouldDeferStartupMetadataRefresh()) scheduleChapterRefresh(); + } + case "chapter-list" -> { + if (!shouldDeferStartupMetadataRefresh()) handleChapterListProperty(value); } - case "chapter-list" -> handleChapterListProperty(value); case "chapter-list/count" -> { observeChapterProperties((int) Math.max(0, longValue(value, 0))); - scheduleChapterRefresh(); + if (!shouldDeferStartupMetadataRefresh()) scheduleChapterRefresh(); } default -> { if (property.startsWith("track-list/")) scheduleTrackRefresh(property); @@ -1906,7 +1929,7 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs } public void restoreVideoTrackSelection() { - if (!initialized) return; + if (!initialized || config.deferStartupTrackRefresh() && !playbackRestarted) return; int count = Math.max(0, intProperty("track-list/count", 0)); for (int index = 0; index < count; index++) { TrackInfo info = readTrackInfo(index, C.INDEX_UNSET); @@ -2014,8 +2037,12 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs loading = true; updateVideoSize("event=file-loaded"); applyVideoAspect(); - refreshTracks(); - refreshChapters(); + if (config.deferStartupTrackRefresh()) { + scheduleTrackRefresh("event=file-loaded"); + } else { + refreshTracks(); + refreshChapters(); + } if (shouldCollectDebugDetails()) PlaybackTrace.log("mpv", playbackTraceId, "event=file-loaded duration=%d size=%dx%d path=%s", cachedDurationMs, videoSize.width, videoSize.height, MpvDiagnosticsPolicy.sourceSummary(currentPlayableUri)); addSubtitleConfigurations(); if (initialSeekPositionMs != C.TIME_UNSET) { @@ -2058,6 +2085,9 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs case MPVLib.MpvEvent.MPV_EVENT_PLAYBACK_RESTART -> { playbackRestarted = true; endSeekBuffering("playback-restart"); + if (config.deferStartupTrackRefresh()) { + scheduleTrackRefresh("event=playback-restart"); + } if (currentLikelyHls) requestHlsPreload(cachedPositionMs); updateVideoSize("event=playback-restart"); if (shouldCollectDebugDetails()) PlaybackTrace.log("mpv", playbackTraceId, "event=playback-restart position=%d duration=%d size=%dx%d", cachedPositionMs, cachedDurationMs, videoSize.width, videoSize.height); @@ -2501,13 +2531,22 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs private void syncOsdSurfaceRequirementFromMpv() { if (!initialized) return; + boolean subtitlesVisible = booleanProperty("sub-visibility", true); + String primarySelection = propertyStringOrInt("sid"); + String secondarySelection = propertyStringOrInt("secondary-sid"); + if (!MpvOsdSurfacePolicy.needsCurrentTrackQuery( + subtitlesVisible, primarySelection, secondarySelection)) { + setOsdSurfaceRequested(false); + return; + } + String primaryCurrent = isDisabledTrackChoice(primarySelection) + ? "" : currentTrackId(C.TRACK_TYPE_TEXT); + String secondaryCurrent = isDisabledTrackChoice(secondarySelection) + ? "" : propertyStringOrInt("current-tracks/sub2/id"); boolean requested = requiresOsdSurface() && MpvOsdSurfacePolicy.requiresSurface( - booleanProperty("sub-visibility", true), - currentTrackId(C.TRACK_TYPE_TEXT), - propertyStringOrInt("sid"), - propertyStringOrInt("current-tracks/sub2/id"), - propertyStringOrInt("secondary-sid")); + subtitlesVisible, primaryCurrent, primarySelection, + secondaryCurrent, secondarySelection); setOsdSurfaceRequested(requested); } @@ -2524,7 +2563,7 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs } private void reconcileOsdSurface() { - if (!initialized) return; + if (!initialized || !surfaceTeardownPolicy.shouldBindSurface()) return; if (osdSurfaceRequested) createOsdSurfaceView(); if (pendingOsdSurfaceRequestId != 0) return; @@ -2600,7 +2639,8 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs } private void bindVideoOutput() { - if (!initialized || surface == null || !surface.isValid()) return; + if (!initialized || !surfaceTeardownPolicy.shouldBindSurface() + || surface == null || !surface.isValid()) return; try { boolean sameVideoSurface = surfaceAttached && attachedSurface == surface; String targetVo = videoOutputVo(); @@ -2655,6 +2695,10 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs if (!initialized) return; if (!surfaceAttached && !osdSurfaceAttached && pendingOsdSurfaceRequestId == 0) return; + if (!surfaceTeardownPolicy.shouldDetachSurface()) { + clearMpvSurfaceAttachmentState(); + return; + } try { enqueueMpvCommand("set", "vo", "null"); enqueueMpvCommand("set", "force-window", "no"); @@ -2664,6 +2708,10 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs if (surfaceAttached) mpvDetachSurface(); } catch (Throwable ignored) { } + clearMpvSurfaceAttachmentState(); + } + + private void clearMpvSurfaceAttachmentState() { surfaceAttached = false; osdSurfaceAttached = false; pendingOsdSurfaceRequestId = 0; @@ -3939,7 +3987,13 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs fileLoadedAtElapsedRealtimeMs, SystemClock.elapsedRealtime())); } + if (config.deferStartupTrackRefresh() && !playbackRestarted) { + if (shouldCollectDebugDetails()) PlaybackTrace.log("mpv", playbackTraceId, + "track refresh deferred until playback restart"); + return; + } refreshTracks(); + if (config.deferStartupTrackRefresh()) refreshChapters(); invalidateState(); } @@ -3973,6 +4027,7 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs private void refreshTracks() { if (trackRefreshScheduled) cancelScheduledTrackRefresh(); + if (config.deferStartupTrackRefresh() && !playbackRestarted) return; if (!initialized) { currentTracks = Tracks.EMPTY; selectedVideoTrackDiagnostics = VideoTrackDiagnostics.empty(); @@ -4137,7 +4192,7 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs } private void refreshChapters() { - if (released || !initialized) return; + if (released || !initialized || shouldDeferStartupMetadataRefresh()) return; currentChapter = intProperty("chapter", currentChapter); List chapters = parseChapters(stringProperty("chapter-list", "")); if (chapters.isEmpty()) chapters = readChaptersFromProperties(); @@ -4145,6 +4200,7 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs } private void handleChapterListProperty(@Nullable Object value) { + if (shouldDeferStartupMetadataRefresh()) return; List chapters = value instanceof String string ? parseChapters(string) : List.of(); if (chapters.isEmpty()) { scheduleChapterRefresh(); @@ -4153,6 +4209,10 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs updateCurrentChapters(chapters); } + private boolean shouldDeferStartupMetadataRefresh() { + return config.deferStartupTrackRefresh() && !playbackRestarted; + } + private void updateCurrentChapters(List chapters) { if (chapters == null) chapters = List.of(); if (chapters.equals(currentChapters)) return; @@ -4209,17 +4269,23 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs private void logTrackSnapshot(List infos, String selectedVideo, String selectedAudio, String selectedText, Tracks tracks) { if (!shouldCollectDebugDetails()) return; + String rawVid = propertyStringOrInt("vid"); + String rawAid = propertyStringOrInt("aid"); + String rawSid = propertyStringOrInt("sid"); + String rawSecondarySid = propertyStringOrInt("secondary-sid"); StringBuilder builder = new StringBuilder(); builder.append("tracks snapshot "); builder.append("vid=").append(selectedVideo).append(" aid=").append(selectedAudio).append(" sid=").append(selectedText); - builder.append(" rawVid=").append(propertyStringOrInt("vid")); - builder.append(" rawAid=").append(propertyStringOrInt("aid")); - builder.append(" rawSid=").append(propertyStringOrInt("sid")); - builder.append(" secondarySid=").append(secondarySubtitleTrackId()); + builder.append(" rawVid=").append(rawVid); + builder.append(" rawAid=").append(rawAid); + builder.append(" rawSid=").append(rawSid); + builder.append(" secondarySid=").append(rawSecondarySid); builder.append(" currentVideo=").append(propertyStringOrInt("current-tracks/video/id")); builder.append(" currentAudio=").append(propertyStringOrInt("current-tracks/audio/id")); - builder.append(" currentSub=").append(propertyStringOrInt("current-tracks/sub/id")); - builder.append(" currentSub2=").append(propertyStringOrInt("current-tracks/sub2/id")); + builder.append(" currentSub=").append(isDisabledTrackChoice(rawSid) + ? rawSid : propertyStringOrInt("current-tracks/sub/id")); + builder.append(" currentSub2=").append(isDisabledTrackChoice(rawSecondarySid) + ? rawSecondarySid : propertyStringOrInt("current-tracks/sub2/id")); builder.append(" size=").append(videoSize.width).append("x").append(videoSize.height); builder.append(" width=").append(intProperty("width", C.LENGTH_UNSET)); builder.append(" height=").append(intProperty("height", C.LENGTH_UNSET)); @@ -4291,10 +4357,12 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs } private String selectedTrackId(int type) { - String currentTrackId = currentTrackId(type); - if (!TextUtils.isEmpty(currentTrackId)) return currentTrackId; String property = mpvTrackProperty(type); - return property == null ? "" : propertyStringOrInt(property); + if (property == null) return ""; + String selected = propertyStringOrInt(property); + if (isDisabledTrackChoice(selected)) return selected; + String current = currentTrackId(type); + return !TextUtils.isEmpty(current) ? current : selected; } private String currentTrackId(int type) { @@ -4308,9 +4376,11 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs } private String secondarySubtitleTrackId() { + String selected = propertyStringOrInt("secondary-sid"); + if (isDisabledTrackChoice(selected)) return selected; String current = propertyStringOrInt("current-tracks/sub2/id"); if (!TextUtils.isEmpty(current)) return current; - return propertyStringOrInt("secondary-sid"); + return selected; } private String propertyStringOrInt(String property) { @@ -4372,6 +4442,8 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs String decoder = stringProperty(prefix + "decoder", ""); int dolbyVisionProfile = intProperty(prefix + "dolby-vision-profile", C.INDEX_UNSET); int dolbyVisionLevel = intProperty(prefix + "dolby-vision-level", C.INDEX_UNSET); + int sourceDolbyVisionProfile = intProperty(prefix + "source-dolby-vision-profile", C.INDEX_UNSET); + int sourceDolbyVisionLevel = intProperty(prefix + "source-dolby-vision-level", C.INDEX_UNSET); boolean selected = booleanProperty(prefix + "selected", false); int width = intProperty(prefix + "demux-w", C.LENGTH_UNSET); int height = intProperty(prefix + "demux-h", C.LENGTH_UNSET); @@ -4389,6 +4461,7 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs ColorInfo colorInfo = type == C.TRACK_TYPE_VIDEO ? videoColorInfo() : null; return new TrackInfo(type, id, demuxId, srcId, title, lang, codec, decoder, dolbyVisionProfile, dolbyVisionLevel, + sourceDolbyVisionProfile, sourceDolbyVisionLevel, selected, width, height, frameRate, sampleRate, channels, bitrate, hlsBitrate, colorInfo); } @@ -5343,6 +5416,8 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs final String decoder; final int dolbyVisionProfile; final int dolbyVisionLevel; + final int sourceDolbyVisionProfile; + final int sourceDolbyVisionLevel; final boolean selected; final int width; final int height; @@ -5356,6 +5431,7 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs TrackInfo(int type, String id, int demuxId, int srcId, String title, String lang, String codec, String decoder, int dolbyVisionProfile, int dolbyVisionLevel, + int sourceDolbyVisionProfile, int sourceDolbyVisionLevel, boolean selected, int width, int height, float frameRate, int sampleRate, int channels, int bitrate, int hlsBitrate, @Nullable ColorInfo colorInfo) { @@ -5369,6 +5445,8 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs this.decoder = decoder; this.dolbyVisionProfile = dolbyVisionProfile; this.dolbyVisionLevel = dolbyVisionLevel; + this.sourceDolbyVisionProfile = sourceDolbyVisionProfile; + this.sourceDolbyVisionLevel = sourceDolbyVisionLevel; this.selected = selected; this.width = width; this.height = height; @@ -5399,16 +5477,22 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs } VideoTrackDiagnostics toVideoTrackDiagnostics() { + int sourceProfile = sourceDolbyVisionProfile > 0 + ? sourceDolbyVisionProfile : dolbyVisionProfile; + int sourceLevel = sourceDolbyVisionProfile > 0 + ? sourceDolbyVisionLevel : dolbyVisionLevel; return new VideoTrackDiagnostics( - sourceCodecs(), dolbyVisionProfile, dolbyVisionLevel, + sourceCodecs(sourceProfile, sourceLevel), + dolbyVisionProfile, dolbyVisionLevel, + sourceProfile, sourceLevel, codec, decoder, colorInfo); } - private String sourceCodecs() { - if (dolbyVisionProfile <= 0) return codec; - String value = String.format(Locale.US, "dvhe.%02d", dolbyVisionProfile); - return dolbyVisionLevel >= 0 - ? value + String.format(Locale.US, ".%02d", dolbyVisionLevel) + private String sourceCodecs(int profile, int level) { + if (profile <= 0) return codec; + String value = String.format(Locale.US, "dvhe.%02d", profile); + return level >= 0 + ? value + String.format(Locale.US, ".%02d", level) : value; } @@ -5427,6 +5511,8 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs String sourceCodecs, int dolbyVisionProfile, int dolbyVisionLevel, + int sourceDolbyVisionProfile, + int sourceDolbyVisionLevel, String decodedCodec, String decoderName, @Nullable ColorInfo outputColorInfo) { @@ -5437,13 +5523,25 @@ public final class MpvPlayer extends SimpleBasePlayer implements MPVLib.EventObs decoderName = decoderName == null ? "" : decoderName; } + public VideoTrackDiagnostics( + String sourceCodecs, + int dolbyVisionProfile, + int dolbyVisionLevel, + String decodedCodec, + String decoderName, + @Nullable ColorInfo outputColorInfo) { + this(sourceCodecs, dolbyVisionProfile, dolbyVisionLevel, + dolbyVisionProfile, dolbyVisionLevel, + decodedCodec, decoderName, outputColorInfo); + } + public boolean hasDolbyVisionSource() { - return dolbyVisionProfile > 0; + return sourceDolbyVisionProfile > 0; } public static VideoTrackDiagnostics empty() { return new VideoTrackDiagnostics("", C.INDEX_UNSET, C.INDEX_UNSET, - "", "", null); + C.INDEX_UNSET, C.INDEX_UNSET, "", "", null); } } diff --git a/app/src/main/java/androidx/media3/mpvplayer/MpvPlayerConfig.java b/app/src/main/java/androidx/media3/mpvplayer/MpvPlayerConfig.java index bea7a8209b..8a0b2797d4 100644 --- a/app/src/main/java/androidx/media3/mpvplayer/MpvPlayerConfig.java +++ b/app/src/main/java/androidx/media3/mpvplayer/MpvPlayerConfig.java @@ -40,6 +40,7 @@ public final class MpvPlayerConfig { private final boolean performanceOptionsPriority; private final boolean automaticCacheTime; private final boolean automaticHlsVariant; + private final boolean deferStartupTrackRefresh; private final Map extraOptions; private MpvPlayerConfig(Builder builder) { @@ -67,6 +68,7 @@ public final class MpvPlayerConfig { performanceOptionsPriority = builder.performanceOptionsPriority; automaticCacheTime = builder.automaticCacheTime; automaticHlsVariant = builder.automaticHlsVariant; + deferStartupTrackRefresh = builder.deferStartupTrackRefresh; extraOptions = Collections.unmodifiableMap(new LinkedHashMap<>(builder.extraOptions)); } @@ -172,6 +174,10 @@ public final class MpvPlayerConfig { return automaticHlsVariant; } + public boolean deferStartupTrackRefresh() { + return deferStartupTrackRefresh; + } + public Map extraOptions() { return extraOptions; } @@ -203,6 +209,7 @@ public final class MpvPlayerConfig { private boolean performanceOptionsPriority = true; private boolean automaticCacheTime; private boolean automaticHlsVariant; + private boolean deferStartupTrackRefresh; private Builder(Context context) { Context app = context.getApplicationContext(); @@ -331,6 +338,11 @@ public final class MpvPlayerConfig { return this; } + public Builder deferStartupTrackRefresh(boolean deferStartupTrackRefresh) { + this.deferStartupTrackRefresh = deferStartupTrackRefresh; + return this; + } + public Builder option(String name, String value) { extraOptions.put(name, value); return this; diff --git a/app/src/main/java/androidx/media3/mpvplayer/MpvSurfaceTeardownPolicy.java b/app/src/main/java/androidx/media3/mpvplayer/MpvSurfaceTeardownPolicy.java new file mode 100644 index 0000000000..0a1034336a --- /dev/null +++ b/app/src/main/java/androidx/media3/mpvplayer/MpvSurfaceTeardownPolicy.java @@ -0,0 +1,20 @@ +package androidx.media3.mpvplayer; + +final class MpvSurfaceTeardownPolicy { + + private volatile boolean terminalReleaseRequested; + + boolean requestTerminalRelease() { + if (terminalReleaseRequested) return false; + terminalReleaseRequested = true; + return true; + } + + boolean shouldBindSurface() { + return !terminalReleaseRequested; + } + + boolean shouldDetachSurface() { + return !terminalReleaseRequested; + } +} diff --git a/app/src/main/java/com/fongmi/android/tv/api/CatSource.java b/app/src/main/java/com/fongmi/android/tv/api/CatSource.java index 91585cb511..169a31737d 100644 --- a/app/src/main/java/com/fongmi/android/tv/api/CatSource.java +++ b/app/src/main/java/com/fongmi/android/tv/api/CatSource.java @@ -11,6 +11,7 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import java.util.Locale; import java.util.concurrent.TimeUnit; /** @@ -30,7 +31,7 @@ public class CatSource { */ public static boolean isBundle(String url) { if (TextUtils.isEmpty(url)) return false; - String value = url.trim().toLowerCase(); + String value = url.trim().toLowerCase(Locale.ROOT); if (value.endsWith(".js.md5") || value.endsWith("/index.js")) return true; return NodeBundle.isLocal(url); } diff --git a/app/src/main/java/com/fongmi/android/tv/api/SiteApi.java b/app/src/main/java/com/fongmi/android/tv/api/SiteApi.java index c270b3ab5e..ffbffe385f 100644 --- a/app/src/main/java/com/fongmi/android/tv/api/SiteApi.java +++ b/app/src/main/java/com/fongmi/android/tv/api/SiteApi.java @@ -178,7 +178,7 @@ public class SiteApi { @NonNull public static Result playerContent(@NonNull String key, @NonNull String flag, @NonNull String id) throws Exception { - return playerContent(key, flag, id, PlayerSetting.getPlayer()); + return playerContent(key, flag, id, PlayerSetting.getActivePlayer()); } @NonNull @@ -188,7 +188,7 @@ public class SiteApi { @NonNull public static Result playerContentIsolated(@NonNull String key, @NonNull String flag, @NonNull String id) throws Exception { - return playerContentIsolated(key, flag, id, PlayerSetting.getPlayer()); + return playerContentIsolated(key, flag, id, PlayerSetting.getActivePlayer()); } @NonNull diff --git a/app/src/main/java/com/fongmi/android/tv/bean/History.java b/app/src/main/java/com/fongmi/android/tv/bean/History.java index d60a27beaa..2781da7699 100644 --- a/app/src/main/java/com/fongmi/android/tv/bean/History.java +++ b/app/src/main/java/com/fongmi/android/tv/bean/History.java @@ -115,7 +115,9 @@ public class History implements Diffable { @ColumnInfo(defaultValue = "0") private int tmdbEpisodeNumber; - private transient int player = PlayerSetting.NONE; + @SerializedName("player") + @ColumnInfo(defaultValue = "-1") + private int player = PlayerSetting.NONE; private transient long updateTime; private transient String playbackSourceKey; @Ignore @@ -873,7 +875,15 @@ public class History implements Diffable { public boolean setTmdbEpisodePosition(Episode episode) { TmdbEpisode tmdbEpisode = episode == null ? null : episode.getTmdbEpisode(); int episodeNumber = tmdbEpisode == null ? 0 : tmdbEpisode.getNumber(); - int seasonNumber = tmdbEpisode == null ? 0 : tmdbEpisode.getSeasonNumber(); + return setTmdbEpisodePosition(tmdbEpisode, episodeNumber); + } + + public boolean setTmdbEpisodePositionWithUnknownSeason(int episodeNumber) { + return setTmdbEpisodePosition(null, Math.max(0, episodeNumber)); + } + + private boolean setTmdbEpisodePosition(TmdbEpisode tmdbEpisode, int episodeNumber) { + int seasonNumber = tmdbEpisode == null ? -1 : tmdbEpisode.getSeasonNumber(); return setTmdbEpisodePosition(seasonNumber, episodeNumber); } @@ -1062,9 +1072,16 @@ public class History implements Diffable { * 将历史记录的 key 迁移到新值。 * 仅在 key 实际变化时删除旧 key,避免同 key 先删后写失败导致历史消失。 * 迁移后立即 save 新 key,缩短「旧已删、新未写」窗口。 + * + *

push(网盘/推送/本地文件)记录不迁移:它的 key 第二段就是那条播放地址本身 + * (见 {@link #getVodId()} 与 SiteApi#pushDetail),而从历史进入播放正是靠这一段反解 + * 出 vodId。普通站点的 vodId 是稳定的条目 id,迁移无害;push 迁移则会把记录改写成详情 + * 阶段解析出的另一条地址,那条地址往往带时效,下次从历史打开必然失败,用户只能回网盘 + * 重新找。按名合并({@link #canMergeByName()})已对 push 豁免,这里补齐同样的豁免。 */ public void replace(String key) { if (TextUtils.isEmpty(key) || TextUtils.equals(getKey(), key)) return; + if (isPushHistory()) return; String previous = getKey(); enrichTmdbId(); updateTime = System.currentTimeMillis(); diff --git a/app/src/main/java/com/fongmi/android/tv/db/AppDatabase.java b/app/src/main/java/com/fongmi/android/tv/db/AppDatabase.java index a7b27ae7c7..f8d8298cd1 100644 --- a/app/src/main/java/com/fongmi/android/tv/db/AppDatabase.java +++ b/app/src/main/java/com/fongmi/android/tv/db/AppDatabase.java @@ -40,7 +40,7 @@ import java.util.concurrent.atomic.AtomicBoolean; @Database(entities = {Keep.class, Site.class, Live.class, Track.class, Config.class, Device.class, History.class, PlaybackDeleteTombstone.class, TmdbSeasonProgress.class}, version = AppDatabase.VERSION) public abstract class AppDatabase extends RoomDatabase { - public static final int VERSION = 43; + public static final int VERSION = 44; public static final String NAME = "tv"; public static final String SYMBOL = "@@@"; private static final int BACKUP_KEEP_COUNT = 7; @@ -177,6 +177,7 @@ public abstract class AppDatabase extends RoomDatabase { .addMigrations(Migrations.MIGRATION_40_41) .addMigrations(Migrations.MIGRATION_41_42) .addMigrations(Migrations.MIGRATION_42_43) + .addMigrations(Migrations.MIGRATION_43_44) .fallbackToDestructiveMigration(true) .allowMainThreadQueries().build(); } diff --git a/app/src/main/java/com/fongmi/android/tv/db/Migrations.java b/app/src/main/java/com/fongmi/android/tv/db/Migrations.java index 533e6c3afb..00d34c5cf3 100644 --- a/app/src/main/java/com/fongmi/android/tv/db/Migrations.java +++ b/app/src/main/java/com/fongmi/android/tv/db/Migrations.java @@ -130,6 +130,18 @@ public class Migrations { } }; + /** + * 播放内核回到「按剧集记住」:History 新增 player 列。 + * -1 表示这条记录没有自己的内核偏好,播放时沿用设置页的全局默认。 + */ + public static final Migration MIGRATION_43_44 = new Migration(43, 44) { + @Override + public void migrate(@NonNull SupportSQLiteDatabase database) { + addColumnIfMissing(database, "History", "player", + "ALTER TABLE History ADD COLUMN `player` INTEGER NOT NULL DEFAULT -1"); + } + }; + private static void addColumnIfMissing( SupportSQLiteDatabase database, String table, diff --git a/app/src/main/java/com/fongmi/android/tv/history/HistoryDisplayPolicy.java b/app/src/main/java/com/fongmi/android/tv/history/HistoryDisplayPolicy.java index c99efa90dc..4caa8406d5 100644 --- a/app/src/main/java/com/fongmi/android/tv/history/HistoryDisplayPolicy.java +++ b/app/src/main/java/com/fongmi/android/tv/history/HistoryDisplayPolicy.java @@ -56,7 +56,8 @@ public final class HistoryDisplayPolicy { if (source != null) { for (History item : source) { if (item == null) continue; - base.add(item); + // 季号未知的路由行若已派生出季度快照,就由快照代表这部剧,否则同剧占两格 + if (!supersededByOwnSeasonSnapshot(item, progress)) base.add(item); routes.put(routeKey(item.getCid(), item.getTmdbId(), item.getKey()), item); } } @@ -115,6 +116,32 @@ public final class HistoryDisplayPolicy { return key == null || key.isEmpty() ? "" : "source:" + key; } + /** + * 季号未知的路由行({@code tmdbSeasonNumber == -1})是否应让位给它自己的季度快照。 + * + *

源站条目解析不出季号时 History 存 -1,而它先前写出的 {@code TmdbSeasonProgress} + * 里存的是 TMDB 刮到的真实季号。{@link #tmdbIdentity} 对前者退化成 {@code source:key}、 + * 对后者算出 {@code tv::season:},两个身份不相等,同一部剧就在列表里占了两格: + * 一格是季号未知的旧进度,一格是快照里的新进度。 + * + *

这里让路由行让位:快照由它自己派生({@code sourceHistoryKey} 指回该行),承载的是 + * 更完整的季集身份与更新的进度,足以代表这部剧。仅在确有同源快照时让位,否则季号未知的 + * 记录会整条从列表消失。 + */ + private static boolean supersededByOwnSeasonSnapshot(History item, List progress) { + if (item == null || progress == null || progress.isEmpty()) return false; + if (!"tv".equalsIgnoreCase(item.getMediaType()) || item.getTmdbId() <= 0) return false; + if (item.getTmdbSeasonNumber() >= 0) return false; + for (TmdbSeasonProgress snapshot : progress) { + if (snapshot == null || snapshot.episodeNumber <= 0 || snapshot.seasonNumber < 0) continue; + if (snapshot.cid != item.getCid() || snapshot.tmdbId != item.getTmdbId()) continue; + if (!"tv".equals(TmdbSeasonProgress.normalizeMediaType(snapshot.mediaType))) continue; + if (snapshot.sourceHistoryKey.equals(item.getKey()) + && snapshot.updatedAt >= item.getCreateTime()) return true; + } + return false; + } + private static List sort(List items) { items.sort((first, second) -> Long.compare(second.getCreateTime(), first.getCreateTime())); return items; diff --git a/app/src/main/java/com/fongmi/android/tv/model/SiteViewModel.java b/app/src/main/java/com/fongmi/android/tv/model/SiteViewModel.java index ac638f063f..0fa898bb71 100644 --- a/app/src/main/java/com/fongmi/android/tv/model/SiteViewModel.java +++ b/app/src/main/java/com/fongmi/android/tv/model/SiteViewModel.java @@ -142,6 +142,11 @@ public class SiteViewModel extends ViewModel { execute(TaskType.PLAYER, player, () -> SiteApi.playerContent(key, flag, id)); } + /** 按指定内核取播放地址:取址要按内核区分线路,所以内核必须显式传入而不是读全局默认。 */ + public void playerContent(String key, String flag, String id, int playerType) { + execute(TaskType.PLAYER, player, () -> SiteApi.playerContent(key, flag, id, playerType)); + } + public void searchContent(Site site, String keyword, boolean quick, String page) { long start = System.currentTimeMillis(); execute(TaskType.RESULT, result, SearchTask.create(site, keyword, quick, page), diff --git a/app/src/main/java/com/fongmi/android/tv/node/NodeBundle.java b/app/src/main/java/com/fongmi/android/tv/node/NodeBundle.java index ab019c611c..7f96520dc8 100644 --- a/app/src/main/java/com/fongmi/android/tv/node/NodeBundle.java +++ b/app/src/main/java/com/fongmi/android/tv/node/NodeBundle.java @@ -6,41 +6,54 @@ import android.text.TextUtils; import com.github.catvod.crawler.SpiderDebug; import com.github.catvod.net.OkHttp; import com.github.catvod.utils.Path; -import com.github.catvod.utils.Util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.security.MessageDigest; +import java.util.Locale; +import java.util.UUID; import okhttp3.Response; /** - * 猫源 bundle(CatPawOpen 的 {@code index.js})的下载与缓存。 + * 猫源 bundle(CatPawOpen 的 {@code index.js})的下载、校验与本地缓存。 * *

用户填的是 {@code .../index.js.md5}——那个地址返回 32 位校验值,真正的 bundle 在去掉 * {@code .md5} 后缀的地址上。每次启动只拉几十字节的 md5 比对,命中就用本地缓存, * 避免重复下载 1.2MB 的 bundle。 * - *

本地包(用户自己解压出来的 {@code index.js} + {@code index.config.js} 目录)走同一套 - * 缓存判定,只是把「下载」换成「复制」、把远端 md5 换成本地文件的实际 md5。 + *

本地包(用户自己解压出来的 {@code index.js} + {@code index.config.js} 目录,或还没解压 + * 的 zip)走同一套缓存判定,只是把「下载」换成「复制/解压」、把远端 md5 换成文件的实际 md5。 + * + *

不把运行目录直接指到用户选的位置:Node 要在 bundle 同级写 {@code data/}、{@code port}、 + * {@code boot.js},外部存储未必允许这些写入,且用户可能随时移走包。 */ public final class NodeBundle { private static final String SUFFIX = ".md5"; - - /** 本地包的判定文件,与 CatPawOpen 的发布约定一致。 */ private static final String MARKER = "index.js.md5"; + private static final String SOURCE_STAMP = "source.key"; + private static final long MAX_ENTRY_BYTES = 32L * 1024L * 1024L; + private static final int MAX_METADATA_BYTES = 4096; + private static final int MAX_SOURCE_KEY_BYTES = 16 * 1024; + /** 复用判定要抢在用户感知之前给结论,慢比错更难接受,所以比下载超时短得多。 */ + private static final long METADATA_TIMEOUT_MS = 3_000L; - /** 包内文件名。指到单个文件时只认这几个,否则任何与包同目录的文件都会被误判成本地包。 */ private static final java.util.Set MEMBERS = new java.util.HashSet<>(java.util.Arrays.asList( "index.js", MARKER, "index.config.js", "index.config.js.md5")); private NodeBundle() { } - /** 是不是本地包(解压好的目录,或还没解压的 zip)。做 IO,异常一律当成不是。 */ public static boolean isLocal(String url) { try { File root = Path.root(); @@ -50,73 +63,153 @@ public final class NodeBundle { } } - /** - * 解析本地包所在目录。 - * - *

接受三种写法:{@code file:/} 开头的相对外部存储路径(选择器生成的那种)、 - * 裸绝对路径、以及直接指向解压出来的目录。指到目录时要求里面有 {@code index.js.md5}, - * 否则无法与「随便一个目录」区分。 - * - * @param root 外部存储根目录,用于还原选择器生成的相对路径;可为 null - * @return 本地包目录,不是本地包则返回 null - */ - static File localDir(String url, File root) { - File target = target(url, root); - if (target == null) return null; - if (target.isDirectory()) return new File(target, MARKER).exists() ? target : null; - // 只有包内那几个文件才顺推到父目录。否则用户把普通订阅 json 跟包放在同一个文件夹里, - // 那个 json 会被当成本地包,配置内容被整个忽略。 - if (!MEMBERS.contains(lower(target.getName()))) return null; - File parent = target.getParentFile(); - return parent != null && new File(parent, MARKER).exists() ? parent : null; + static boolean isMd5(String value) { + if (value == null || value.length() != 32) return false; + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) return false; + } + return true; } /** - * 解析还没解压的本地包 zip。发布出来的包就是这个形态,选一个文件比让用户在目录树里 - * 定位到解压后的文件夹省事。 + * 本地包(目录或 zip)的来源身份:路径 + 两个文件的内容指纹。 * - * @return 含 {@code index.js.md5} 的 zip,不是则返回 null + *

远端来源不走这里——它的身份要带上服务端公布的校验值,见 {@link #remoteSourceKey}。 + * 早先这里对远端会自己发两次 md5 请求,那让「算身份」这件事变成有网络副作用的操作。 */ + static String sourceKey(String url) { + return sourceKey(url, root()); + } + + /** + * {@code root} 必须与 {@link #ensure} 用的是同一个,否则相对路径可能解析到不同文件—— + * 那会让指纹算的是 A 包、装的是 B 包。单测传 {@code null} 以避开 Environment。 + */ + static String sourceKey(String url, File root) { + if (TextUtils.isEmpty(url)) return ""; + String value = url.trim(); + try { + File local = localDir(value, root); + if (local != null) { + String bundle = contentSignature(new File(local, "index.js")); + String config = contentSignature(new File(local, "index.config.js")); + if (TextUtils.isEmpty(bundle) || TextUtils.isEmpty(config)) return ""; + return localSourceKey(local, bundle, config); + } + File zip = localZip(value, root); + if (zip != null) return zipSourceKey(zip); + } catch (Throwable ignored) { + } + return ""; + } + + /** + * 远端身份必须带上服务端公布的校验值,否则「同一个 URL」就等于「同一份内容」—— + * 服务端原地更新 bundle(URL 不变、md5 变了)时会继续复用旧的运行缓存,跑的还是旧 JS。 + * + *

拿不到校验值时返回空串:宁可当作身份未知重新走一遍 ensure,也不能凭 URL 相等就复用。 + */ + static String remoteSourceKey(String url, String bundleMd5, String configMd5) { + if (!isMd5(bundleMd5) || !isMd5(configMd5)) return ""; + return "remote:" + bundleUrl(url) + ":" + lower(bundleMd5) + ":" + lower(configMd5); + } + + /** + * 已安装的来源键是否就是这个远端地址的(不比对内容,只看归属)。 + * + *

也接受旧版本落盘的 {@code remote:}(无内容指纹):否则老用户升级后在断网 + * 状态下会被判成「没有该地址的缓存」,尽管两个文件都完好躺在磁盘上。 + */ + static boolean installedIsRemoteOf(String installed, String url) { + if (TextUtils.isEmpty(installed)) return false; + String prefix = "remote:" + bundleUrl(url); + return installed.startsWith(prefix + ":") || installed.equals(prefix); + } + + /** 从已安装的来源键里取出安装时已校验过的两个 md5,用于离线交叉校验。旧格式返回空。 */ + static String[] installedDigests(String installed) { + if (TextUtils.isEmpty(installed)) return new String[]{"", ""}; + int config = installed.lastIndexOf(':'); + if (config <= 0) return new String[]{"", ""}; + int bundle = installed.lastIndexOf(':', config - 1); + if (bundle <= 0) return new String[]{"", ""}; + String bundleMd5 = installed.substring(bundle + 1, config); + String configMd5 = installed.substring(config + 1); + if (!isMd5(bundleMd5) || !isMd5(configMd5)) return new String[]{"", ""}; + return new String[]{bundleMd5, configMd5}; + } + + /** + * 运行中的猫源是否仍与来源一致,决定能否跳过重启直接复用。 + * + *

判据是完整的来源身份(路径/地址 + 两个文件的内容指纹),而不是地址相等: + * 本地包被改写、或服务端原地更新了 bundle,都必须重启才能跑上新内容。 + * + *

远端拿不到校验值时(断网、404)退回「这份缓存确实属于该地址」——此时 + * {@link #ensureRemote} 也只会启用已校验过的缓存,两处口径一致,不会因为一次 + * 网络抖动就把正在正常服务的 Node 杀掉重启。 + */ + static boolean servesCurrentSource(String url, String servingKey) { + if (TextUtils.isEmpty(servingKey)) return false; + if (!isRemote(url)) { + String key = sourceKey(url); + return !TextUtils.isEmpty(key) && key.equals(servingKey); + } + String bundleMd5 = remoteMd5(url); + String configMd5 = remoteMd5(configUrl(url)); + String key = remoteSourceKey(url, bundleMd5, configMd5); + if (!TextUtils.isEmpty(key)) return key.equals(servingKey); + return installedIsRemoteOf(servingKey, url); + } + + private static File root() { + try { + return Path.root(); + } catch (Throwable ignored) { + return null; + } + } + + static File localDir(String url, File root) { + File target = target(url, root); + if (target == null) return null; + if (target.isDirectory()) return new File(target, MARKER).isFile() ? target : null; + if (!MEMBERS.contains(lower(target.getName()))) return null; + File parent = target.getParentFile(); + return parent != null && new File(parent, MARKER).isFile() ? parent : null; + } + static File localZip(String url, File root) { File target = target(url, root); - if (target == null || !target.isFile()) return null; - if (!lower(target.getName()).endsWith(".zip")) return null; + if (target == null || !target.isFile() || !lower(target.getName()).endsWith(".zip")) return null; try (java.util.zip.ZipFile zip = new java.util.zip.ZipFile(target)) { - return zip.getEntry(MARKER) != null ? target : null; + java.util.zip.ZipEntry marker = zip.getEntry(MARKER); + return marker != null && !marker.isDirectory() ? target : null; } catch (Exception ignored) { return null; } } - /** - * 固定用 ROOT 折叠大小写。土耳其语等 locale 下 {@code "INDEX.JS"} 的默认小写会把 I 变成 ı, - * 那样文件名和 scheme 的比对都会落空。 - */ private static String lower(String value) { - return value == null ? "" : value.toLowerCase(java.util.Locale.ROOT); + return value == null ? "" : value.toLowerCase(Locale.ROOT); } - /** 能直接下载的地址。非此即彼:不是远端就只能当本地路径处理。 */ static boolean isRemote(String url) { if (TextUtils.isEmpty(url)) return false; String value = lower(url.trim()); return value.startsWith("http://") || value.startsWith("https://"); } - /** 把配置里存的地址还原成本地文件;远端地址返回 null。 */ private static File target(String url, File root) { if (TextUtils.isEmpty(url) || isRemote(url)) return null; String path = url.trim(); - String lower = lower(path); - if (lower.startsWith("file://")) path = path.substring(7); - else if (lower.startsWith("file:/")) path = path.substring(6); + String value = lower(path); + if (value.startsWith("file://")) path = path.substring(7); + else if (value.startsWith("file:/")) path = path.substring(6); return resolve(path, root); } - /** - * 选择器给的是相对外部存储的路径({@code file://Download/x} 这种),用户手输的是绝对路径, - * 而从 content URI 落地的缓存文件去掉 {@code file:/} 后会变成丢了根斜杠的绝对路径——三种都试。 - */ private static File resolve(String path, File root) { if (TextUtils.isEmpty(path)) return null; if (root != null) { @@ -129,17 +222,16 @@ public final class NodeBundle { return rooted.exists() ? rooted : null; } - /** 用户填 .md5 地址(约定如此),也容忍直接填 bundle 地址。 */ public static String bundleUrl(String url) { if (TextUtils.isEmpty(url)) return ""; String trimmed = url.trim(); - return trimmed.endsWith(SUFFIX) ? trimmed.substring(0, trimmed.length() - SUFFIX.length()) : trimmed; + return lower(trimmed).endsWith(SUFFIX) ? trimmed.substring(0, trimmed.length() - SUFFIX.length()) : trimmed; } public static String md5Url(String url) { if (TextUtils.isEmpty(url)) return ""; String trimmed = url.trim(); - return trimmed.endsWith(SUFFIX) ? trimmed : trimmed + SUFFIX; + return lower(trimmed).endsWith(SUFFIX) ? trimmed : trimmed + SUFFIX; } public static File dir(Context context) { @@ -149,24 +241,38 @@ public final class NodeBundle { } public static File file(Context context) { - return new File(dir(context), "index.js"); + return file(dir(context)); } - /** - * bundle 的配置文件。服务端会在里面自动写好 {@code server.url} 和 {@code authorization}, - * 且各站点的配置项(如 {@code ffm3u8.url})都得由它提供——传空对象会让 bundle 在 - * 注册/首个请求阶段抛 undefined。 - */ public static File config(Context context) { - return new File(dir(context), "index.config.js"); + return config(dir(context)); } - private static File stamp(Context context) { - return new File(dir(context), "index.js.md5"); + static String installedSourceKey(Context context) { + return read(sourceStamp(dir(context))); } - private static File configStamp(Context context) { - return new File(dir(context), "index.config.js.md5"); + // 以下都按运行目录取文件,而不是按 Context——单测无法构造 Context(抽象方法太多), + // 但只要能传目录,ensure/install/isCached/sweep 全都可以做真实行为测试。 + + private static File file(File dir) { + return new File(dir, "index.js"); + } + + private static File config(File dir) { + return new File(dir, "index.config.js"); + } + + private static File stamp(File dir) { + return new File(dir, "index.js.md5"); + } + + private static File configStamp(File dir) { + return new File(dir, "index.config.js.md5"); + } + + private static File sourceStamp(File dir) { + return new File(dir, SOURCE_STAMP); } private static String configUrl(String url) { @@ -175,101 +281,227 @@ public final class NodeBundle { return slash < 0 ? bundle : bundle.substring(0, slash + 1) + "index.config.js"; } - /** - * 确保本地 bundle 与远端一致。 - * - * @return null 表示就绪,否则是失败原因 - */ public static synchronized String ensure(Context context, String url) { - File root = Path.root(); - File source = localDir(url, root); - if (source != null) return ensureLocal(context, source); - File zip = localZip(url, root); - if (zip != null) return ensureZip(context, zip); - // 走到这里必须是能下载的地址。本地包在主进程判定、在 :node 子进程加载,中间用户挪走了包 - // 就会落到这儿;下面那套逻辑对拿不到 md5 一律「复用已有缓存」,会把上一个源的 bundle - // 当成就绪跑起来——用户选了 A 却加载出 B。所以这里如实报错。 - if (!isRemote(url)) return "猫源地址无法访问,本地包可能已被移动:" + url; - try { - File bundle = file(context); - String remote = remoteMd5(url); - if (bundle.exists() && bundle.length() > 0) { - String local = read(stamp(context)); - // 远端拿不到 md5(离线等)时不该阻断,已有缓存就先用着。 - // 但配置仍要单独校验——服务端改夸克 Cookie 这类操作只会变 index.config.js, - // bundle 的 md5 不变,早退会导致新配置永远拉不到。 - if (TextUtils.isEmpty(remote) || remote.equalsIgnoreCase(local)) return ensureConfig(context, url); - } else if (TextUtils.isEmpty(remote)) { - remote = ""; - } - String error = download(bundleUrl(url), bundle); - if (error != null) return error; - String actual = TextUtils.isEmpty(remote) ? Util.md5(bundle) : remote; - write(stamp(context), actual); - return ensureConfig(context, url); - } catch (Exception e) { - SpiderDebug.log("node", e); - return e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage(); - } + return ensure(dir(context), url); } - /** 配置文件同样带 .md5,按同一套缓存判定。 */ - private static String ensureConfig(Context context, String url) { - File target = config(context); - String remote = remoteMd5(configUrl(url)); - if (target.exists() && target.length() > 0) { - String local = read(configStamp(context)); - if (TextUtils.isEmpty(remote) || remote.equalsIgnoreCase(local)) return null; - } - String error = download(configUrl(url), target); - if (error != null) return error; - try { - write(configStamp(context), TextUtils.isEmpty(remote) ? Util.md5(target) : remote); - } catch (IOException ignored) { - } - return null; + static synchronized String ensure(File dir, String url) { + return ensure(dir, url, root()); + } + + /** {@code root} 与 {@link #sourceKey(String, File)} 必须一致,否则指纹和安装会指向不同文件。 */ + static synchronized String ensure(File dir, String url, File root) { + dir.mkdirs(); + sweep(dir); + File source = localDir(url, root); + if (source != null) return ensureLocal(dir, source); + File zip = localZip(url, root); + if (zip != null) return ensureZip(dir, zip); + if (!isRemote(url)) return "猫源地址无法访问,本地包可能已被移动:" + url; + return ensureRemote(dir, url); } /** - * 本地包:把用户目录里的 {@code index.js} / {@code index.config.js} 同步到运行目录。 + * 清掉上次被杀进程留下的 staging 目录和 backup 临时文件。 * - *

不能直接把运行目录指到用户选的位置——Node 会在 bundle 同级写 {@code data/}、 - * {@code port}、{@code boot.js},外部存储上这些写入未必被允许,且用户可能随时移走。 + *

换源时主进程 {@code stopService} 会触发 {@code NodeService.onDestroy} 里的 + * {@code killProcess},正在 install 的 finally 不会执行,残留最多可达几十 MB + * 且落在内部存储里,用户既看不到也删不掉。 * - *

用文件实际 md5 做缓存判定(而不是包里附带的 {@code .md5},那个只是发布者给的, - * 用户换了 index.js 却忘了改 md5 的话会同步不到)。 + *

backup 残留一律丢弃、不尝试当恢复点:那份内容是否完整无从判断,而丢掉最多 + * 多下一次,认错了却会把损坏的 bundle 当有效缓存跑起来。 */ - private static String ensureLocal(Context context, File dir) { - File bundle = new File(dir, "index.js"); - // 单独挑 index.js.md5 时系统选择器只会把那一个文件拷进来,同级找不到 index.js。 - // 提示要指向整个包,否则用户只看到「缺少 index.js」而不知道该改选什么。 - if (!bundle.exists() || bundle.length() == 0) return "本地包缺少 index.js,请选择整个包(zip 或解压后的文件夹)"; - File config = new File(dir, "index.config.js"); - if (!config.exists() || config.length() == 0) return "本地包缺少 index.config.js"; - try { - String error = sync(bundle, file(context), stamp(context)); - if (error != null) return error; - return sync(config, config(context), configStamp(context)); - } catch (Exception e) { - SpiderDebug.log("node", e); - return e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage(); + static void sweep(File dir) { + File[] files = dir.listFiles(); + if (files == null) return; + for (File file : files) { + String name = file.getName(); + // 该目录里没有需要保留的 .tmp:backup、writeAtomic 的临时文件都是过程产物。 + if (name.startsWith(".stage-")) cleanup(file); + else if (name.endsWith(".tmp")) deleteQuietly(file); } } - /** 源文件 md5 与落地戳一致就跳过复制,避免每次启动都搬 9MB。 */ - private static String sync(File source, File target, File stamp) throws IOException { - // 运行目录本身就满足本地包的判定(index.js + index.config.js + 那个 stamp 恰好叫 - // index.js.md5),用户真指到它时源和目标是同一个文件,开写就把 bundle 截断了。 - if (same(source, target)) return null; - String md5 = Util.md5(source); - if (target.exists() && target.length() > 0 && !TextUtils.isEmpty(md5) && md5.equalsIgnoreCase(read(stamp))) return null; - String error = copy(source, target); - if (error != null) return error; - write(stamp, TextUtils.isEmpty(md5) ? Util.md5(target) : md5); - return null; + private static String ensureLocal(File dir, File source) { + File bundle = new File(source, "index.js"); + File config = new File(source, "index.config.js"); + if (!bundle.isFile() || bundle.length() == 0) return "本地包缺少 index.js,请选择整个包(zip 或解压后的文件夹)"; + if (!config.isFile() || config.length() == 0) return "本地包缺少 index.config.js"; + if (same(bundle, file(dir)) || same(config, config(dir))) return "本地包不能指向 Node 运行目录"; + + File staging = null; + try { + staging = stagingDir(dir); + PreparedFile preparedBundle = prepareFile(bundle, new File(staging, "index.js")); + PreparedFile preparedConfig = prepareFile(config, new File(staging, "index.config.js")); + // 目录形态只在标记与内容不一致时告警,不阻断:解压出来的目录是用户可写的, + // 改 index.config.js 换站点、魔改 index.js 都是本地包的正常用法,marker 不会跟着更新。 + // 来源身份用的是实际内容指纹(见下面 localSourceKey),所以缓存判定仍然自洽。 + warnMarkerMismatch(source, MARKER, preparedBundle.md5()); + warnMarkerMismatch(source, "index.config.js.md5", preparedConfig.md5()); + String key = localSourceKey(source, preparedBundle.md5(), preparedConfig.md5()); + return install(dir, preparedBundle, preparedConfig, key); + } catch (Exception e) { + SpiderDebug.log("node", e); + return e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage(); + } finally { + cleanup(staging); + } + } + + /** + * 发布标记与实际内容不符时只记日志。 + * + *

zip 形态保持硬校验(压缩包内容用户改不了,不符就是包损坏),但解压后的目录里 + * 改配置是主要用法,硬校验会把一批当前可用的包判死,且用户没有自救路径。 + */ + private static void warnMarkerMismatch(File source, String name, String actual) { + String expected = readMarker(new File(source, name)); + if (!isMd5(expected) || expected.equalsIgnoreCase(actual)) return; + SpiderDebug.log("node", "local bundle %s says %s but content is %s, using actual content", name, expected, actual); + } + + private static String ensureZip(File dir, File zip) { + File staging = null; + try (java.util.zip.ZipFile file = new java.util.zip.ZipFile(zip)) { + String bundleExpected = readEntry(file, MARKER); + if (!isMd5(bundleExpected)) throw new IOException("本地包 index.js.md5 无效"); + String configExpected = readEntry(file, "index.config.js.md5"); + if (!TextUtils.isEmpty(configExpected) && !isMd5(configExpected)) throw new IOException("本地包 index.config.js.md5 无效"); + staging = stagingDir(dir); + PreparedFile bundle = prepareZipEntry(file, "index.js", new File(staging, "index.js"), bundleExpected); + PreparedFile config = prepareZipEntry(file, "index.config.js", new File(staging, "index.config.js"), configExpected); + return install(dir, bundle, config, localSourceKey(zip, bundle.md5(), config.md5())); + } catch (Exception e) { + SpiderDebug.log("node", e); + return "本地包解压失败: " + (e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()); + } finally { + cleanup(staging); + } + } + + private static String ensureRemote(File dir, String url) { + // 一次取齐校验值:来源键、缓存判定、下载校验全都用这两个值,避免重复请求。 + String expectedBundle = remoteMd5(url); + String expectedConfig = remoteMd5(configUrl(url)); + String key = remoteSourceKey(url, expectedBundle, expectedConfig); + // 两个校验值缺任何一个都算不出完整身份,此时只能靠已装好的缓存服务,不能下载未校验内容。 + if (TextUtils.isEmpty(key)) return ensureRemoteOffline(dir, url); + + boolean[] cached = remoteCacheState(dir, url, expectedBundle, expectedConfig); + boolean bundleCached = cached[0]; + boolean configCached = cached[1]; + if (bundleCached && configCached) { + refreshSourceKey(dir, key); + return null; + } + + File staging = null; + try { + staging = stagingDir(dir); + PreparedFile bundle = bundleCached + ? prepareFile(file(dir), new File(staging, "index.js")) + : download(bundleUrl(url), new File(staging, "index.js"), expectedBundle); + PreparedFile config = configCached + ? prepareFile(config(dir), new File(staging, "index.config.js")) + : download(configUrl(url), new File(staging, "index.config.js"), expectedConfig); + return install(dir, bundle, config, key); + } catch (Exception e) { + SpiderDebug.log("node", e); + return e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage(); + } finally { + cleanup(staging); + } + } + + /** + * 逐个文件判定远端缓存是否可用,返回 {@code [bundle, config]}。 + * + *

归属和内容要分开判:**不能**把本次算出的复合来源键(含两个文件的指纹)当成单个 + * 文件的缓存键。那样「服务端只改了 index.config.js」会连 index.js 一起判失效, + * 每次配置更新都重下整包。归属用落盘的键比(旧格式也认),内容各自比自己的校验值。 + * + * @return 长度 2 的数组,下标 0 是 index.js、1 是 index.config.js + */ + static boolean[] remoteCacheState(File dir, String url, String expectedBundle, String expectedConfig) { + String installed = read(sourceStamp(dir)); + if (!installedIsRemoteOf(installed, url)) return new boolean[]{false, false}; + return new boolean[]{ + isCached(file(dir), stamp(dir), sourceStamp(dir), installed, expectedBundle), + isCached(config(dir), configStamp(dir), sourceStamp(dir), installed, expectedConfig)}; + } + + /** + * 两个文件都命中缓存、但落盘的来源键不是当前身份时,就地补齐。 + * + *

典型来源是旧版本落盘的 {@code remote:}(没有内容指纹)。不补的话 + * {@link #servesCurrentSource} 每次都判定「身份不符」,于是每次加载配置都白白重启 + * 一遍 {@code :node} 子进程。 + * + *

调用方必须已确认两个文件的实际内容都等于服务端公布的校验值。这里再按两个 + * stamp 复核一遍:只读 32 字节、不重算哈希,代价可忽略,但能挡住「将来有人从别处 + * 调它」——那会静默写入一个与内容不符的身份,让下次复用判定认错。 + * + * @return 是否发生了改写 + */ + static boolean refreshSourceKey(File dir, String key) { + if (TextUtils.isEmpty(key) || key.equals(read(sourceStamp(dir)))) return false; + String[] digests = installedDigests(key); + if (!digests[0].equalsIgnoreCase(read(stamp(dir)))) return false; + if (!digests[1].equalsIgnoreCase(read(configStamp(dir)))) return false; + try { + writeAtomic(sourceStamp(dir), key); + // 只记摘要:来源键里含完整 URL,而猫源地址支持 user:pass@host 形式的凭据。 + SpiderDebug.log("node", "refreshed source key to digests %s/%s", digests[0], digests[1]); + return true; + } catch (Exception e) { + // 没写上只影响下次的复用判定(会多重启一次),不影响本次服务。 + SpiderDebug.log("node", e); + return false; + } + } + + /** + * 校验值不全(断网、404、返回 HTML)时的降级:继续用已经装好、且确实属于这个地址的 + * 缓存,绝不下载未校验的内容。没有可用缓存才报错。 + * + *

交叉校验的期望值**只能**取 {@code source.key} 里安装时已校验过的那两个 md5。 + * 用服务端这次拿到的新值去比旧缓存必然不等——那会把「暂时无法更新」误判成 + * 「缓存不可用」,让一次 config 校验值抖动就整个源起不来。 + */ + private static String ensureRemoteOffline(File dir, String url) { + String installed = read(sourceStamp(dir)); + if (!installedIsRemoteOf(installed, url)) return "猫源校验值不可用,且没有该地址的本地缓存:" + url; + String[] digests = installedDigests(installed); + boolean bundleCached = isCached(file(dir), stamp(dir), sourceStamp(dir), installed, digests[0]); + boolean configCached = isCached(config(dir), configStamp(dir), sourceStamp(dir), installed, digests[1]); + if (bundleCached && configCached) { + SpiderDebug.log("node", "remote md5 unavailable, keeping verified cache for %s", url); + return null; + } + return "猫源校验值不可用,本地缓存也不完整,无法安全启动:" + url; + } + + private static String remoteMd5(String url) { + // 校验值只有 32 字节,但走默认 30s 超时会把复用判定拖成半分钟的黑屏。 + try (Response response = OkHttp.newCall(OkHttp.client(METADATA_TIMEOUT_MS), md5Url(url), "node-bundle").execute()) { + if (!response.isSuccessful() || response.body() == null) return ""; + if (response.body().contentLength() > MAX_METADATA_BYTES) return ""; + try (InputStream in = response.body().byteStream()) { + String value = readLimited(in, MAX_METADATA_BYTES).trim(); + return isMd5(value) ? value : ""; + } + } catch (Exception ignored) { + return ""; + } + } + + private static PreparedFile prepareFile(File source, File target) throws IOException { + try (InputStream in = new FileInputStream(source)) { + return new PreparedFile(target, copyAndDigest(in, target)); + } } - /** 同一个文件(含符号链接/`..` 等写法差异)。取不到规范路径时退回绝对路径比较。 */ private static boolean same(File a, File b) { try { return a.getCanonicalFile().equals(b.getCanonicalFile()); @@ -278,107 +510,325 @@ public final class NodeBundle { } } - private static String copy(File source, File target) { - try (InputStream in = new FileInputStream(source)) { - pipe(in, target); - } catch (Exception e) { - SpiderDebug.log("node", e); - return "本地包复制失败: " + (e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()); - } - return target.length() > 0 ? null : "本地包 " + source.getName() + " 为空"; - } - - private static void pipe(InputStream in, File target) throws IOException { - try (FileOutputStream out = new FileOutputStream(target)) { - byte[] buf = new byte[65536]; - int len; - while ((len = in.read(buf)) != -1) out.write(buf, 0, len); - } - } - - /** - * 本地包 zip:直接把里面的 {@code index.js} / {@code index.config.js} 解到运行目录。 - * - *

缓存判定用 zip 里附带的 {@code .md5}(换包必然换这个值),拿不到就退回解压后的实际 md5。 - * 不做「先整体解压到临时目录再搬」——包里就这两个文件,逐条目写更省一次 9MB 的落盘。 - */ - private static String ensureZip(Context context, File zip) { - try (java.util.zip.ZipFile file = new java.util.zip.ZipFile(zip)) { - String error = unzip(file, "index.js", file(context), stamp(context), MARKER); - if (error != null) return error; - return unzip(file, "index.config.js", config(context), configStamp(context), "index.config.js.md5"); - } catch (Exception e) { - SpiderDebug.log("node", e); - return "本地包解压失败: " + (e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()); - } - } - - private static String unzip(java.util.zip.ZipFile zip, String name, File target, File stamp, String digestName) throws IOException { + private static PreparedFile prepareZipEntry(java.util.zip.ZipFile zip, String name, File target, String expected) throws IOException { java.util.zip.ZipEntry entry = zip.getEntry(name); - if (entry == null) return "本地包缺少 " + name; - String md5 = digest(zip, digestName); - if (target.exists() && target.length() > 0 && !TextUtils.isEmpty(md5) && md5.equalsIgnoreCase(read(stamp))) return null; + if (entry == null || entry.isDirectory()) throw new IOException("本地包缺少 " + name); + if (entry.getSize() > MAX_ENTRY_BYTES) throw new IOException("本地包 " + name + " 超过大小限制"); try (InputStream in = zip.getInputStream(entry)) { - pipe(in, target); - } - if (target.length() == 0) return "本地包 " + name + " 为空"; - write(stamp, TextUtils.isEmpty(md5) ? Util.md5(target) : md5); - return null; - } - - /** zip 里附带的校验值;缺失或格式不对时返回空串,由调用方退回实际 md5。 */ - private static String digest(java.util.zip.ZipFile zip, String name) { - java.util.zip.ZipEntry entry = zip.getEntry(name); - if (entry == null) return ""; - try (InputStream in = zip.getInputStream(entry)) { - byte[] buf = new byte[64]; - int len = in.read(buf); - if (len <= 0) return ""; - String value = new String(buf, 0, len).trim(); - return value.length() == 32 ? value : ""; - } catch (Exception ignored) { - return ""; + String actual = copyAndDigest(in, target); + if (isMd5(expected) && !expected.equalsIgnoreCase(actual)) throw new IOException("本地包 " + name + " 校验失败"); + return new PreparedFile(target, actual); } } - private static String remoteMd5(String url) { - try { - String text = OkHttp.string(md5Url(url)); - if (text == null) return ""; - String value = text.trim(); - return value.length() == 32 ? value : ""; - } catch (Exception ignored) { - return ""; - } - } - - private static String download(String url, File target) { - try (Response res = OkHttp.newCall(url, "node-bundle").execute()) { - if (!res.isSuccessful() || res.body() == null) return "bundle 下载失败 HTTP " + res.code(); - try (InputStream in = res.body().byteStream()) { - pipe(in, target); + private static PreparedFile download(String url, File target, String expected) throws IOException { + if (!isMd5(expected)) throw new IOException("bundle 校验值不可用"); + try (Response response = OkHttp.newCall(url, "node-bundle").execute()) { + if (!response.isSuccessful() || response.body() == null) throw new IOException("bundle 下载失败 HTTP " + response.code()); + try (InputStream in = response.body().byteStream()) { + String actual = copyAndDigest(in, target); + if (isMd5(expected) && !expected.equalsIgnoreCase(actual)) throw new IOException("bundle 校验失败"); + return new PreparedFile(target, actual); } - return target.length() > 0 ? null : "bundle 为空"; - } catch (Exception e) { - SpiderDebug.log("node", e); - return e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage(); } } - private static String read(File file) { - if (!file.exists()) return ""; - try (InputStream in = new java.io.FileInputStream(file)) { - byte[] buf = new byte[64]; - int len = in.read(buf); - return len <= 0 ? "" : new String(buf, 0, len).trim(); + /** 正式文件只在准备完成后替换,失败时恢复旧缓存。 */ + static String install(File dir, PreparedFile bundle, PreparedFile config, String sourceKey) { + File bundleTarget = file(dir); + File configTarget = config(dir); + File bundleBackup = null; + File configBackup = null; + boolean bundlePublished = false; + boolean configPublished = false; + File stamp = stamp(dir); + File configStamp = configStamp(dir); + File sourceStamp = sourceStamp(dir); + boolean oldStamp = stamp.isFile(); + boolean oldConfigStamp = configStamp.isFile(); + boolean oldSourceStamp = sourceStamp.isFile(); + String oldStampText = read(stamp); + String oldConfigStampText = read(configStamp); + String oldSourceStampText = read(sourceStamp); + try { + if (bundleTarget.isFile()) bundleBackup = backup(bundleTarget); + if (configTarget.isFile()) configBackup = backup(configTarget); + move(bundle.file(), bundleTarget); + bundlePublished = true; + move(config.file(), configTarget); + configPublished = true; + writeAtomic(stamp, bundle.md5()); + writeAtomic(configStamp, config.md5()); + writeAtomic(sourceStamp, sourceKey); + deleteQuietly(bundleBackup); + deleteQuietly(configBackup); + return null; + } catch (Exception e) { + boolean restored = true; + if (bundleBackup != null) restored = restore(bundleBackup, bundleTarget); + else if (bundlePublished) deleteQuietly(bundleTarget); + if (configBackup != null) restored &= restore(configBackup, configTarget); + else if (configPublished) deleteQuietly(configTarget); + restoreText(stamp, oldStamp, oldStampText); + restoreText(configStamp, oldConfigStamp, oldConfigStampText); + restoreText(sourceStamp, oldSourceStamp, oldSourceStampText); + // 回滚不完整时磁盘可能是「新 index.js + 旧 config」的混合态,而 stamp 已被恢复成旧值。 + // 删掉来源键把缓存标记为不可信,强制下次重新准备,而不是让 isCached 把混合态当有效缓存。 + if (!restored) { + SpiderDebug.log("node", "rollback incomplete, invalidating cache source key"); + deleteQuietly(sourceStamp); + } + SpiderDebug.log("node", e); + return "本地包写入失败: " + (e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()); + } + } + + static boolean isCached(File target, File stamp, File sourceStamp, String sourceKey, String expected) { + if (TextUtils.isEmpty(sourceKey) || !target.isFile() || target.length() == 0 || target.length() > MAX_ENTRY_BYTES) return false; + if (!sourceKey.equals(read(sourceStamp))) return false; + String local = read(stamp); + if (!isMd5(local)) return false; + String actual = contentSignature(target); + return isMd5(actual) && actual.equalsIgnoreCase(local) && (!isMd5(expected) || expected.equalsIgnoreCase(actual)); + } + + private static String readEntry(java.util.zip.ZipFile zip, String name) throws IOException { + java.util.zip.ZipEntry entry = zip.getEntry(name); + if (entry == null || entry.isDirectory() || entry.getSize() > MAX_METADATA_BYTES) return ""; + try (InputStream in = zip.getInputStream(entry)) { + return marker(readLimited(in, MAX_METADATA_BYTES)); + } + } + + /** 目录形态的发布标记,限长读取,缺失或过大都当作没有。 */ + private static String readMarker(File file) { + if (!file.isFile() || file.length() > MAX_METADATA_BYTES) return ""; + try (InputStream in = new FileInputStream(file)) { + return marker(readLimited(in, MAX_METADATA_BYTES)); } catch (IOException e) { return ""; } } - private static void write(File file, String text) throws IOException { - try (FileOutputStream out = new FileOutputStream(file)) { - out.write(text.getBytes()); + /** + * 取校验值本体。{@code md5sum > index.js.md5} 生成的是「{@code index.js}」, + * 只 trim 会让整行过不了 {@link #isMd5}——那会把本来能用的包判成「校验值无效」。 + */ + private static String marker(String text) { + String value = text == null ? "" : text.trim(); + int space = value.indexOf(' '); + if (space > 0) value = value.substring(0, space); + int tab = value.indexOf('\t'); + if (tab > 0) value = value.substring(0, tab); + return value; + } + + private static String zipSourceKey(File zip) { + try (java.util.zip.ZipFile file = new java.util.zip.ZipFile(zip)) { + if (!isMd5(readEntry(file, MARKER))) return ""; + String bundle = entryDigest(file, "index.js"); + String config = entryDigest(file, "index.config.js"); + String configMarker = readEntry(file, "index.config.js.md5"); + if (!isMd5(bundle) || !isMd5(config) || (!TextUtils.isEmpty(configMarker) && !isMd5(configMarker))) return ""; + return localSourceKey(zip, bundle, config); + } catch (Exception ignored) { + return ""; } } + + private static String entryDigest(java.util.zip.ZipFile zip, String name) throws IOException { + java.util.zip.ZipEntry entry = zip.getEntry(name); + if (entry == null || entry.isDirectory() || entry.getSize() > MAX_ENTRY_BYTES) return ""; + try (InputStream in = zip.getInputStream(entry)) { + MessageDigest digest = MessageDigest.getInstance("MD5"); + byte[] buffer = new byte[65536]; + long total = 0; + int length; + while ((length = in.read(buffer)) != -1) { + total += length; + if (total > MAX_ENTRY_BYTES) return ""; + digest.update(buffer, 0, length); + } + return total == 0 ? "" : hex(digest.digest()); + } catch (java.security.NoSuchAlgorithmException e) { + throw new IOException("MD5 不可用", e); + } + } + + private static String copyAndDigest(InputStream in, File target) throws IOException { + MessageDigest digest; + try { + digest = MessageDigest.getInstance("MD5"); + } catch (Exception e) { + throw new IOException("MD5 不可用", e); + } + File parent = target.getParentFile(); + if (parent != null) parent.mkdirs(); + long total = 0; + try (OutputStream out = new FileOutputStream(target)) { + byte[] buffer = new byte[65536]; + int length; + while ((length = in.read(buffer)) != -1) { + total += length; + if (total > MAX_ENTRY_BYTES) throw new IOException("文件超过大小限制"); + digest.update(buffer, 0, length); + out.write(buffer, 0, length); + } + } + if (total == 0) throw new IOException("文件为空"); + return hex(digest.digest()); + } + + private static File stagingDir(File dir) throws IOException { + File staging = new File(dir, ".stage-" + UUID.randomUUID()); + if (!staging.mkdirs()) throw new IOException("无法创建本地包临时目录"); + return staging; + } + + /** + * 用移动而不是复制:目标文件反正要被替换掉,同目录的 rename 是常数时间, + * 而复制要多读写一遍最多 32 MiB。复制还会顺带算一个用不上的 MD5,且对 0 字节 + * 目标文件抛「文件为空」——那会让残缺缓存永久无法自愈。 + */ + private static File backup(File target) throws IOException { + File backup = File.createTempFile(target.getName() + ".backup-", ".tmp", target.getParentFile()); + try { + move(target, backup); + return backup; + } catch (Exception e) { + deleteQuietly(backup); + throw e; + } + } + + /** @return 是否成功恢复;失败意味着磁盘停在混合态,调用方要把缓存标记为不可信。 */ + private static boolean restore(File backup, File target) { + if (backup == null || !backup.exists()) return true; + try { + move(backup, target); + return true; + } catch (Exception e) { + SpiderDebug.log("node", e); + return false; + } + } + + private static void restoreText(File target, boolean existed, String text) { + try { + if (existed) writeAtomic(target, text); + else deleteQuietly(target); + } catch (Exception e) { + SpiderDebug.log("node", e); + } + } + + private static void writeAtomic(File target, String text) throws IOException { + File parent = target.getParentFile(); + if (parent != null) parent.mkdirs(); + File temporary = File.createTempFile(target.getName() + ".", ".tmp", parent); + try { + try (FileOutputStream out = new FileOutputStream(temporary)) { + out.write((text == null ? "" : text).getBytes(StandardCharsets.UTF_8)); + } + move(temporary, target); + } finally { + deleteQuietly(temporary); + } + } + + private static void move(File source, File target) throws IOException { + try { + Files.move(source.toPath(), target.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } catch (AtomicMoveNotSupportedException e) { + Files.move(source.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING); + } + } + + private static String localSourceKey(File source, String bundleDigest, String configDigest) { + return "local:" + canonical(source) + ":" + bundleDigest + ":" + configDigest; + } + + private static String contentSignature(File file) { + return file.isFile() ? digestFile(file) : ""; + } + + private static String digestFile(File file) { + if (file.length() <= 0 || file.length() > MAX_ENTRY_BYTES) return ""; + try (InputStream in = new FileInputStream(file)) { + return digestStream(in, MAX_ENTRY_BYTES); + } catch (IOException e) { + return ""; + } + } + + private static String digestStream(InputStream in, long maxBytes) throws IOException { + MessageDigest digest; + try { + digest = MessageDigest.getInstance("MD5"); + } catch (Exception e) { + throw new IOException("MD5 不可用", e); + } + byte[] buffer = new byte[65536]; + long total = 0; + int length; + while ((length = in.read(buffer)) != -1) { + total += length; + if (total > maxBytes) return ""; + digest.update(buffer, 0, length); + } + return total == 0 ? "" : hex(digest.digest()); + } + + private static String canonical(File file) { + try { + return file.getCanonicalPath(); + } catch (IOException e) { + return file.getAbsolutePath(); + } + } + + private static String hex(byte[] bytes) { + StringBuilder value = new StringBuilder(bytes.length * 2); + for (byte item : bytes) value.append(String.format(Locale.ROOT, "%02x", item & 0xff)); + return value.toString(); + } + + private static String read(File file) { + if (file == null || !file.isFile()) return ""; + try (InputStream in = new FileInputStream(file)) { + return readLimited(in, MAX_SOURCE_KEY_BYTES).trim(); + } catch (IOException e) { + return ""; + } + } + + private static String readLimited(InputStream in, int maxBytes) throws IOException { + ByteArrayOutputStream output = new ByteArrayOutputStream(Math.min(maxBytes, 256)); + byte[] buffer = new byte[256]; + int total = 0; + int length; + while ((length = in.read(buffer)) != -1) { + total += length; + if (total > maxBytes) throw new IOException("文本超过大小限制"); + output.write(buffer, 0, length); + } + return total == 0 ? "" : output.toString(StandardCharsets.UTF_8.name()); + } + + private static void cleanup(File directory) { + if (directory == null) return; + File[] files = directory.listFiles(); + if (files != null) for (File file : files) deleteQuietly(file); + deleteQuietly(directory); + } + + private static void deleteQuietly(File file) { + // 不用 deleteOnExit 兜底:Android 上进程被 kill,shutdown hook 不跑, + // 只会把路径永久留在 DeleteOnExitHook 里。残留交给 sweep() 下次启动清。 + if (file != null && file.exists() && !file.delete()) SpiderDebug.log("node", "failed to delete %s", file.getAbsolutePath()); + } + + /** 准备好、已算过摘要、等待发布到运行目录的文件。package-private 以便直测 install 的回滚。 */ + record PreparedFile(File file, String md5) { + } } diff --git a/app/src/main/java/com/fongmi/android/tv/node/NodeRuntime.java b/app/src/main/java/com/fongmi/android/tv/node/NodeRuntime.java index 62ca2722e3..d6cf9dff05 100644 --- a/app/src/main/java/com/fongmi/android/tv/node/NodeRuntime.java +++ b/app/src/main/java/com/fongmi/android/tv/node/NodeRuntime.java @@ -17,6 +17,7 @@ import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; /** * 猫源运行时:主进程侧的协调层。 @@ -40,11 +41,13 @@ public final class NodeRuntime { private static final AtomicBoolean STARTING = new AtomicBoolean(false); private static volatile boolean running; private static volatile String servingUrl = ""; - private static volatile long startGeneration; + private static volatile String servingSourceKey = ""; + /** 每轮启动的世代号,用来丢弃旧子进程的延迟回报。 */ + private static final AtomicLong START_GENERATION = new AtomicLong(); - /** 主进程侧的回复 Messenger,接收子进程回报。 */ - private static Messenger replyMessenger; - private static NodeRuntime.Callback pendingCallback; + /** 主进程侧的回复 Messenger,接收子进程回报。写在后台线程、读在主线程,必须 volatile。 */ + private static volatile Messenger replyMessenger; + private static volatile NodeRuntime.Callback pendingCallback; public interface Callback { void onProgress(String message); @@ -78,23 +81,25 @@ public final class NodeRuntime { * * @param url 用户填的猫源地址({@code .../index.js.md5}) */ - public static void start(Context context, String url, Callback callback) { + public static synchronized void start(Context context, String url, Callback callback) { if (TextUtils.isEmpty(url)) { if (callback != null) callback.onError("未填写猫源地址"); return; } - // 同一个 bundle 已就绪:直接复用 - if (running && same(url)) { + // 复用要求「同一地址」且「来源身份仍与运行中的一致」:只比地址的话,服务端原地更新 + // bundle、或本地包被改写后都会继续跑旧 JS。本地包按内容指纹判定,内容没变就无需重启。 + if (running && same(url) && NodeBundle.servesCurrentSource(url, servingSourceKey)) { if (callback != null) callback.onReady(baseUrl()); return; } - if (!STARTING.compareAndSet(false, true)) { - if (callback != null) callback.onError("正在启动中"); - return; + if (!STARTING.compareAndSet(false, true)) { + if (callback != null) callback.onError("正在启动中"); + return; } + long generation = START_GENERATION.incrementAndGet(); pendingCallback = callback; - replyMessenger = new Messenger(new ReplyHandler()); - // 换源:先杀旧子进程(如果有),再起新的 + replyMessenger = new Messenger(new ReplyHandler(generation)); + // 换源:先杀旧子进程(如果有),再起新的 if (running || !TextUtils.isEmpty(servingUrl)) { SpiderDebug.log("node", "switching source: stopping old node service (was=%s)", servingUrl); notifyProgress(context, callback, context.getString(R.string.node_stopping)); @@ -103,29 +108,36 @@ public final class NodeRuntime { // 不等的话 startForegroundService 会投递到还没死掉的旧进程,node::Start 第二次调用会 SIGSEGV。 waitForProcessDeath(context); running = false; + servingSourceKey = ""; port = 0; notifyProgress(context, callback, context.getString(R.string.node_switch_restart)); } servingUrl = NodeBundle.bundleUrl(url); + servingSourceKey = ""; try { NodeService.start(context, url, replyMessenger); - long generation = ++startGeneration; App.post(() -> timeout(context, generation), START_TIMEOUT_MS); } catch (RuntimeException e) { STARTING.set(false); running = false; servingUrl = ""; + servingSourceKey = ""; port = 0; + pendingCallback = null; + replyMessenger = null; SpiderDebug.log("node", "failed to start node service: %s", e.getMessage()); if (callback != null) callback.onError("猫源服务启动失败: " + e.getMessage()); } } - private static void timeout(Context context, long generation) { - if (generation != startGeneration || !STARTING.compareAndSet(true, false)) return; + private static synchronized void timeout(Context context, long generation) { + if (generation != START_GENERATION.get() || !STARTING.compareAndSet(true, false)) return; + // 先让当前 reply handler 失效:stopService 是异步的,旧 :node 仍可能在退出前发 READY。 + // 同时保留 servingUrl,让下一次 start 先等待这个旧进程真的结束,不能把重试投给旧 Service。 + START_GENERATION.incrementAndGet(); NodeService.stop(context); running = false; - servingUrl = ""; + servingSourceKey = ""; port = 0; NodeNotify.done(context, "猫源启动失败:服务未在预期时间内就绪"); Notify.show("猫源启动失败:服务未在预期时间内就绪"); @@ -138,7 +150,7 @@ public final class NodeRuntime { /** 是否就是当前这个 bundle。 */ private static boolean same(String url) { String requested = NodeBundle.bundleUrl(url); - return !TextUtils.isEmpty(requested) && requested.equals(servingUrl); + return !TextUtils.isEmpty(requested) && requested.equals(servingUrl); } /** 换源等主进程侧阶段进度:同时推通知栏和 callback。 */ @@ -171,19 +183,33 @@ public final class NodeRuntime { return false; } - /** 主进程侧处理子进程通过 Messenger 回报的消息。 */ + /** + * 主进程侧处理子进程通过 Messenger 回报的消息。 + * + *

每轮 start 都带自己的 generation:旧 :node 进程可能在 waitForProcessDeath 的 3 秒后 + * 还活着并继续回报,若不校验就会把旧端口写进新一轮的 port/servingSourceKey, + * 表现为「选了 B 源却连到 A 源」,同时把新一轮的 callback 吃掉。 + */ private static class ReplyHandler extends Handler { - ReplyHandler() { + private final long generation; + + ReplyHandler(long generation) { super(Looper.getMainLooper()); + this.generation = generation; } @Override public void handleMessage(Message msg) { + if (generation != START_GENERATION.get()) { + SpiderDebug.log("node", "ignoring stale node reply what=%d gen=%d current=%d", msg.what, generation, START_GENERATION.get()); + return; + } NodeRuntime.Callback callback = pendingCallback; switch (msg.what) { case NodeService.MSG_READY: { port = msg.arg1; running = true; + servingSourceKey = NodeBundle.installedSourceKey(App.get()); STARTING.set(false); pendingCallback = null; replyMessenger = null; @@ -203,6 +229,7 @@ public final class NodeRuntime { String text = msg.getData() != null ? msg.getData().getString("text") : "未知错误"; STARTING.set(false); running = false; + servingSourceKey = ""; pendingCallback = null; replyMessenger = null; NodeNotify.done(App.get(), "猫源启动失败:" + text); diff --git a/app/src/main/java/com/fongmi/android/tv/node/NodeService.java b/app/src/main/java/com/fongmi/android/tv/node/NodeService.java index f895c8af95..2e930c4ac5 100644 --- a/app/src/main/java/com/fongmi/android/tv/node/NodeService.java +++ b/app/src/main/java/com/fongmi/android/tv/node/NodeService.java @@ -226,6 +226,7 @@ public class NodeService extends Service { msg.setData(data); try { reply.send(msg); + stopSelf(); } catch (RemoteException ignored) { } } diff --git a/app/src/main/java/com/fongmi/android/tv/player/DolbyVisionFormatLabel.java b/app/src/main/java/com/fongmi/android/tv/player/DolbyVisionFormatLabel.java index 1d7cc91f0f..e9b4d53981 100644 --- a/app/src/main/java/com/fongmi/android/tv/player/DolbyVisionFormatLabel.java +++ b/app/src/main/java/com/fongmi/android/tv/player/DolbyVisionFormatLabel.java @@ -12,7 +12,7 @@ public final class DolbyVisionFormatLabel { public static String formatName(PlayerEngine.VideoPlaybackDetails details) { if (details == null || !details.hasDolbyVisionSource()) return ""; - return "Dolby Vision DV." + profile(details.dolbyVisionProfile()); + return "Dolby Vision DV." + profile(sourceProfile(details)); } public static String codecText(PlayerEngine.VideoPlaybackDetails details) { @@ -37,6 +37,20 @@ public final class DolbyVisionFormatLabel { return (comma < 0 ? value : value.substring(0, comma)).trim(); } + private static int sourceProfile(PlayerEngine.VideoPlaybackDetails details) { + String codec = firstCodec(details.sourceCodecs()).toLowerCase(Locale.US); + if (codec.startsWith("dvhe.") || codec.startsWith("dvh1.")) { + int end = codec.indexOf('.', 5); + String value = end < 0 ? codec.substring(5) : codec.substring(5, end); + try { + int profile = Integer.parseInt(value); + if (profile > 0) return profile; + } catch (NumberFormatException ignored) { + } + } + return details.dolbyVisionProfile(); + } + private static String profile(int value) { return String.format(Locale.US, "%02d", value); } diff --git a/app/src/main/java/com/fongmi/android/tv/player/PlayerManager.java b/app/src/main/java/com/fongmi/android/tv/player/PlayerManager.java index 8efa519584..29242c8841 100644 --- a/app/src/main/java/com/fongmi/android/tv/player/PlayerManager.java +++ b/app/src/main/java/com/fongmi/android/tv/player/PlayerManager.java @@ -100,6 +100,7 @@ import com.fongmi.android.tv.player.lut.MpvLutShaderFactory; import com.fongmi.android.tv.player.mpv.MpvAutoController; import com.fongmi.android.tv.player.mpv.MpvAutoControlPolicy; import com.fongmi.android.tv.player.mpv.MpvAutoOutputPolicy; +import com.fongmi.android.tv.player.mpv.MpvAutoRenderPolicy; import com.fongmi.android.tv.player.mpv.MpvBackCacheController; import com.fongmi.android.tv.player.mpv.MpvBackCachePolicy; import com.fongmi.android.tv.player.mpv.MpvCacheTargetCoordinator; @@ -140,6 +141,8 @@ import com.github.catvod.crawler.SpiderDebug; import com.github.catvod.net.OkHttp; import com.google.common.net.HttpHeaders; +import is.xyz.mpv.MPVLib; + import java.io.IOException; import java.text.DecimalFormat; import java.util.ArrayList; @@ -301,10 +304,13 @@ public class PlayerManager implements ParseCallback { private boolean lutAllowed = true; private boolean manualPlayerSwitchPending; private boolean mpvAutoOutputEvaluated; + private boolean mpvAutoOutputFrameReady; private boolean mpvAutoOutputEvaluationScheduled; private boolean mpvAutoOutputProbeGaveUp; private boolean mpvExplicitSubtitlePreference; private boolean mpvAutoGpuPinnedForSession; + private boolean mpvAutoVulkanPinnedForItem; + private boolean mpvAutoVulkanDisabledForItem; private boolean mpvSurfaceFallbackTried; private boolean mpvVulkanFallbackTried; private boolean mpvCopyFallbackTried; @@ -400,7 +406,10 @@ public class PlayerManager implements ParseCallback { onNativeAudioBecomingNoisy(); } }; - this.playerType = PlayerSetting.getPlayer(); + // 播放页可能在服务起来之前就定好了本次要用的内核(按剧集记住的选择), + // 所以这里读会话内核;没有会话时它自然退回设置页的全局默认。 + this.playerType = PlayerSetting.getActivePlayer(); + PlayerSetting.putActivePlayer(this.playerType); this.playerFallbackTried = new boolean[PLAYER_COUNT]; clearFfmpegModeFallbackState(); this.adAudioRuntime = new AdAudioRuntimeController( @@ -417,12 +426,14 @@ public class PlayerManager implements ParseCallback { public void release() { mediaSession.beforeRelease(); + PlayerSetting.clearActivePlayer(); adAudioRuntime.close(); prepareSeq++; exoSpeedRestoreState.clear(); lutApplySeq++; clearFfmpegModeFallbackState(); ffmpegModeEngine = PlayerSetting.NONE; + prepareTerminalRelease(); resetNetworkProtectionSession("release"); clearExoDecoderResourceRecovery(true); player.removeListener(listener); @@ -448,6 +459,8 @@ public class PlayerManager implements ParseCallback { pendingIjkRuntimeFallbackReparse = false; closeMultiThreadProxyRegistration(); mpvAutoGpuPinnedForSession = false; + mpvAutoVulkanPinnedForItem = false; + mpvAutoVulkanDisabledForItem = false; if (engine == null) { mediaSession.close(); return; @@ -472,6 +485,10 @@ public class PlayerManager implements ParseCallback { lastLoggedRouteTraceId = PlaybackTrace.NONE; } + public void prepareTerminalRelease() { + if (engine instanceof MpvPlayerEngine mpv) mpv.prepareTerminalRelease(); + } + private boolean experimentAllowed(PlaybackExperimentPolicy.Action action) { return PlaybackExperimentSetting.isAllowed(action); } @@ -914,7 +931,7 @@ public class PlayerManager implements ParseCallback { } public String getAudioPassThroughText() { - if (!PlayerSetting.isAudioPassThrough()) return "关"; + if (!PlayerSetting.isAudioPassThrough(playerType)) return "关"; if (!isMpv()) return "开"; String codecs = engine == null ? "" : engine.getAudioSpdifCodecs(); return TextUtils.isEmpty(codecs) ? "开/PCM" : "开/" + codecs; @@ -1155,7 +1172,8 @@ public class PlayerManager implements ParseCallback { && MpvPerformanceSetting.isAutoSurfaceDirectEnabled() && MpvPerformanceSetting.getOutputMode() == MpvPerformanceSetting.OUTPUT_AUTO && !mpvAutoOutputEvaluated - && !mpvAutoOutputProbeGaveUp; + && !mpvAutoOutputProbeGaveUp + && !mpvAutoOutputFrameReady; } public boolean isExo() { @@ -1687,6 +1705,16 @@ public class PlayerManager implements ParseCallback { ijkRealtimeRecoveryController.onUserSeek(playbackAutoSession, now); ijkDecodePressureController.onUserSeek(playbackAutoSession, now); resetNetworkProtectionSession("user-seek"); + if (isExo()) { + PlaybackAnalyticsListener.onUserSeekRequested( + player.getCurrentPosition(), + time, + player.getPlaybackState(), + player.getBufferedPosition(), + player.getTotalBufferedDuration(), + player.isLoading(), + player.isPlaying()); + } player.seekTo(time); // A seek has no timeout of its own; without this the session can sit in // BUFFERING indefinitely waiting on the rebuffer threshold. Arm after the @@ -1899,11 +1927,38 @@ public void resetTrack(int type) { } public void switchPlayer(int type) { - switchPlayer(type, true, false); + switchPlayer(type, false); } public void switchPlayerManually(int type) { - switchPlayer(type, true, true); + switchPlayer(type, true); + } + + /** + * 为即将开始的一次播放切到指定内核(通常来自历史记录里记住的选择)。 + * 与 switchPlayer 不同:这里不保留旧 spec 的进度、也不重新起播旧地址, + * 因为调用方紧接着就会 start/parse 新地址;只换引擎并记下本次会话内核。 + */ + public void preparePlayer(int type) { + int next = resolveAvailablePlayer(PlayerSetting.sanitizePlayer(type)); + PlayerSetting.putActivePlayer(next); + if (engine == null || player == null || next == playerType) return; + int decode = engine.getDecode(); + resetPlayerFallback(); + manualPlayerSwitchPending = false; + beginPlaybackTrace("prepare-player"); + prepareSeq++; + resetLutRuntimeState("prepare_player", true); + stopNativeAudioSession(); + stopParse(); + engine.release(); + playerType = next; + spec = null; + clearPendingSwitchRestore(); + if (SpiderDebug.isEnabled()) SpiderDebug.log("player", "prepare player type=%d decode=%d", next, decode); + engine = buildEngine(playerType, sanitizeDecode(decode)); + player = engine.getPlayer(); + callback.onPlayerRebuild(player, false); } public void switchPlayer(int type, PlaySpec freshSpec, long position, float speed, boolean repeat) { @@ -1918,7 +1973,7 @@ public void resetTrack(int type) { stopNativeAudioSession(); engine.release(); playerType = type; - PlayerSetting.putPlayer(type); + PlayerSetting.putActivePlayer(type); spec = freshSpec; bindPlaybackTrace(); playWhenReady = wasPlayWhenReady; @@ -1946,7 +2001,7 @@ public void resetTrack(int type) { stopParse(); engine.release(); playerType = type; - PlayerSetting.putPlayer(type); + PlayerSetting.putActivePlayer(type); engine = buildEngine(playerType, decode); player = engine.getPlayer(); playWhenReady = wasPlayWhenReady; @@ -1971,11 +2026,7 @@ public void resetTrack(int type) { } } - private void switchPlayer(int type, boolean persist) { - switchPlayer(type, persist, false); - } - - private void switchPlayer(int type, boolean persist, boolean manual) { + private void switchPlayer(int type, boolean manual) { if (engine == null || player == null) return; type = PlayerSetting.sanitizePlayer(type); type = manual ? resolveManualPlayer(type) : resolveAvailablePlayer(type); @@ -1984,32 +2035,35 @@ public void resetTrack(int type) { manualPlayerSwitchPending = manual; if (manual) beginIjkRuntimeManualOverride(); beginPlaybackTrace("switch-player"); - switchEngine(type, persist, true, true); + switchEngine(type, true, true, true); } - private void switchEngine(int type, boolean persist, boolean preserveState, boolean notifyPrepare) { + /** + * chosen 区分「用户为本次播放选定的内核」与「当前实际在跑的引擎」: + * 手动切换要更新会话内核(供取播放地址、写历史使用), + * 而播放失败后的自动回退只换引擎,不能改写用户的选择。 + */ + private void switchEngine(int type, boolean chosen, boolean preserveState, boolean notifyPrepare) { int decode = engine.getDecode(); - switchEngine(type, persist, preserveState, notifyPrepare, decode); + switchEngine(type, chosen, preserveState, notifyPrepare, decode); } - private void switchEngine(int type, boolean persist, boolean preserveState, boolean notifyPrepare, int decode) { + private void switchEngine(int type, boolean chosen, boolean preserveState, boolean notifyPrepare, int decode) { long position = preserveState ? getPosition() : 0; float speed = preserveState ? getSpeed() : 1f; boolean repeat = preserveState && isRepeatOne(); boolean wasPlayWhenReady = preserveState && player != null ? player.getPlayWhenReady() : playWhenReady; - switchEngine(type, persist, notifyPrepare, decode, position, speed, repeat, wasPlayWhenReady); + switchEngine(type, chosen, notifyPrepare, decode, position, speed, repeat, wasPlayWhenReady); } - private void switchEngine(int type, boolean persist, boolean notifyPrepare, int decode, long position, float speed, boolean repeat, boolean wasPlayWhenReady) { + private void switchEngine(int type, boolean chosen, boolean notifyPrepare, int decode, long position, float speed, boolean repeat, boolean wasPlayWhenReady) { prepareSeq++; resetLutRuntimeState("switch_player", true); stopNativeAudioSession(); engine.release(); playerType = type; - if (persist) { - PlayerSetting.putPlayer(type); - } - if (SpiderDebug.isEnabled()) SpiderDebug.log("player", "switch player type=%d persist=%s position=%d spec=%s", type, persist, position, debugSpec()); + if (chosen) PlayerSetting.putActivePlayer(type); + if (SpiderDebug.isEnabled()) SpiderDebug.log("player", "switch player type=%d chosen=%s position=%d spec=%s", type, chosen, position, debugSpec()); engine = buildEngine(playerType, sanitizeDecode(decode)); player = engine.getPlayer(); callback.onPlayerRebuild(player, false); @@ -3635,7 +3689,7 @@ public void resetTrack(int type) { || !playbackAutoSession.active() || playerType != PlayerSetting.IJK || !PlaybackPerformanceSetting.isAuto(PlayerSetting.IJK) - || PlayerSetting.getPlayer() != PlayerSetting.IJK) return; + || PlayerSetting.getActivePlayer() != PlayerSetting.IJK) return; long now = Math.max(0, nowElapsedMs); IjkRuntimeProfileController.Facts facts = currentIjkRuntimeFacts(now); IjkRuntimeProfileController.RuntimeSample sample = @@ -3655,7 +3709,7 @@ public void resetTrack(int type) { private IjkRuntimeProfileController.Facts currentIjkRuntimeFacts( long nowElapsedMs) { - boolean automatic = PlayerSetting.getPlayer() == PlayerSetting.IJK + boolean automatic = PlayerSetting.getActivePlayer() == PlayerSetting.IJK && PlaybackPerformanceSetting.isAuto(PlayerSetting.IJK) && !ijkRuntimeManualOverride; return IjkRuntimeProfileController.Facts.fromContext( @@ -4030,7 +4084,7 @@ public void resetTrack(int type) { ijkRuntimeManualOverride = false; pendingIjkRuntimeFallbackReparse = false; if (!ijkRuntimeTemporaryFallback) return; - if (PlayerSetting.getPlayer() != PlayerSetting.IJK + if (PlayerSetting.getActivePlayer() != PlayerSetting.IJK || !PlaybackPerformanceSetting.isAuto(PlayerSetting.IJK)) { ijkRuntimeTemporaryFallback = false; return; @@ -5216,8 +5270,12 @@ public void resetTrack(int type) { } if (!isMpv() || spec == null || TextUtils.isEmpty(spec.getUrl()) || !(engine instanceof MpvPlayerEngine mpv)) return; resetMpvOutputEvaluationState(); + mpvAutoVulkanPinnedForItem = false; + mpvAutoVulkanDisabledForItem = false; mpv.setSurfaceDirectOverride(null); mpv.clearHwdecOverride(); + mpv.setVulkanRenderOverride(null); + mpv.resetDv7HandlingForNewItem(); rebuildAndRestartMpv(null, "performance-settings-changed"); } @@ -5285,8 +5343,13 @@ public void resetTrack(int type) { mpvExplicitSubtitlePreference = hasRequestedSubtitle(Track.find(getKey())); if (!(engine instanceof MpvPlayerEngine mpv)) return; boolean hwdecOverrideCleared = mpv.clearHwdecOverride(); + boolean dv7HandlingChanged = mpv.resetDv7HandlingForNewItem(); + boolean clearAutoVulkanRenderer = mpvAutoVulkanPinnedForItem; + mpvAutoVulkanPinnedForItem = false; + mpvAutoVulkanDisabledForItem = false; + mpv.setVulkanRenderOverride(null); boolean automaticOutput = MpvPerformanceSetting.getOutputMode() == MpvPerformanceSetting.OUTPUT_AUTO; - if (shouldKeepVideoShutterClosed()) callback.onPlayerOutputPending(); + if (automaticOutput) callback.onPlayerOutputPending(); mpv.setSurfaceDirectOverride(null); boolean autoDirectEligible = MpvAutoOutputPolicy.canStartSurfaceDirect( engine.isHard(), @@ -5309,8 +5372,10 @@ public void resetTrack(int type) { if (SpiderDebug.isEnabled()) SpiderDebug.log("mpv-output", "preserve direct output for new item reason=auto-sticky"); return; } - if (mpv.isSurfaceDirect() == shouldStartDirect && !hwdecOverrideCleared) return; - if (SpiderDebug.isEnabled()) SpiderDebug.log("mpv-output", "prepare new item rebuild currentDirect=%s desiredDirect=%s mode=%s hwdecOverrideCleared=%s", mpv.isSurfaceDirect(), shouldStartDirect, MpvPerformanceSetting.getOutputModeText(), hwdecOverrideCleared); + if (mpv.isSurfaceDirect() == shouldStartDirect + && !hwdecOverrideCleared + && !clearAutoVulkanRenderer && !dv7HandlingChanged) return; + if (SpiderDebug.isEnabled()) SpiderDebug.log("mpv-output", "prepare new item rebuild currentDirect=%s desiredDirect=%s mode=%s hwdecOverrideCleared=%s clearAutoVulkan=%s dv7HandlingChanged=%s", mpv.isSurfaceDirect(), shouldStartDirect, MpvPerformanceSetting.getOutputModeText(), hwdecOverrideCleared, clearAutoVulkanRenderer, dv7HandlingChanged); mpv.setSurfaceDirectOverride(shouldStartDirect); rebuildPlayer(); } @@ -5318,15 +5383,19 @@ public void resetTrack(int type) { private void resetMpvOutputRuntime() { resetMpvOutputEvaluationState(); mpvAutoGpuPinnedForSession = false; + mpvAutoVulkanPinnedForItem = false; + mpvAutoVulkanDisabledForItem = false; lastMpvFrameTimingLogMs = 0; if (engine instanceof MpvPlayerEngine mpv) { mpv.setSurfaceDirectOverride(null); mpv.clearHwdecOverride(); + mpv.setVulkanRenderOverride(null); } } private void resetMpvOutputEvaluationState() { mpvAutoOutputEvaluated = false; + mpvAutoOutputFrameReady = false; mpvAutoOutputEvaluationScheduled = false; mpvAutoOutputProbeGaveUp = false; mpvAutoOutputProbeAttempts = 0; @@ -5370,7 +5439,8 @@ public void resetTrack(int type) { } private boolean evaluateMpvAutoOutput() { - if (!isMpv() || mpvAutoOutputEvaluated || engine == null) return true; + if (!isMpv() || mpvAutoOutputEvaluated + || !(engine instanceof MpvPlayerEngine mpv)) return true; if (mpvHlsManagedReload) return false; Tracks tracks = engine.getCurrentTracks(); boolean tracksReady = tracks != null && !tracks.isEmpty(); @@ -5382,7 +5452,7 @@ public void resetTrack(int type) { if (!dolbyVision && (format == null || !tracks.containsType(C.TRACK_TYPE_VIDEO))) { return false; } - VideoSize probedSize = engine instanceof MpvPlayerEngine mpv ? mpv.getVideoSizeSnapshot() : VideoSize.UNKNOWN; + VideoSize probedSize = mpv.getVideoSizeSnapshot(); int width = format != null && format.width > 0 ? format.width : probedSize.width > 0 ? probedSize.width : getVideoWidth(); int height = format != null && format.height > 0 ? format.height : probedSize.height > 0 ? probedSize.height : getVideoHeight(); if (width <= 0 || height <= 0) return false; @@ -5391,22 +5461,49 @@ public void resetTrack(int type) { boolean subtitleActive = externalSubtitleActive || mpvExplicitSubtitlePreference; boolean lutOrFilterActive = videoEffectsActive || videoEffectsDirty || lutAllowed && LutSetting.isEnabled() || MpvPerformanceSetting.isInterpolation(); boolean customGpuProcessing = MpvConfigStore.hasGpuVideoProcessing(); - boolean forceNativeDv7 = isDv7NativeAttemptRequested(); boolean dv7Hdr10FallbackEnabled = dolbyVision && videoDetails.dolbyVisionProfile() == 7 - && PlaybackPerformanceSetting.isDv7Hdr10FallbackEnabled(); + && mpv.isDv7Hdr10Active(); MpvAutoOutputPolicy.DolbyVisionSupport dolbyVisionSupport = dolbyVision ? CodecCapabilityInspector.dolbyVisionSupport( App.get(), videoDetails, format, width, height) : MpvAutoOutputPolicy.DolbyVisionSupport.UNKNOWN; - MpvAutoOutputPolicy.Decision decision = forceNativeDv7 - ? new MpvAutoOutputPolicy.Decision(true, - "dv7-native-attempt") - : MpvAutoOutputPolicy.evaluate(width, height, engine.isHard(), + MpvAutoOutputPolicy.DolbyVisionSupport profile81Support = + dolbyVision && videoDetails.dolbyVisionProfile() == 7 + && PlaybackPerformanceSetting.getMpvDv7HandlingMode() + == PlaybackPerformanceSetting.DV7_HANDLING_P81 + ? CodecCapabilityInspector.dolbyVisionProfileSupport( + App.get(), 8, videoDetails.dolbyVisionLevel(), + videoDetails.sourceCodecs(), format, width, height) + : MpvAutoOutputPolicy.DolbyVisionSupport.UNKNOWN; + boolean dv7HandlingChanged = dolbyVision + && videoDetails.dolbyVisionProfile() == 7 + && mpv.updateDv7Handling(dolbyVisionSupport, profile81Support); + dv7Hdr10FallbackEnabled = dolbyVision + && videoDetails.dolbyVisionProfile() == 7 + && mpv.isDv7Hdr10Active(); + MpvAutoOutputPolicy.Decision decision = MpvAutoOutputPolicy.evaluate( + width, height, engine.isHard(), Util.isLeanback(), lutOrFilterActive, customGpuProcessing, dolbyVisionSupport, dolbyVision ? videoDetails.dolbyVisionProfile() : C.INDEX_UNSET, dv7Hdr10FallbackEnabled); + int dolbyVisionProfile = dolbyVision + ? videoDetails.dolbyVisionProfile() : C.INDEX_UNSET; + boolean currentlyVulkan = mpv.isVulkanRenderer(); + MpvAutoRenderPolicy.Decision renderDecision = MpvAutoRenderPolicy.evaluate( + PlaybackPerformanceSetting.isAuto( + PlayerSetting.MPV, PlaybackPerformanceCatalog.MPV_RENDER), + engine.isHard(), dolbyVisionProfile, dolbyVisionSupport, + MPVLib.isBundledVulkanEnabled(App.get()), + MPVLib.isDeviceVulkan13Capable(App.get()), + currentlyVulkan, mpvAutoVulkanDisabledForItem); + boolean enableAutoVulkan = renderDecision.action() + == MpvAutoRenderPolicy.Action.ENABLE_VULKAN; + if (enableAutoVulkan) { + mpvAutoVulkanPinnedForItem = true; + mpv.setVulkanRenderOverride(true); + } if (dolbyVision && decision.reason().startsWith("dolby-vision-hw-")) { mpvAutoGpuPinnedForSession = true; } @@ -5415,16 +5512,30 @@ public void resetTrack(int type) { boolean effectiveEligible = MpvPerformanceSetting.isAutoSurfaceDirectEnabled() && decision.eligible(); MpvAutoOutputPolicy.Transition transition = MpvAutoOutputPolicy.transition(effectiveEligible, currentlyDirect); if (SpiderDebug.isEnabled()) SpiderDebug.log("mpv-output", "auto decision eligible=%s effectiveEligible=%s transition=%s reason=%s size=%dx%d tracksReady=%s early=%s subtitle=%s lutOrFilter=%s customGpu=%s dvProfile=%d dvSupport=%s direct=%s gpuPinned=%s attempts=%d", decision.eligible(), effectiveEligible, transition, decision.reason(), width, height, tracksReady, earlyEvaluation, subtitleActive, lutOrFilterActive, customGpuProcessing, dolbyVision ? videoDetails.dolbyVisionProfile() : C.INDEX_UNSET, dolbyVisionSupport, currentlyDirect, mpvAutoGpuPinnedForSession, mpvAutoOutputProbeAttempts); - boolean transitionRequested = transition == MpvAutoOutputPolicy.Transition.ENTER_SURFACE_DIRECT + boolean transitionRequested = dv7HandlingChanged || enableAutoVulkan + || transition == MpvAutoOutputPolicy.Transition.ENTER_SURFACE_DIRECT || transition == MpvAutoOutputPolicy.Transition.LEAVE_SURFACE_DIRECT; boolean requestAccepted = true; - if (transition == MpvAutoOutputPolicy.Transition.ENTER_SURFACE_DIRECT) { + if (dv7HandlingChanged) { + Boolean outputOverride = enableAutoVulkan + || transition == MpvAutoOutputPolicy.Transition.LEAVE_SURFACE_DIRECT + ? false + : transition == MpvAutoOutputPolicy.Transition.ENTER_SURFACE_DIRECT + ? true : null; + requestAccepted = rebuildAndRestartMpv(outputOverride, + "auto-dv7-" + mpv.getDv7HandlingOption()); + } else if (enableAutoVulkan) { + requestAccepted = rebuildAndRestartMpv(false, + "auto-" + renderDecision.reason()); + } else if (transition == MpvAutoOutputPolicy.Transition.ENTER_SURFACE_DIRECT) { requestAccepted = rebuildAndRestartMpv(true, "auto-" + decision.reason()); } else if (transition == MpvAutoOutputPolicy.Transition.LEAVE_SURFACE_DIRECT) { requestAccepted = rebuildAndRestartMpv(false, "auto-" + decision.reason()); } - String oldOutput = currentlyDirect ? "surface-direct" : "gpu"; - String targetOutput = effectiveEligible ? "surface-direct" : "gpu"; + String oldOutput = currentlyDirect ? "surface-direct" + : currentlyVulkan ? "gpu-vulkan" : "gpu-opengl"; + String targetOutput = enableAutoVulkan ? "gpu-vulkan" + : effectiveEligible ? "surface-direct" : "gpu"; PlaybackTelemetry.DecisionOutcome telemetryOutcome = transitionRequested ? requestAccepted ? PlaybackTelemetry.DecisionOutcome.REQUESTED : PlaybackTelemetry.DecisionOutcome.FAILED : PlaybackTelemetry.DecisionOutcome.HELD; @@ -5435,7 +5546,7 @@ public void resetTrack(int type) { oldOutput, targetOutput, transitionRequested && requestAccepted ? targetOutput : oldOutput, - decision.reason(), + enableAutoVulkan ? renderDecision.reason() : decision.reason(), transitionRequested ? requestAccepted ? "none" : "rebuild-rejected" : "no-transition", List.of( PlaybackTelemetry.DecisionInput.number("width", width, PlaybackAutoContext.ValueSource.PLAYER_CALLBACK, PlaybackAutoContext.Confidence.HIGH), @@ -5482,6 +5593,38 @@ public void resetTrack(int type) { if (!evaluateMpvAutoOutput()) scheduleMpvAutoOutputEvaluation(); } + private boolean retryMpvDv7P81Failure(PlaybackException error) { + if (error == null || !(engine instanceof MpvPlayerEngine mpv) + || !mpv.isDv7P81Active()) return false; + String message = error.getMessage(); + boolean conversionOrDecodeFailure = error.errorCode + == PlaybackException.ERROR_CODE_DECODER_INIT_FAILED + || error.errorCode == PlaybackException.ERROR_CODE_DECODER_QUERY_FAILED + || error.errorCode == PlaybackException.ERROR_CODE_DECODING_FAILED + || error.errorCode == PlaybackException.ERROR_CODE_DECODING_FORMAT_UNSUPPORTED + || message != null && (message.startsWith(MpvPlayer.ERROR_DECODE_FAILED) + || message.startsWith(MpvPlayer.ERROR_INVALID_MEDIA_DATA)); + if (!conversionOrDecodeFailure || !mpv.prepareDv7P81Hdr10Fallback()) { + return false; + } + return rebuildAndRestartMpv(null, "dv7-p81-hdr10-fallback"); + } + + private boolean retryMpvDv7P81FirstFrameTimeout() { + if (!(engine instanceof MpvPlayerEngine mpv) + || player == null + || !mpv.isDv7P81Active() + || playbackTrace.hasStage(PlaybackTrace.Stage.FIRST_FRAME) + || !mpv.prepareDv7P81Hdr10Fallback()) { + return false; + } + long position = Math.max(0, player.getCurrentPosition()); + PlaybackTrace.log("mpv-dv", playbackTrace.current(), + "P8.1 produced no first frame before startup timeout; retry HDR10 position=%d", + position); + return rebuildAndRestartMpv(null, "dv7-p81-first-frame-timeout"); + } + private boolean retryMpvSurfaceDirectFailure(PlaybackException error) { if (!isMpvSurfaceDirect() || mpvSurfaceFallbackTried || error == null) return false; if (isDv7NativeAttemptRequested()) return false; @@ -5583,10 +5726,36 @@ public void resetTrack(int type) { return rebuildAndRestartMpv(false, reason); } + private boolean retryMpvAutoVulkanFailure(PlaybackException error) { + if (error == null || !mpvAutoVulkanPinnedForItem + || !(engine instanceof MpvPlayerEngine mpv) + || !mpv.isVulkanRenderer()) return false; + String message = error.getMessage(); + boolean outputFailure = error.errorCode + == PlaybackException.ERROR_CODE_VIDEO_FRAME_PROCESSING_FAILED + || message != null + && message.startsWith(MpvPlayer.ERROR_VIDEO_OUTPUT_FAILED); + return outputFailure + && retryMpvAutoVulkanToOpenGl("auto-vulkan-output-failure"); + } + + private boolean retryMpvAutoVulkanToOpenGl(String reason) { + if (!mpvAutoVulkanPinnedForItem + || !(engine instanceof MpvPlayerEngine mpv) + || !mpv.isVulkanRenderer()) return false; + mpvAutoVulkanPinnedForItem = false; + mpvAutoVulkanDisabledForItem = true; + mpv.setVulkanRenderOverride(false); + mpv.setVulkanBackendOverride(null); + PlaybackTrace.log("mpv-vulkan", playbackTrace.current(), + "automatic DV5 Vulkan failed; fallback OpenGL once reason=%s", + reason); + return rebuildAndRestartMpv(false, reason); + } + private boolean isDv7NativeAttemptRequested() { - if (!isMpv() || engine == null || !engine.isHard() - || PlaybackPerformanceSetting - .isDv7Hdr10FallbackEnabled()) return false; + if (!isMpv() || !(engine instanceof MpvPlayerEngine mpv) + || !engine.isHard() || !mpv.isDv7NativeActive()) return false; PlayerEngine.VideoPlaybackDetails details = engine.getVideoPlaybackDetails(); return details != null && details.dolbyVisionProfile() == 7; @@ -6581,7 +6750,7 @@ public void resetTrack(int type) { if (spec != null && spec.getDrm() != null) return false; if (PlayerSetting.isTunnel()) return false; if (engine.getDecode() == PlayerEngine.SOFT) return false; - if (PlayerSetting.isVideoPrefer()) return false; + if (PlayerSetting.isVideoPrefer(playerType)) return false; return true; } @@ -7922,6 +8091,7 @@ public void resetTrack(int type) { boolean hasAudio = tracks.containsType(C.TRACK_TYPE_AUDIO); PlaybackStartupPolicy.Completion completion = PlaybackStartupPolicy.resolve(ready, playerType == PlayerSetting.MPV, hasVideo, hasAudio); if (completion == PlaybackStartupPolicy.Completion.FIRST_FRAME) { + if (playbackTrace.hasStage(PlaybackTrace.Stage.FIRST_FRAME)) return; playbackTrace.mark(PlaybackTrace.Stage.FIRST_FRAME, "source=mpv-playback-restart player=" + playerType); onIjkRuntimeFirstFrame(SystemClock.elapsedRealtime()); } else if (completion == PlaybackStartupPolicy.Completion.AUDIO_PLAYABLE) { @@ -7929,6 +8099,26 @@ public void resetTrack(int type) { } } + private void completeMpvDirectFirstFrame(int state) { + if (!MpvAutoOutputPolicy.canRevealDirectFrame( + MpvPerformanceSetting.getOutputMode() == MpvPerformanceSetting.OUTPUT_AUTO, + mpvAutoOutputEvaluated, + state == Player.STATE_READY, + isMpvSurfaceDirect(), + getVideoWidth(), + getVideoHeight())) return; + mpvAutoOutputFrameReady = true; + callback.onPlayerOutputReady(); + if (!playbackTrace.hasStage(PlaybackTrace.Stage.FIRST_FRAME)) { + playbackTrace.mark(PlaybackTrace.Stage.FIRST_FRAME, + "source=mpv-playback-restart-direct player=" + playerType); + onIjkRuntimeFirstFrame(SystemClock.elapsedRealtime()); + } + PlaybackTrace.log("mpv-output", playbackTrace.current(), + "auto shutter release reason=direct-playback-restart size=%dx%d evaluated=%s", + getVideoWidth(), getVideoHeight(), mpvAutoOutputEvaluated); + } + private void recordBufferingState(int state) { if (player == null) return; if (state == Player.STATE_BUFFERING @@ -7942,6 +8132,14 @@ public void resetTrack(int type) { "action=seek-buffering result=excluded-from-rebuffer"); return; } + if (isExo() + && state == Player.STATE_BUFFERING + && !playbackBufferingTracker.isBuffering() + && PlaybackAnalyticsListener.isSeekRecoveryActive()) { + PlaybackTrace.log("playback-buffer", playbackTrace.current(), + "event=excluded phase=seek outcome=user-action"); + return; + } if ((mpvHlsManagedReload || ijkBufferManagedReload) && state == Player.STATE_BUFFERING && !playbackBufferingTracker.isBuffering()) { @@ -8197,6 +8395,7 @@ public void resetTrack(int type) { if (SpiderDebug.isEnabled()) SpiderDebug.log("player", "state=%s spec=%s", stateName(state), debugSpec()); publishPlaybackAutoContext(state != Player.STATE_IDLE); if (state == Player.STATE_READY) { + completeMpvDirectFirstFrame(state); manualPlayerSwitchPending = false; App.post(PlayerManager.this::refreshAdAudioRuntime); ijkRuntimeProfileController.onPrepared( @@ -8304,7 +8503,7 @@ public void resetTrack(int type) { List savedTracks = Track.find(getKey()); setTrack(savedTracks); if (RealtimeSubtitleController.get().isEnabled()) disableSubtitleTrackForRealtime(); - if (PlayerSetting.isPreferAAC() && !TrackUtil.hasTrack(player, savedTracks, C.TRACK_TYPE_AUDIO)) TrackUtil.preferAAC(player); + if (PlayerSetting.isPreferAAC(playerType) && !TrackUtil.hasTrack(player, savedTracks, C.TRACK_TYPE_AUDIO)) TrackUtil.preferAAC(player); callback.onTracksChanged(); initTrack = true; } @@ -8360,8 +8559,10 @@ public void resetTrack(int type) { publishPlaybackTelemetry( PlaybackAutoContext.PlaybackPhase.ERROR, false); if (recoverMpvHlsVariantError()) return; + if (retryMpvDv7P81Failure(e)) return; if (retryMpvSurfaceDirectFailure(e)) return; if (retryMpvVulkanBackendFailure(e)) return; + if (retryMpvAutoVulkanFailure(e)) return; PlaybackErrorClassifier.Failure failure = PlaybackErrorClassifier.classify(e, getEffectivePlaybackRoute()); PlayerEngine.ErrorAction action = engine.handleError(e); int statusCode = httpStatus(e); @@ -8513,7 +8714,9 @@ public void resetTrack(int type) { false, "timeout", SystemClock.elapsedRealtime(), true); PlaybackException e = new PlaybackException(ResUtil.getString(R.string.error_play_timeout), null, PlaybackException.ERROR_CODE_TIMEOUT); if (retryLutWarmupByRefresh("timeout")) return; + if (retryMpvDv7P81FirstFrameTimeout()) return; if (retryMpvVulkanBackendTimeout()) return; + if (retryMpvAutoVulkanToOpenGl("auto-vulkan-first-frame-timeout")) return; if (retryExoDv7FirstFrameTimeout()) return; if (manualPlayerSwitchPending) { finishPlaybackProfileAbSession( @@ -8560,12 +8763,34 @@ public void resetTrack(int type) { : ResUtil.getString(R.string.error_play_stage_network); case MEDIA_PARSING -> ResUtil.getString(R.string.error_play_stage_media); case DECODER -> ResUtil.getString(R.string.error_play_stage_decoder); - case OUTPUT -> ResUtil.getString(R.string.error_play_stage_output); + case OUTPUT -> isAudioOutputFailure(failure) + ? ResUtil.getString(R.string.error_play_stage_audio_output) + : isVideoOutputFailure(failure) + ? ResUtil.getString(R.string.error_play_stage_video_output) + : ResUtil.getString(R.string.error_play_stage_output); case DRM -> ResUtil.getString(R.string.error_play_stage_drm); case UNKNOWN -> ResUtil.getString(R.string.error_play_stage_unknown); }; } + private boolean isAudioOutputFailure(PlaybackErrorClassifier.Failure failure) { + return hasErrorCode(failure, PlaybackException.ERROR_CODE_AUDIO_TRACK_INIT_FAILED) + || hasErrorCode(failure, PlaybackException.ERROR_CODE_AUDIO_TRACK_WRITE_FAILED) + || hasErrorCode(failure, PlaybackException.ERROR_CODE_AUDIO_TRACK_OFFLOAD_INIT_FAILED) + || hasErrorCode(failure, PlaybackException.ERROR_CODE_AUDIO_TRACK_OFFLOAD_WRITE_FAILED); + } + + private boolean isVideoOutputFailure(PlaybackErrorClassifier.Failure failure) { + return hasErrorCode(failure, PlaybackException.ERROR_CODE_VIDEO_FRAME_PROCESSOR_INIT_FAILED) + || hasErrorCode(failure, PlaybackException.ERROR_CODE_VIDEO_FRAME_PROCESSING_FAILED) + || "mpv-video-output-marker".equals(failure.evidence()); + } + + private boolean hasErrorCode( + PlaybackErrorClassifier.Failure failure, int errorCode) { + return PlaybackException.getErrorCodeName(errorCode).equals(failure.errorCode()); + } + private boolean handleExoDecoderResourcesReclaimed( PlaybackException error) { if (error.errorCode diff --git a/app/src/main/java/com/fongmi/android/tv/player/Source.java b/app/src/main/java/com/fongmi/android/tv/player/Source.java index d7e8ee6d44..fcfbd5bd5e 100644 --- a/app/src/main/java/com/fongmi/android/tv/player/Source.java +++ b/app/src/main/java/com/fongmi/android/tv/player/Source.java @@ -85,7 +85,7 @@ public class Source { } public String fetch(Result result) throws Exception { - return fetch(result, PlayerSetting.getPlayer()); + return fetch(result, PlayerSetting.getActivePlayer()); } public String fetch(Result result, int playerType) throws Exception { diff --git a/app/src/main/java/com/fongmi/android/tv/player/codec/CodecCapabilityInspector.java b/app/src/main/java/com/fongmi/android/tv/player/codec/CodecCapabilityInspector.java index 18e3c19e95..d8a7f55bdb 100644 --- a/app/src/main/java/com/fongmi/android/tv/player/codec/CodecCapabilityInspector.java +++ b/app/src/main/java/com/fongmi/android/tv/player/codec/CodecCapabilityInspector.java @@ -118,12 +118,27 @@ public final class CodecCapabilityInspector { if (context == null || details == null || details.dolbyVisionProfile() <= 0) { return MpvAutoOutputPolicy.DolbyVisionSupport.UNKNOWN; } - String codecs = details.sourceCodecs(); - if (TextUtils.isEmpty(codecs)) { - codecs = details.dolbyVisionLevel() > 0 - ? String.format(Locale.US, "dvhe.%02d.%02d", - details.dolbyVisionProfile(), details.dolbyVisionLevel()) - : String.format(Locale.US, "dvhe.%02d", details.dolbyVisionProfile()); + return dolbyVisionProfileSupport(context, details.dolbyVisionProfile(), + details.dolbyVisionLevel(), details.sourceCodecs(), current, + width, height); + } + + public static MpvAutoOutputPolicy.DolbyVisionSupport dolbyVisionProfileSupport( + Context context, + int profile, + int level, + String sourceCodecs, + Format current, + int width, + int height) { + if (context == null || profile <= 0) { + return MpvAutoOutputPolicy.DolbyVisionSupport.UNKNOWN; + } + String codecs = sourceCodecs; + if (TextUtils.isEmpty(codecs) || !codecMatchesProfile(codecs, profile)) { + codecs = level > 0 + ? String.format(Locale.US, "dvhe.%02d.%02d", profile, level) + : String.format(Locale.US, "dvhe.%02d", profile); } Format.Builder builder = new Format.Builder() .setSampleMimeType(MimeTypes.VIDEO_DOLBY_VISION) @@ -151,6 +166,14 @@ public final class CodecCapabilityInspector { } } + private static boolean codecMatchesProfile(String codecs, int profile) { + if (TextUtils.isEmpty(codecs)) return false; + String expected = String.format(Locale.US, ".%02d.", profile); + String first = codecs.split(",", 2)[0].trim().toLowerCase(Locale.US); + return (first.startsWith("dvhe.") || first.startsWith("dvh1.")) + && first.contains(expected); + } + public static List getHardwareDecoders() { List value = cache; if (value != null) return value; diff --git a/app/src/main/java/com/fongmi/android/tv/player/engine/MpvAudioCapabilities.java b/app/src/main/java/com/fongmi/android/tv/player/engine/MpvAudioCapabilities.java index fc86eea5bb..56dc37ac68 100644 --- a/app/src/main/java/com/fongmi/android/tv/player/engine/MpvAudioCapabilities.java +++ b/app/src/main/java/com/fongmi/android/tv/player/engine/MpvAudioCapabilities.java @@ -92,24 +92,36 @@ final class MpvAudioCapabilities { private static boolean supportsMpvCarrier(String codec) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return true; - int sampleRate = "ac3".equals(codec) || "dts".equals(codec) ? 48000 : 192000; - int channelMask = "truehd".equals(codec) - ? AudioFormat.CHANNEL_OUT_7POINT1_SURROUND - : AudioFormat.CHANNEL_OUT_STEREO; - try { - AudioFormat format = new AudioFormat.Builder() - .setEncoding(AudioFormat.ENCODING_IEC61937) - .setSampleRate(sampleRate) - .setChannelMask(channelMask) - .build(); - AudioAttributes attributes = new AudioAttributes.Builder() - .setUsage(AudioAttributes.USAGE_MEDIA) - .setContentType(AudioAttributes.CONTENT_TYPE_MOVIE) - .build(); - return AudioTrack.isDirectPlaybackSupported(format, attributes); - } catch (Throwable ignored) { - return false; + for (CarrierFormat carrier : getCarrierFormats(codec, Build.VERSION.SDK_INT)) { + try { + AudioFormat format = new AudioFormat.Builder() + .setEncoding(AudioFormat.ENCODING_IEC61937) + .setSampleRate(carrier.sampleRate()) + .setChannelMask(carrier.channelMask()) + .build(); + AudioAttributes attributes = new AudioAttributes.Builder() + .setUsage(AudioAttributes.USAGE_MEDIA) + .setContentType(AudioAttributes.CONTENT_TYPE_MOVIE) + .build(); + if (!AudioTrack.isDirectPlaybackSupported(format, attributes)) return false; + } catch (Throwable ignored) { + return false; + } } + return true; + } + + static List getCarrierFormats(String codec, int sdkInt) { + int sampleRate = "ac3".equals(codec) || "dts".equals(codec) ? 48000 : 192000; + if ("truehd".equals(codec)) { + return List.of(new CarrierFormat(sampleRate, AudioFormat.CHANNEL_OUT_7POINT1_SURROUND)); + } + if ("dts-hd".equals(codec) && sdkInt >= Build.VERSION_CODES.S) { + return List.of( + new CarrierFormat(sampleRate, AudioFormat.CHANNEL_OUT_STEREO), + new CarrierFormat(sampleRate, AudioFormat.CHANNEL_OUT_7POINT1_SURROUND)); + } + return List.of(new CarrierFormat(sampleRate, AudioFormat.CHANNEL_OUT_STEREO)); } private static boolean hasPassthroughOutputDevice(AudioManager manager) { @@ -180,4 +192,7 @@ final class MpvAudioCapabilities { default -> "type_" + type; }; } + + record CarrierFormat(int sampleRate, int channelMask) { + } } diff --git a/app/src/main/java/com/fongmi/android/tv/player/engine/MpvPlayerEngine.java b/app/src/main/java/com/fongmi/android/tv/player/engine/MpvPlayerEngine.java index 61d063db5c..a9f2892f2d 100644 --- a/app/src/main/java/com/fongmi/android/tv/player/engine/MpvPlayerEngine.java +++ b/app/src/main/java/com/fongmi/android/tv/player/engine/MpvPlayerEngine.java @@ -22,6 +22,7 @@ import com.fongmi.android.tv.player.PlayerHelper; import com.fongmi.android.tv.player.PlaybackRoute; import com.fongmi.android.tv.player.PlaybackResourceClassifier; import com.fongmi.android.tv.player.PlaybackTrace; +import com.fongmi.android.tv.player.codec.CodecCapabilityInspector; import com.fongmi.android.tv.player.exo.ExoUtil; import com.fongmi.android.tv.player.exo.TrackUtil; import com.fongmi.android.tv.player.lut.MpvLutShader; @@ -48,6 +49,10 @@ import is.xyz.mpv.MPVLib; @UnstableApi public class MpvPlayerEngine implements PlayerEngine { + static final String DV7_PRESERVE = "preserve"; + static final String DV7_P81 = "p81"; + static final String DV7_HDR10 = "hdr10"; + private MpvPlayer player; private PlaySpec spec; private boolean playWhenReady; @@ -55,11 +60,14 @@ public class MpvPlayerEngine implements PlayerEngine { private boolean surfaceDirect; private Boolean surfaceDirectOverride; private boolean lutAllowed = true; + private Boolean vulkanRenderOverride; private String vulkanBackendOverride; private String vulkanBackend = MpvVulkanBackendPolicy.AUTO; private boolean vulkanRenderer; private String hwdecOverride; private String configuredHwdec = "no"; + private String dv7HandlingOption; + private boolean dv7P81FallbackTried; private final BiConsumer videoSizeProbeListener; private int decode; @@ -67,6 +75,7 @@ public class MpvPlayerEngine implements PlayerEngine { this.decode = decode; this.lutAllowed = lutAllowed; this.videoSizeProbeListener = videoSizeProbeListener; + resetDv7HandlingForNewItem(); this.player = buildPlayer(listener); } @@ -80,6 +89,10 @@ public class MpvPlayerEngine implements PlayerEngine { player.release(); } + public void prepareTerminalRelease() { + player.prepareTerminalRelease(); + } + @Override public Player rebuild(Player.Listener listener) { player.release(); @@ -289,6 +302,14 @@ public class MpvPlayerEngine implements PlayerEngine { vulkanBackendOverride = value; } + public void setVulkanRenderOverride(@Nullable Boolean value) { + vulkanRenderOverride = value; + } + + public boolean isVulkanRenderer() { + return vulkanRenderer; + } + public boolean shouldFallbackVulkanToStable() { return vulkanRenderer && MpvVulkanBackendPolicy.isAutomaticConfig() && !MpvVulkanBackendPolicy.STABLE.equals(vulkanBackend); @@ -413,8 +434,7 @@ public class MpvPlayerEngine implements PlayerEngine { } String currentVo = player.getObservedCurrentVideoOutput(); boolean fallbackConfigured = isConfiguredDv7Hdr10Fallback( - details, isHard(), - PlaybackPerformanceSetting.isDv7Hdr10FallbackEnabled()); + details, isHard(), isDv7Hdr10Active()); return new VideoPlaybackDetails( details.sourceCodecs(), details.dolbyVisionProfile(), @@ -424,7 +444,8 @@ public class MpvPlayerEngine implements PlayerEngine { player.getObservedHwdecCurrent(), details.outputColorInfo(), isDolbyVisionHdr10Fallback(details, currentVo) - || fallbackConfigured); + || fallbackConfigured, + details.sourceDolbyVisionProfile() == 7 && isDv7P81Active()); } static boolean isConfiguredDv7Hdr10Fallback( @@ -443,6 +464,73 @@ public class MpvPlayerEngine implements PlayerEngine { return output.equals("gpu") || output.startsWith("gpu-next"); } + public boolean resetDv7HandlingForNewItem() { + String previous = dv7HandlingOption; + MpvAutoOutputPolicy.DolbyVisionSupport nativeDv7 = + CodecCapabilityInspector.dolbyVisionProfileSupport( + App.get(), 7, 6, null, null, 0, 0); + MpvAutoOutputPolicy.DolbyVisionSupport profile81 = + PlaybackPerformanceSetting.getMpvDv7HandlingMode() + == PlaybackPerformanceSetting.DV7_HANDLING_P81 + ? CodecCapabilityInspector.dolbyVisionProfileSupport( + App.get(), 8, 6, null, null, 0, 0) + : MpvAutoOutputPolicy.DolbyVisionSupport.UNKNOWN; + dv7HandlingOption = selectDv7Handling(nativeDv7, profile81, + PlaybackPerformanceSetting.getMpvDv7HandlingMode()); + dv7P81FallbackTried = false; + return !dv7HandlingOption.equals(previous); + } + + public boolean updateDv7Handling( + MpvAutoOutputPolicy.DolbyVisionSupport nativeDv7, + MpvAutoOutputPolicy.DolbyVisionSupport profile81) { + String selected = selectDv7Handling(nativeDv7, profile81, + PlaybackPerformanceSetting.getMpvDv7HandlingMode()); + if (selected.equals(dv7HandlingOption)) return false; + dv7HandlingOption = selected; + dv7P81FallbackTried = false; + return true; + } + + static String selectDv7Handling( + MpvAutoOutputPolicy.DolbyVisionSupport nativeDv7, + MpvAutoOutputPolicy.DolbyVisionSupport profile81, + int preferredMode) { + if (nativeDv7 == MpvAutoOutputPolicy.DolbyVisionSupport.SUPPORTED) { + return DV7_PRESERVE; + } + if (preferredMode == PlaybackPerformanceSetting.DV7_HANDLING_P81 + && profile81 == MpvAutoOutputPolicy.DolbyVisionSupport.SUPPORTED) { + return DV7_P81; + } + return DV7_HDR10; + } + + public boolean prepareDv7P81Hdr10Fallback() { + if (!isDv7P81Active() || dv7P81FallbackTried) return false; + dv7P81FallbackTried = true; + dv7HandlingOption = DV7_HDR10; + PlaybackTrace.log("mpv-dv", getPlaybackTraceId(), + "P8.1 failed; prepare one-shot HDR10 fallback"); + return true; + } + + public boolean isDv7NativeActive() { + return DV7_PRESERVE.equals(dv7HandlingOption); + } + + public boolean isDv7P81Active() { + return DV7_P81.equals(dv7HandlingOption); + } + + public boolean isDv7Hdr10Active() { + return DV7_HDR10.equals(dv7HandlingOption); + } + + public String getDv7HandlingOption() { + return dv7HandlingOption; + } + @Override public long getDroppedFrames() { return player.getDroppedFrames(); @@ -739,7 +827,9 @@ public class MpvPlayerEngine implements PlayerEngine { surfaceDirect = surfaceDirectOverride == null ? MpvPerformanceSetting.shouldUseSurfaceDirect(autoDirectEligible, Util.isLeanback(), decode == HARD) : surfaceDirectOverride && decode == HARD && !zeroCopyBlocked; - boolean requestVulkan = PlayerSetting.getMpvRender() == PlayerSetting.MPV_RENDER_VULKAN; + boolean requestVulkan = vulkanRenderOverride != null + ? vulkanRenderOverride + : PlayerSetting.getMpvRender() == PlayerSetting.MPV_RENDER_VULKAN; boolean nativeVulkan = MPVLib.isBundledVulkanEnabled(App.get()); boolean deviceVulkan = MPVLib.isDeviceVulkan13Capable(App.get()); boolean useVulkan = !surfaceDirect && requestVulkan && nativeVulkan && deviceVulkan; @@ -776,13 +866,13 @@ public class MpvPlayerEngine implements PlayerEngine { .automaticHlsVariant(PlaybackPerformanceSetting.isAuto( PlayerSetting.MPV, PlaybackPerformanceCatalog.MPV_HLS_BITRATE)) + .deferStartupTrackRefresh(DV7_P81.equals(getDv7HandlingOption())) .option("framedrop", MpvPerformanceSetting.getFrameDropOption()) .option("video-sync", MpvPerformanceSetting.getSyncOption()) .option("interpolation", MpvPerformanceSetting.isInterpolation() ? "yes" : "no") .option("hls-bitrate", MpvPerformanceSetting.getHlsBitrateOption()) .option("demuxer-dovi-profile7", - PlaybackPerformanceSetting.isDv7Hdr10FallbackEnabled() - ? "hdr10" : "preserve"); + getDv7HandlingOption()); if (useVulkan && !appBackendOverride.isEmpty()) { builder.option(MpvVulkanBackendPolicy.OPTION, appBackendOverride); } else if (useVulkan && automaticBackend && !automaticOverride.isEmpty()) { diff --git a/app/src/main/java/com/fongmi/android/tv/player/exo/AutoLoadControl.java b/app/src/main/java/com/fongmi/android/tv/player/exo/AutoLoadControl.java index a29afd49a6..e4ae964606 100644 --- a/app/src/main/java/com/fongmi/android/tv/player/exo/AutoLoadControl.java +++ b/app/src/main/java/com/fongmi/android/tv/player/exo/AutoLoadControl.java @@ -131,9 +131,9 @@ final class AutoLoadControl implements LoadControl { mediaDurationMs(parameters.targetLiveOffsetUs), parameters.rebuffering, now); - ExoPlaybackThresholdCoordinator.Episode episode = parameters.rebuffering - ? ExoPlaybackThresholdCoordinator.Episode.REBUFFER - : ExoPlaybackThresholdCoordinator.Episode.STARTUP; + ExoPlaybackThresholdCoordinator.Episode episode = playbackEpisode( + parameters.rebuffering, + thresholdCoordinator.isSeekPending(inputs.session(), now)); ExoPlaybackThresholdCoordinator.Selection selection = thresholdCoordinator.lockEpisode(episode, inputs); if (!selection.session().active()) { @@ -197,6 +197,14 @@ final class AutoLoadControl implements LoadControl { return playoutBufferedUs >= requiredUs; } + static ExoPlaybackThresholdCoordinator.Episode playbackEpisode( + boolean rebuffering, + boolean seekPending) { + if (rebuffering) return ExoPlaybackThresholdCoordinator.Episode.REBUFFER; + if (seekPending) return ExoPlaybackThresholdCoordinator.Episode.SEEK; + return ExoPlaybackThresholdCoordinator.Episode.STARTUP; + } + static int controlledTimeThresholdMs(int configuredThresholdMs) { return Math.min( Math.max(0, configuredThresholdMs), @@ -310,6 +318,8 @@ final class AutoLoadControl implements LoadControl { PlaybackTelemetry.DecisionOutcome.APPLIED, selection.episode() == ExoPlaybackThresholdCoordinator.Episode.REBUFFER ? Integer.toString(inputs.configuredRebufferMs()) + : selection.episode() == ExoPlaybackThresholdCoordinator.Episode.SEEK + ? Integer.toString(ExoPlaybackThresholdCoordinator.SEEK_START_BUFFER_MS) : Integer.toString(inputs.configuredStartBufferMs()), Integer.toString(selection.thresholdMs()), Integer.toString(selection.thresholdMs()), diff --git a/app/src/main/java/com/fongmi/android/tv/player/exo/ErrorMsgProvider.java b/app/src/main/java/com/fongmi/android/tv/player/exo/ErrorMsgProvider.java index 80bdc80204..06482620ac 100644 --- a/app/src/main/java/com/fongmi/android/tv/player/exo/ErrorMsgProvider.java +++ b/app/src/main/java/com/fongmi/android/tv/player/exo/ErrorMsgProvider.java @@ -29,6 +29,8 @@ public class ErrorMsgProvider { case PlaybackException.ERROR_CODE_DECODING_FORMAT_EXCEEDS_CAPABILITIES -> "Decoding Format Exceeds Capabilities"; case PlaybackException.ERROR_CODE_AUDIO_TRACK_INIT_FAILED -> "Audio Track Init Failed"; case PlaybackException.ERROR_CODE_AUDIO_TRACK_WRITE_FAILED -> "Audio Track Write Failed"; + case PlaybackException.ERROR_CODE_VIDEO_FRAME_PROCESSOR_INIT_FAILED -> "Video Output Init Failed"; + case PlaybackException.ERROR_CODE_VIDEO_FRAME_PROCESSING_FAILED -> "Video Output Failed"; case PlaybackException.ERROR_CODE_DRM_UNSPECIFIED -> "DRM Unspecified"; case PlaybackException.ERROR_CODE_DRM_SYSTEM_ERROR -> "DRM System Error"; case PlaybackException.ERROR_CODE_DRM_CONTENT_ERROR -> "DRM Content Error"; diff --git a/app/src/main/java/com/fongmi/android/tv/player/exo/ExoDv5GpuMappingPolicy.java b/app/src/main/java/com/fongmi/android/tv/player/exo/ExoDv5GpuMappingPolicy.java new file mode 100644 index 0000000000..4ef48fbf27 --- /dev/null +++ b/app/src/main/java/com/fongmi/android/tv/player/exo/ExoDv5GpuMappingPolicy.java @@ -0,0 +1,137 @@ +package com.fongmi.android.tv.player.exo; + +import java.util.Locale; + +/** Pure route selection policy for Dolby Vision Profile 5 playback. */ +final class ExoDv5GpuMappingPolicy { + + static final int MIN_GPU_MAPPING_API = 26; + static final int MIN_CODEC_TONE_MAP_API = 31; + + private ExoDv5GpuMappingPolicy() { + } + + static Decision decide(Input input) { + Input safe = input == null ? Input.unsupported() : input; + if (!safe.profile5()) { + return unsupported(Reason.NOT_PROFILE_5); + } + if (safe.nativeDolbyVisionDisplayAvailable() + && safe.nativeDolbyVisionDecoderAvailable()) { + return selected( + Route.NATIVE_DOLBY_VISION, + Reason.NATIVE_DOLBY_VISION_AVAILABLE); + } + if (safe.apiLevel() >= MIN_CODEC_TONE_MAP_API + && safe.codecToneMapRequestAccepted()) { + return selected(Route.CODEC_TONE_MAP, Reason.CODEC_TONE_MAP_ACCEPTED); + } + + Reason gpuBlockReason = gpuBlockReason(safe); + if (gpuBlockReason == Reason.NONE) { + return selected(Route.GPU_MAPPING, Reason.GPU_MAPPING_ELIGIBLE); + } + if (!safe.drmProtected() && safe.legacyHdr10FallbackAllowed()) { + return new Decision( + Route.LEGACY_HDR10_FALLBACK, + Reason.LEGACY_HDR10_FALLBACK_ALLOWED, + gpuBlockReason); + } + return new Decision(Route.UNSUPPORTED, gpuBlockReason, gpuBlockReason); + } + + static boolean isProfile5(String sampleMimeType, String codecs) { + if (!"video/dolby-vision".equals(sampleMimeType) + || codecs == null + || codecs.isBlank()) { + return false; + } + int comma = codecs.indexOf(','); + String firstCodec = (comma < 0 ? codecs : codecs.substring(0, comma)) + .trim() + .toLowerCase(Locale.US); + return firstCodec.startsWith("dvhe.05.") + || firstCodec.startsWith("dvh1.05."); + } + + private static Reason gpuBlockReason(Input input) { + if (input.drmProtected()) return Reason.DRM_REQUIRES_SECURE_OUTPUT; + if (input.apiLevel() < MIN_GPU_MAPPING_API) return Reason.API_BELOW_26; + if (!input.experimentalGpuMappingEnabled()) return Reason.EXPERIMENT_DISABLED; + if (input.tunnelingRequested()) return Reason.TUNNELING_UNSUPPORTED; + if (!input.hardwareHevcDecoderAvailable()) return Reason.HEVC_DECODER_UNAVAILABLE; + if (!input.independentRendererAvailable()) return Reason.RENDERER_UNAVAILABLE; + if (!input.vulkanAhbProbePassed()) return Reason.VULKAN_AHB_PROBE_FAILED; + return Reason.NONE; + } + + private static Decision selected(Route route, Reason reason) { + return new Decision(route, reason, Reason.NONE); + } + + private static Decision unsupported(Reason reason) { + return new Decision(Route.UNSUPPORTED, reason, reason); + } + + enum Route { + NATIVE_DOLBY_VISION, + CODEC_TONE_MAP, + GPU_MAPPING, + LEGACY_HDR10_FALLBACK, + UNSUPPORTED + } + + enum Reason { + NONE, + NOT_PROFILE_5, + NATIVE_DOLBY_VISION_AVAILABLE, + CODEC_TONE_MAP_ACCEPTED, + GPU_MAPPING_ELIGIBLE, + DRM_REQUIRES_SECURE_OUTPUT, + API_BELOW_26, + EXPERIMENT_DISABLED, + TUNNELING_UNSUPPORTED, + HEVC_DECODER_UNAVAILABLE, + RENDERER_UNAVAILABLE, + VULKAN_AHB_PROBE_FAILED, + LEGACY_HDR10_FALLBACK_ALLOWED + } + + record Input( + boolean profile5, + boolean drmProtected, + boolean nativeDolbyVisionDisplayAvailable, + boolean nativeDolbyVisionDecoderAvailable, + int apiLevel, + boolean codecToneMapRequestAccepted, + boolean hardwareHevcDecoderAvailable, + boolean independentRendererAvailable, + boolean vulkanAhbProbePassed, + boolean experimentalGpuMappingEnabled, + boolean tunnelingRequested, + boolean legacyHdr10FallbackAllowed) { + + static Input unsupported() { + return new Input( + false, + false, + false, + false, + 0, + false, + false, + false, + false, + false, + false, + false); + } + } + + record Decision(Route route, Reason reason, Reason gpuBlockReason) { + + boolean usesGpuMapping() { + return route == Route.GPU_MAPPING; + } + } +} diff --git a/app/src/main/java/com/fongmi/android/tv/player/exo/ExoDv5GpuRenderer.java b/app/src/main/java/com/fongmi/android/tv/player/exo/ExoDv5GpuRenderer.java new file mode 100644 index 0000000000..91d4d31dc9 --- /dev/null +++ b/app/src/main/java/com/fongmi/android/tv/player/exo/ExoDv5GpuRenderer.java @@ -0,0 +1,293 @@ +package com.fongmi.android.tv.player.exo; + +import android.content.Context; +import android.media.MediaCrypto; +import android.os.Handler; + +import androidx.annotation.Nullable; +import androidx.media3.common.C; +import androidx.media3.common.Format; +import androidx.media3.common.MimeTypes; +import androidx.media3.exoplayer.mediacodec.MediaCodecAdapter; +import androidx.media3.exoplayer.mediacodec.MediaCodecInfo; +import androidx.media3.exoplayer.mediacodec.MediaCodecSelector; +import androidx.media3.decoder.DecoderInputBuffer; +import androidx.media3.exoplayer.ExoPlaybackException; +import androidx.media3.exoplayer.RendererCapabilities; +import androidx.media3.exoplayer.source.MediaSource; +import androidx.media3.exoplayer.video.MediaCodecVideoRenderer; +import androidx.media3.exoplayer.video.VideoRendererEventListener; + +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; + +/** Experimental MediaCodec renderer targeting {@link ExoDv5VideoSink}. */ +final class ExoDv5GpuRenderer extends MediaCodecVideoRenderer { + + private final Context context; + private final ExoDv5VideoSink sink; + + ExoDv5GpuRenderer( + Context context, + MediaCodecAdapter.Factory codecAdapterFactory, + MediaCodecSelector mediaCodecSelector, + long allowedJoiningTimeMs, + boolean enableDecoderFallback, + @Nullable Handler eventHandler, + @Nullable VideoRendererEventListener eventListener, + ExoFrameSchedulingExperimentPolicy.Decision frameSchedulingDecision, + ExoDv5VideoSink sink) { + super(ExoFrameSchedulingRendererSettings.from(frameSchedulingDecision) + .apply(new Builder(context) + .setCodecAdapterFactory(codecAdapterFactory) + .setMediaCodecSelector(mediaCodecSelector) + .setAllowedJoiningTimeMs(allowedJoiningTimeMs) + .setEnableDecoderFallback(enableDecoderFallback) + .setEventHandler(eventHandler) + .setEventListener(eventListener) + .setVideoSink(sink))); + this.context = context; + this.sink = sink; + sink.setDiagnosticContext(context); + } + + @Override + public String getName() { + return "MediaCodecVideoRenderer-DV5-Vulkan"; + } + + @Override + protected int supportsFormat(MediaCodecSelector selector, Format format) + throws androidx.media3.exoplayer.mediacodec.MediaCodecUtil.DecoderQueryException { + if (!ExoDv5GpuMappingPolicy.isProfile5( + format.sampleMimeType, format.codecs) + || format.cryptoType != C.CRYPTO_TYPE_NONE) { + return C.FORMAT_UNSUPPORTED_TYPE; + } + if (supportsNativeDolbyVision(selector, format)) { + return C.FORMAT_UNSUPPORTED_TYPE; + } + if (getDecoderInfos(selector, format, false).isEmpty()) { + return C.FORMAT_UNSUPPORTED_TYPE; + } + return super.supportsFormat(selector, asHevc(format)) + & ~RendererCapabilities.TUNNELING_SUPPORT_MASK; + } + + @Override + protected List getDecoderInfos( + MediaCodecSelector selector, Format format, boolean secure) + throws androidx.media3.exoplayer.mediacodec.MediaCodecUtil.DecoderQueryException { + if (secure || !ExoDv5GpuMappingPolicy.isProfile5( + format.sampleMimeType, format.codecs)) { + return List.of(); + } + if (supportsNativeDolbyVision(selector, format)) return List.of(); + List infos = super.getDecoderInfos( + selector, asHevc(format), false); + List hardwareInfos = new ArrayList<>(infos.size()); + for (MediaCodecInfo info : infos) { + if (info != null && info.hardwareAccelerated) hardwareInfos.add(info); + } + return hardwareInfos; + } + + @Override + protected MediaCodecAdapter.Configuration getMediaCodecConfiguration( + MediaCodecInfo info, Format format, MediaCrypto crypto, float rate) { + return super.getMediaCodecConfiguration(info, asHevc(format), crypto, rate); + } + + @Override + public void render(long positionUs, long elapsedRealtimeUs) + throws ExoPlaybackException { + try { + super.render(positionUs, elapsedRealtimeUs); + } catch (ExoPlaybackException error) { + sink.diagnosticLog("renderer render failed code=" + error.errorCode + + " message=" + error.getMessage() + + " cause=" + error.getCause()); + throw error; + } catch (RuntimeException error) { + sink.diagnosticLog("renderer render runtime failure=" + error); + throw error; + } + } + + @Override + protected void onCodecInitialized( + String name, + MediaCodecAdapter.Configuration configuration, + long initializedTimestampMs, + long initializationDurationMs) { + sink.diagnosticLog("renderer codec initialized name=" + name + + " durationMs=" + initializationDurationMs); + super.onCodecInitialized( + name, configuration, initializedTimestampMs, initializationDurationMs); + } + + @Override + protected void onCodecReleased(String name) { + sink.diagnosticLog("renderer codec released name=" + name); + super.onCodecReleased(name); + } + + @Override + protected void onCodecError(Exception codecError) { + sink.diagnosticLog("renderer codec error=" + codecError); + super.onCodecError(codecError); + } + + @Override + protected void onStreamChanged( + Format[] formats, + long startPositionUs, + long offsetUs, + MediaSource.MediaPeriodId mediaPeriodId) throws ExoPlaybackException { + super.onStreamChanged(formats, startPositionUs, offsetUs, mediaPeriodId); + Format format = formats == null || formats.length == 0 ? null : formats[0]; + sink.diagnosticLog("renderer stream startUs=" + startPositionUs + + " offsetUs=" + offsetUs + + " mime=" + (format == null ? null : format.sampleMimeType) + + " codecs=" + (format == null ? null : format.codecs)); + } + + @Override + protected void onDisabled() { + sink.diagnosticLog("renderer disabled stats=" + sink.stats()); + try { + super.onDisabled(); + } finally { + // Release the codec input Surface before disconnecting the output swapchain. + sink.disable(); + } + } + + @Override + protected void onStopped() { + sink.diagnosticLog("renderer stopped stats=" + sink.stats()); + super.onStopped(); + } + + @Override + protected void onQueueInputBuffer(DecoderInputBuffer buffer) + throws ExoPlaybackException { + ByteBuffer data = buffer.data; + if (data == null || buffer.isEncrypted()) return; + for (byte[] rpu : findRpuNalus(data)) { + sink.queueRpu(buffer.timeUs, rpu); + } + } + + ExoDv5Native.Stats diagnosticStats() { + return sink.stats(); + } + + static Format asHevc(Format format) { + return format.buildUpon() + .setSampleMimeType(MimeTypes.VIDEO_H265) + .setCodecs(null) + .setInitializationData( + DolbyVisionP81ExtractorsFactory.removeDolbyVisionCsd( + format.initializationData)) + .build(); + } + + private boolean supportsNativeDolbyVision( + MediaCodecSelector selector, Format format) + throws androidx.media3.exoplayer.mediacodec.MediaCodecUtil.DecoderQueryException { + if (android.os.Build.VERSION.SDK_INT < 26) return false; + android.hardware.display.DisplayManager displayManager = + (android.hardware.display.DisplayManager) context.getSystemService( + Context.DISPLAY_SERVICE); + android.view.Display display = displayManager == null + ? null : displayManager.getDisplay(android.view.Display.DEFAULT_DISPLAY); + if (display == null || !display.isHdr() + || display.getHdrCapabilities() == null) return false; + boolean dolbyDisplay = false; + for (int hdrType : display.getHdrCapabilities().getSupportedHdrTypes()) { + if (hdrType == android.view.Display.HdrCapabilities.HDR_TYPE_DOLBY_VISION) { + dolbyDisplay = true; + break; + } + } + if (!dolbyDisplay) return false; + for (MediaCodecInfo info : selector.getDecoderInfos( + format.sampleMimeType, false, false)) { + if (info != null && info.hardwareAccelerated + && info.isFormatSupported(context, format)) return true; + } + return false; + } + + static List findRpuNalus(ByteBuffer source) { + ByteBuffer data = source.duplicate(); + int start = data.position(); + int limit = data.limit(); + List result = new ArrayList<>(); + if (findStartCode(data, start, limit) >= 0) { + int cursor = start; + while (true) { + int prefix = findStartCode(data, cursor, limit); + if (prefix < 0) break; + int prefixSize = data.get(prefix + 2) == 1 ? 3 : 4; + int nalStart = prefix + prefixSize; + int next = findStartCode(data, nalStart, limit); + int nalEnd = next < 0 ? limit : next; + addRpu(data, nalStart, nalEnd, result); + if (next < 0) break; + cursor = next; + } + return result; + } + for (int lengthSize : new int[] {4, 2, 1}) { + List candidate = parseLengthPrefixed( + data, start, limit, lengthSize); + if (candidate != null) return candidate; + } + return result; + } + + private static List parseLengthPrefixed( + ByteBuffer data, int start, int limit, int lengthSize) { + List result = new ArrayList<>(); + int cursor = start; + boolean sawNal = false; + while (cursor < limit) { + if (limit - cursor < lengthSize) return null; + long length = 0; + for (int i = 0; i < lengthSize; i++) { + length = (length << 8) | (data.get(cursor + i) & 0xffL); + } + cursor += lengthSize; + if (length < 2 || length > limit - cursor) return null; + int nalEnd = cursor + (int) length; + addRpu(data, cursor, nalEnd, result); + sawNal = true; + cursor = nalEnd; + } + return sawNal ? result : null; + } + + private static void addRpu( + ByteBuffer data, int start, int end, List output) { + if (end - start < 2 || ((data.get(start) & 0x7e) >> 1) != 62) return; + byte[] nal = new byte[end - start]; + ByteBuffer copy = data.duplicate(); + copy.position(start); + copy.limit(end); + copy.get(nal); + output.add(nal); + } + + private static int findStartCode(ByteBuffer data, int start, int limit) { + for (int i = start; i + 3 <= limit; i++) { + if (data.get(i) != 0 || data.get(i + 1) != 0) continue; + if (data.get(i + 2) == 1) return i; + if (i + 4 <= limit && data.get(i + 2) == 0 + && data.get(i + 3) == 1) return i; + } + return -1; + } +} diff --git a/app/src/main/java/com/fongmi/android/tv/player/exo/ExoDv5GpuRendererFactory.java b/app/src/main/java/com/fongmi/android/tv/player/exo/ExoDv5GpuRendererFactory.java new file mode 100644 index 0000000000..75828b3964 --- /dev/null +++ b/app/src/main/java/com/fongmi/android/tv/player/exo/ExoDv5GpuRendererFactory.java @@ -0,0 +1,46 @@ +package com.fongmi.android.tv.player.exo; + +import android.content.Context; +import android.os.Handler; + +import androidx.annotation.Nullable; +import androidx.media3.exoplayer.mediacodec.MediaCodecAdapter; +import androidx.media3.exoplayer.mediacodec.MediaCodecSelector; +import androidx.media3.exoplayer.video.VideoRendererEventListener; + +/** Creates the E9-3 experimental renderer only after an explicit opt-in. */ +final class ExoDv5GpuRendererFactory { + + private ExoDv5GpuRendererFactory() { + } + + static boolean shouldCreate( + boolean experimentEnabled, ExoDv5Native.Probe probe) { + return experimentEnabled && probe != null && probe.available(); + } + + @Nullable + static ExoDv5GpuRenderer create( + boolean experimentEnabled, + Context context, + MediaCodecAdapter.Factory codecAdapterFactory, + MediaCodecSelector mediaCodecSelector, + long allowedJoiningTimeMs, + boolean enableDecoderFallback, + @Nullable Handler eventHandler, + @Nullable VideoRendererEventListener eventListener, + ExoFrameSchedulingExperimentPolicy.Decision frameSchedulingDecision) { + ExoDv5Native.Probe probe = ExoDv5Native.probe(); + if (!shouldCreate(experimentEnabled, probe)) return null; + return new ExoDv5GpuRenderer( + context, + codecAdapterFactory, + mediaCodecSelector, + allowedJoiningTimeMs, + enableDecoderFallback, + eventHandler, + eventListener, + frameSchedulingDecision, + new ExoDv5VideoSink()); + } +} diff --git a/app/src/main/java/com/fongmi/android/tv/player/exo/ExoDv5Native.java b/app/src/main/java/com/fongmi/android/tv/player/exo/ExoDv5Native.java new file mode 100644 index 0000000000..f7905e50bf --- /dev/null +++ b/app/src/main/java/com/fongmi/android/tv/player/exo/ExoDv5Native.java @@ -0,0 +1,190 @@ +package com.fongmi.android.tv.player.exo; + +import android.os.Build; +import android.view.Surface; + +import androidx.annotation.Nullable; + +/** JNI boundary for the independent Exo DV5 renderer. */ +final class ExoDv5Native { + + static final int CAPABILITY_IMAGE_READER = 1 << 0; + static final int CAPABILITY_VULKAN_12 = 1 << 1; + static final int CAPABILITY_AHB_IMPORT = 1 << 2; + static final int CAPABILITY_YCBCR_CONVERSION = 1 << 3; + static final int CAPABILITY_FOREIGN_QUEUE = 1 << 4; + static final int CAPABILITY_LIBPLACEBO_375 = 1 << 5; + static final int CAPABILITY_LIBDOVI = 1 << 6; + static final int REQUIRED_CAPABILITIES = CAPABILITY_IMAGE_READER + | CAPABILITY_VULKAN_12 + | CAPABILITY_AHB_IMPORT + | CAPABILITY_YCBCR_CONVERSION + | CAPABILITY_FOREIGN_QUEUE + | CAPABILITY_LIBPLACEBO_375 + | CAPABILITY_LIBDOVI; + + private static final LoadResult LOAD_RESULT = loadLibrary(); + + private ExoDv5Native() { + } + + static Probe probe() { + if (Build.VERSION.SDK_INT < ExoDv5GpuMappingPolicy.MIN_GPU_MAPPING_API) { + return new Probe(false, 0, "api-below-26"); + } + if (!LOAD_RESULT.loaded()) { + return new Probe(false, 0, LOAD_RESULT.reason()); + } + try { + int capabilities = nativeProbeCapabilities(); + boolean available = (capabilities & REQUIRED_CAPABILITIES) + == REQUIRED_CAPABILITIES; + return new Probe( + available, + capabilities, + available ? "available" : "missing-capability"); + } catch (Throwable error) { + return new Probe(false, 0, + "probe-" + error.getClass().getSimpleName()); + } + } + + static NativeRenderer create(int width, int height) { + if (!LOAD_RESULT.loaded() || width <= 0 || height <= 0) { + throw new IllegalStateException("DV5 native renderer unavailable"); + } + long handle = nativeCreate(width, height); + if (handle == 0) throw new IllegalStateException("AImageReader creation failed"); + Surface surface = nativeGetInputSurface(handle); + if (surface == null) { + nativeRelease(handle); + throw new IllegalStateException("AImageReader Surface creation failed"); + } + return new NativeRenderer(handle, surface); + } + + private static LoadResult loadLibrary() { + if (Build.VERSION.SDK_INT < ExoDv5GpuMappingPolicy.MIN_GPU_MAPPING_API) { + return new LoadResult(false, "api-below-26"); + } + try { + System.loadLibrary("exo_dovi_renderer"); + return new LoadResult(true, "loaded"); + } catch (Throwable error) { + return new LoadResult(false, + "load-" + error.getClass().getSimpleName()); + } + } + + record Probe(boolean available, int capabilities, String reason) { + + boolean has(int capability) { + return (capabilities & capability) == capability; + } + } + + record Stats( + long acquiredFrames, + long ahbFrames, + long sampledUsageFrames, + long highDepthFrames, + long matchedFrames, + long unmatchedFrames, + long expectedQueueDrops, + long lastImageTimestampNs, + long lastPresentationTimeUs, + long lastAhbFormat, + long pendingFrames, + long parsedRpus, + long malformedRpus, + long rpuQueueDrops, + long pendingRpus, + long renderedFrames, + long renderFailures) { + + static Stats empty() { + return new Stats(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0); + } + } + + static final class NativeRenderer implements AutoCloseable { + + private long handle; + @Nullable private Surface inputSurface; + + NativeRenderer(long handle, Surface inputSurface) { + this.handle = handle; + this.inputSurface = inputSurface; + } + + synchronized Surface inputSurface() { + if (inputSurface == null) throw new IllegalStateException("renderer released"); + return inputSurface; + } + + synchronized boolean queueFrame( + long imageTimestampNs, long presentationTimeUs) { + return handle != 0 && nativeQueueFrame( + handle, imageTimestampNs, presentationTimeUs); + } + + synchronized void clearFrames() { + if (handle != 0) nativeClearFrames(handle); + } + + synchronized boolean queueRpu(long presentationTimeUs, byte[] rpu) { + return handle != 0 && rpu != null && rpu.length >= 2 + && nativeQueueRpu(handle, presentationTimeUs, rpu); + } + + synchronized void setOutputSurface(@Nullable Surface surface) { + if (handle != 0) nativeSetOutputSurface(handle, surface); + } + + synchronized Stats stats() { + if (handle == 0) return Stats.empty(); + long[] values = nativeGetStats(handle); + if (values == null || values.length < 17) return Stats.empty(); + return new Stats( + values[0], values[1], values[2], values[3], values[4], + values[5], values[6], values[7], values[8], values[9], + values[10], values[11], values[12], values[13], + values[14], values[15], values[16]); + } + + @Override + public synchronized void close() { + if (handle == 0) return; + Surface surface = inputSurface; + inputSurface = null; + nativeRelease(handle); + handle = 0; + if (surface != null) surface.release(); + } + } + + private record LoadResult(boolean loaded, String reason) { + } + + private static native int nativeProbeCapabilities(); + + private static native long nativeCreate(int width, int height); + + @Nullable private static native Surface nativeGetInputSurface(long handle); + + private static native boolean nativeQueueFrame( + long handle, long imageTimestampNs, long presentationTimeUs); + + private static native void nativeClearFrames(long handle); + + private static native boolean nativeQueueRpu( + long handle, long presentationTimeUs, byte[] rpu); + + private static native void nativeSetOutputSurface( + long handle, @Nullable Surface surface); + + @Nullable private static native long[] nativeGetStats(long handle); + + private static native void nativeRelease(long handle); +} diff --git a/app/src/main/java/com/fongmi/android/tv/player/exo/ExoDv5VideoSink.java b/app/src/main/java/com/fongmi/android/tv/player/exo/ExoDv5VideoSink.java new file mode 100644 index 0000000000..53737651d5 --- /dev/null +++ b/app/src/main/java/com/fongmi/android/tv/player/exo/ExoDv5VideoSink.java @@ -0,0 +1,458 @@ +package com.fongmi.android.tv.player.exo; + +import android.content.Context; +import android.graphics.Bitmap; +import android.media.MediaFormat; +import android.os.SystemClock; +import android.view.Surface; + +import androidx.annotation.Nullable; +import androidx.media3.common.C; +import androidx.media3.common.Effect; +import androidx.media3.common.Format; +import androidx.media3.common.MimeTypes; +import androidx.media3.common.VideoSize; +import androidx.media3.common.util.Size; +import androidx.media3.common.util.TimestampIterator; +import androidx.media3.exoplayer.video.VideoFrameMetadataListener; +import androidx.media3.exoplayer.video.VideoSink; + +import java.io.FileOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayDeque; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.Executor; + +/** + * Experimental Media3 sink for MediaCodec -> AImageReader -> Vulkan/libplacebo output. + */ +final class ExoDv5VideoSink implements VideoSink { + + private static final String DIAGNOSTIC_FILE = "exo-dv5-debug.log"; + static final int MAX_PENDING_FRAMES = 8; + static final long EARLY_RELEASE_THRESHOLD_US = 50_000L; + static final long DROP_THRESHOLD_US = -30_000L; + static final int MAX_CONSECUTIVE_RENDER_FAILURES = 3; + + private final Queue pendingFrames; + private Listener listener; + private Executor listenerExecutor; + private VideoFrameMetadataListener metadataListener; + @Nullable private ExoDv5Native.NativeRenderer nativeRenderer; + @Nullable private Surface outputSurface; + private Format inputFormat; + private long bufferTimestampAdjustmentUs; + private boolean initialized; + private boolean started; + private boolean allowBeforeStarted; + private boolean inputEnded; + private boolean released; + private boolean firstFrameRendered; + private long observedRenderedFrames; + private long observedRenderFailures; + private int consecutiveRenderFailures; + private int timestampLogs; + private int rpuLogs; + private int queueFailureLogs; + private int renderLogs; + @Nullable private Context diagnosticContext; + + ExoDv5VideoSink() { + pendingFrames = new ArrayDeque<>(); + listener = Listener.NO_OP; + listenerExecutor = Runnable::run; + metadataListener = (presentationTimeUs, releaseTimeNs, format, mediaFormat) -> {}; + inputFormat = new Format.Builder().build(); + } + + void setDiagnosticContext(Context context) { + diagnosticContext = context.getApplicationContext(); + try (FileOutputStream output = diagnosticContext.openFileOutput( + DIAGNOSTIC_FILE, Context.MODE_PRIVATE)) { + output.write((diagnosticLine("session start")).getBytes(StandardCharsets.UTF_8)); + } catch (Throwable ignored) { + // Diagnostic logging must never affect playback. + } + } + + synchronized void diagnosticLog(String message) { + Context context = diagnosticContext; + if (context == null) return; + try (FileOutputStream output = context.openFileOutput( + DIAGNOSTIC_FILE, Context.MODE_APPEND)) { + output.write(diagnosticLine(message).getBytes(StandardCharsets.UTF_8)); + } catch (Throwable ignored) { + // Diagnostic logging must never affect playback. + } + } + + private static String diagnosticLine(String message) { + return SystemClock.elapsedRealtime() + " " + + Thread.currentThread().getName() + " " + message + "\n"; + } + + @Override + public void startRendering() { + started = true; + diagnosticLog("sink startRendering"); + } + + @Override + public void stopRendering() { + started = false; + diagnosticLog("sink stopRendering"); + } + + @Override + public void setListener(Listener listener, Executor executor) { + this.listener = listener == null ? Listener.NO_OP : listener; + this.listenerExecutor = executor == null ? Runnable::run : executor; + } + + @Override + public boolean initialize(Format sourceFormat) throws VideoSinkException { + if (initialized) return true; + diagnosticLog("sink initialize format=" + sourceFormat); + if (released || sourceFormat == null || sourceFormat.width <= 0 + || sourceFormat.height <= 0 + || !ExoDv5GpuMappingPolicy.isProfile5( + sourceFormat.sampleMimeType, sourceFormat.codecs) + || sourceFormat.cryptoType != C.CRYPTO_TYPE_NONE) { + throw new VideoSinkException( + new IllegalArgumentException("unsupported DV5 Vulkan format"), + sourceFormat == null ? inputFormat : sourceFormat); + } + try { + nativeRenderer = ExoDv5Native.create( + sourceFormat.width, sourceFormat.height); + if (outputSurface != null) { + nativeRenderer.setOutputSurface(outputSurface); + } + inputFormat = sourceFormat; + initialized = true; + inputEnded = false; + diagnosticLog("sink initialized stats=" + nativeRenderer.stats()); + return true; + } catch (Throwable error) { + diagnosticLog("sink initialize failed=" + error); + throw new VideoSinkException(error, sourceFormat); + } + } + + @Override + public boolean isInitialized() { + return initialized; + } + + @Override + public void redraw() { + // The swapchain retains the most recently presented frame. + } + + @Override + public void flush(boolean resetPosition) { + skipPendingFrames(false); + ExoDv5Native.NativeRenderer renderer = nativeRenderer; + if (renderer != null) renderer.clearFrames(); + inputEnded = false; + if (resetPosition) allowBeforeStarted = false; + if (resetPosition) resetRenderObservation(); + } + + @Override + public boolean isReady(boolean otherwiseReady) { + return initialized && otherwiseReady; + } + + @Override + public void signalEndOfCurrentInputStream() { + inputEnded = true; + } + + @Override + public void signalEndOfInput() { + inputEnded = true; + } + + @Override + public boolean isEnded() { + ExoDv5Native.NativeRenderer renderer = nativeRenderer; + return inputEnded && pendingFrames.isEmpty() + && (renderer == null || renderer.stats().pendingFrames() == 0); + } + + @Override + public Surface getInputSurface() { + ExoDv5Native.NativeRenderer renderer = nativeRenderer; + if (!initialized || renderer == null) { + throw new IllegalStateException("DV5 sink is not initialized"); + } + return renderer.inputSurface(); + } + + @Override + public void setVideoFrameMetadataListener( + VideoFrameMetadataListener videoFrameMetadataListener) { + metadataListener = videoFrameMetadataListener == null + ? (presentationTimeUs, releaseTimeNs, format, mediaFormat) -> {} + : videoFrameMetadataListener; + } + + @Override + public void setPlaybackSpeed(float speed) { + // The player position passed to render() is already speed adjusted. + } + + @Override + public void setVideoEffects(List videoEffects) { + if (videoEffects != null && !videoEffects.isEmpty()) { + throw new UnsupportedOperationException("DV5 diagnostic sink has no effects"); + } + } + + @Override + public void setBufferTimestampAdjustmentUs(long bufferTimestampAdjustmentUs) { + this.bufferTimestampAdjustmentUs = bufferTimestampAdjustmentUs; + diagnosticLog("sink timestamp adjustmentUs=" + bufferTimestampAdjustmentUs); + } + + @Override + public void setOutputSurfaceInfo(Surface outputSurface, Size outputResolution) { + this.outputSurface = outputSurface; + diagnosticLog("sink setOutputSurface valid=" + outputSurface.isValid() + + " resolution=" + outputResolution); + resetRenderObservation(); + ExoDv5Native.NativeRenderer renderer = nativeRenderer; + if (renderer != null) renderer.setOutputSurface(outputSurface); + } + + @Override + public void clearOutputSurfaceInfo() { + diagnosticLog("sink clearOutputSurface"); + outputSurface = null; + resetRenderObservation(); + ExoDv5Native.NativeRenderer renderer = nativeRenderer; + if (renderer != null) renderer.setOutputSurface(null); + } + + @Override + public void setChangeFrameRateStrategy(int changeFrameRateStrategy) { + // Surface frame-rate hints are left to the outer Media3 renderer. + } + + @Override + public void onInputStreamChanged( + int inputType, + Format format, + long startPositionUs, + int firstFrameReleaseInstruction, + List videoEffects) { + if (inputType != INPUT_TYPE_SURFACE) { + throw new IllegalArgumentException("DV5 sink requires Surface input"); + } + setVideoEffects(videoEffects); + inputFormat = format; + inputEnded = false; + listenerExecutor.execute(() -> listener.onVideoSizeChanged( + new VideoSize(format.width, format.height))); + } + + @Override + public void allowReleaseFirstFrameBeforeStarted() { + allowBeforeStarted = true; + } + + @Override + public boolean handleInputFrame( + long bufferPresentationTimeUs, VideoFrameHandler videoFrameHandler) { + if (!initialized || released || videoFrameHandler == null + || pendingFrames.size() >= MAX_PENDING_FRAMES) { + return false; + } + long framePresentationTimeUs = bufferPresentationTimeUs + + bufferTimestampAdjustmentUs; + pendingFrames.add(new PendingFrame( + bufferPresentationTimeUs, + framePresentationTimeUs, + videoFrameHandler)); + if (timestampLogs++ < 4) { + diagnosticLog("sink frame bufferPtsUs=" + bufferPresentationTimeUs + + " framePtsUs=" + framePresentationTimeUs + + " adjustmentUs=" + bufferTimestampAdjustmentUs); + } + listenerExecutor.execute(listener::onFrameAvailableForRendering); + return true; + } + + @Override + public boolean handleInputBitmap( + Bitmap inputBitmap, TimestampIterator bufferTimestampIterator) { + return false; + } + + @Override + public void render(long positionUs, long elapsedRealtimeUs) + throws VideoSinkException { + updateRenderObservation(); + PendingFrame frame = pendingFrames.peek(); + if (frame == null) return; + long framePositionUs = positionUs + bufferTimestampAdjustmentUs; + long earlyUs = frame.framePresentationTimeUs() - framePositionUs; + FrameAction action = frameAction(started, allowBeforeStarted, earlyUs); + if (renderLogs++ < 4) { + diagnosticLog("sink render positionUs=" + positionUs + + " framePositionUs=" + framePositionUs + + " bufferPtsUs=" + frame.bufferPresentationTimeUs() + + " framePtsUs=" + frame.framePresentationTimeUs() + + " earlyUs=" + earlyUs + + " action=" + action); + } + if (action == FrameAction.WAIT) return; + pendingFrames.remove(); + if (action == FrameAction.DROP) { + frame.handler().skip(); + listenerExecutor.execute(listener::onFrameDropped); + return; + } + + long releaseTimeNs = System.nanoTime() + Math.max(0, earlyUs) * 1_000L; + ExoDv5Native.NativeRenderer renderer = nativeRenderer; + long imageTimestampNs = releaseTimeNs; + if (renderer == null || !renderer.queueFrame( + imageTimestampNs, frame.bufferPresentationTimeUs())) { + if (queueFailureLogs++ < 4) { + diagnosticLog("sink queueFrame rejected imageNs=" + imageTimestampNs + + " bufferPtsUs=" + frame.bufferPresentationTimeUs() + + " framePtsUs=" + frame.framePresentationTimeUs() + + " stats=" + stats()); + } + frame.handler().skip(); + listenerExecutor.execute(listener::onFrameDropped); + return; + } + metadataListener.onVideoFrameAboutToBeRendered( + frame.framePresentationTimeUs(), + releaseTimeNs, + inputFormat.buildUpon() + .setSampleMimeType(MimeTypes.VIDEO_RAW) + .build(), + (MediaFormat) null); + frame.handler().render(releaseTimeNs); + } + + @Override + public void join(boolean renderNextFrameImmediately) { + if (renderNextFrameImmediately) allowBeforeStarted = true; + } + + @Override + public void release() { + if (released) return; + diagnosticLog("sink release stats=" + stats() + + " pendingJava=" + pendingFrames.size()); + released = true; + disable(); + outputSurface = null; + } + + void disable() { + diagnosticLog("sink disable stats=" + stats() + + " pendingJava=" + pendingFrames.size()); + skipPendingFrames(false); + ExoDv5Native.NativeRenderer renderer = nativeRenderer; + nativeRenderer = null; + if (renderer != null) renderer.close(); + initialized = false; + started = false; + allowBeforeStarted = false; + inputEnded = false; + resetRenderObservation(); + } + + ExoDv5Native.Stats stats() { + ExoDv5Native.NativeRenderer renderer = nativeRenderer; + return renderer == null ? ExoDv5Native.Stats.empty() : renderer.stats(); + } + + void queueRpu(long presentationTimeUs, byte[] rpu) { + ExoDv5Native.NativeRenderer renderer = nativeRenderer; + if (rpuLogs++ < 4) { + diagnosticLog("sink rpu ptsUs=" + presentationTimeUs + + " bytes=" + (rpu == null ? 0 : rpu.length) + + " renderer=" + (renderer != null)); + } + if (renderer != null) renderer.queueRpu(presentationTimeUs, rpu); + } + + static FrameAction frameAction( + boolean started, boolean allowBeforeStarted, long earlyUs) { + if (!started && !allowBeforeStarted) return FrameAction.WAIT; + if (earlyUs > EARLY_RELEASE_THRESHOLD_US) return FrameAction.WAIT; + if (earlyUs < DROP_THRESHOLD_US) return FrameAction.DROP; + return FrameAction.RENDER; + } + + static long imageTimestampNsFor(long presentationTimeUs) { + if (presentationTimeUs > Long.MAX_VALUE / 1_000L) return Long.MAX_VALUE; + if (presentationTimeUs < Long.MIN_VALUE / 1_000L) return Long.MIN_VALUE; + return presentationTimeUs * 1_000L; + } + + private void updateRenderObservation() throws VideoSinkException { + ExoDv5Native.NativeRenderer renderer = nativeRenderer; + if (renderer == null || outputSurface == null) return; + ExoDv5Native.Stats stats = renderer.stats(); + long renderedDelta = Math.max(0, + stats.renderedFrames() - observedRenderedFrames); + long failureDelta = Math.max(0, + stats.renderFailures() - observedRenderFailures); + observedRenderedFrames = stats.renderedFrames(); + observedRenderFailures = stats.renderFailures(); + if (renderedDelta > 0) { + consecutiveRenderFailures = 0; + if (!firstFrameRendered) { + firstFrameRendered = true; + listenerExecutor.execute(listener::onFirstFrameRendered); + } + } else if (failureDelta > 0) { + consecutiveRenderFailures = (int) Math.min( + MAX_CONSECUTIVE_RENDER_FAILURES, + consecutiveRenderFailures + failureDelta); + diagnosticLog("sink render failure delta=" + failureDelta + + " consecutive=" + consecutiveRenderFailures + + " stats=" + stats); + } + if (consecutiveRenderFailures >= MAX_CONSECUTIVE_RENDER_FAILURES) { + diagnosticLog("sink throwing render failure stats=" + stats); + throw new VideoSinkException( + new IllegalStateException("DV5 Vulkan rendering failed"), + inputFormat); + } + } + + private void resetRenderObservation() { + firstFrameRendered = false; + consecutiveRenderFailures = 0; + ExoDv5Native.NativeRenderer renderer = nativeRenderer; + ExoDv5Native.Stats stats = renderer == null + ? ExoDv5Native.Stats.empty() : renderer.stats(); + observedRenderedFrames = stats.renderedFrames(); + observedRenderFailures = stats.renderFailures(); + } + + private void skipPendingFrames(boolean notify) { + while (!pendingFrames.isEmpty()) { + pendingFrames.remove().handler().skip(); + if (notify) listenerExecutor.execute(listener::onFrameDropped); + } + } + + enum FrameAction { WAIT, RENDER, DROP } + + private record PendingFrame( + long bufferPresentationTimeUs, + long framePresentationTimeUs, + VideoFrameHandler handler) { + } +} diff --git a/app/src/main/java/com/fongmi/android/tv/player/exo/ExoPlaybackThresholdCoordinator.java b/app/src/main/java/com/fongmi/android/tv/player/exo/ExoPlaybackThresholdCoordinator.java index 8a2eaa9562..4228322b09 100644 --- a/app/src/main/java/com/fongmi/android/tv/player/exo/ExoPlaybackThresholdCoordinator.java +++ b/app/src/main/java/com/fongmi/android/tv/player/exo/ExoPlaybackThresholdCoordinator.java @@ -8,6 +8,8 @@ final class ExoPlaybackThresholdCoordinator { static final long RECOVERY_STABLE_MS = 30_000L; static final long RECOVERY_STEP_MS = 15_000L; + static final long SEEK_RECOVERY_TIMEOUT_MS = 30_000L; + static final int SEEK_START_BUFFER_MS = 1_000; private static final ExoPlaybackThresholdCoordinator PROCESS = new ExoPlaybackThresholdCoordinator(); @@ -103,6 +105,7 @@ final class ExoPlaybackThresholdCoordinator { lastRebufferAtMs, observedRebufferCount, raw.currentlyRebuffering(), + state.seekPendingAtMs(), state.lock(), policy); return new Update( @@ -178,7 +181,30 @@ final class ExoPlaybackThresholdCoordinator { synchronized void endEpisode(PlaybackAutoContext.SessionToken session) { if (session == null || !session.equals(state.session())) return; - state = state.withLock(null); + state = state.withLock(null).withSeekPendingAtMs(0); + } + + synchronized void markSeek( + PlaybackAutoContext.SessionToken session, + long nowElapsedMs) { + if (session == null || !session.active()) return; + if (!session.equals(state.session())) state = State.begin(session); + state = state.withLock(null).withSeekPendingAtMs( + Math.max(1, nowElapsedMs)); + } + + synchronized boolean isSeekPending( + PlaybackAutoContext.SessionToken session, + long nowElapsedMs) { + boolean pending = session != null + && session.active() + && session.equals(state.session()) + && state.seekPendingAtMs() > 0; + if (!pending) return false; + if (Math.max(0, nowElapsedMs) - state.seekPendingAtMs() + <= SEEK_RECOVERY_TIMEOUT_MS) return true; + state = state.withSeekPendingAtMs(0); + return false; } synchronized void disrupt(PlaybackAutoContext.SessionToken session) { @@ -337,6 +363,7 @@ final class ExoPlaybackThresholdCoordinator { } enum Episode { + SEEK("seek"), STARTUP("startup"), REBUFFER("rebuffer"); @@ -417,6 +444,9 @@ final class ExoPlaybackThresholdCoordinator { } int thresholdMs() { + if (episode == Episode.SEEK) { + return Math.min(SEEK_START_BUFFER_MS, startBufferMs); + } return episode == Episode.REBUFFER ? rebufferMs : startBufferMs; } } @@ -440,6 +470,7 @@ final class ExoPlaybackThresholdCoordinator { long lastRebufferAtMs, int maxRebufferCount, boolean currentlyRebuffering, + long seekPendingAtMs, EpisodeLock lock, ExoPlaybackThresholdPolicy.Decision policy) { @@ -458,6 +489,7 @@ final class ExoPlaybackThresholdCoordinator { -1, 0, false, + 0, null, null); } @@ -472,10 +504,26 @@ final class ExoPlaybackThresholdCoordinator { lastRebufferAtMs, maxRebufferCount, currentlyRebuffering, + seekPendingAtMs, episodeLock, policy); } + State withSeekPendingAtMs(long pendingAtMs) { + return new State( + session, + startBufferMs, + rebufferMs, + stableSinceMs, + lastLowerAtMs, + lastRebufferAtMs, + maxRebufferCount, + currentlyRebuffering, + Math.max(0, pendingAtMs), + lock, + policy); + } + State disrupt() { return new State( session, @@ -486,6 +534,7 @@ final class ExoPlaybackThresholdCoordinator { lastRebufferAtMs, maxRebufferCount, false, + 0, null, policy); } diff --git a/app/src/main/java/com/fongmi/android/tv/player/exo/ExoUtil.java b/app/src/main/java/com/fongmi/android/tv/player/exo/ExoUtil.java index 9788828447..ff330d80ed 100644 --- a/app/src/main/java/com/fongmi/android/tv/player/exo/ExoUtil.java +++ b/app/src/main/java/com/fongmi/android/tv/player/exo/ExoUtil.java @@ -1029,6 +1029,21 @@ public class ExoUtil { protected void buildVideoRenderers(Context context, int extensionRendererMode, MediaCodecSelector mediaCodecSelector, boolean enableDecoderFallback, Handler eventHandler, VideoRendererEventListener eventListener, long allowedVideoJoiningTimeMs, ArrayList out) { MediaCodecSelector videoCodecSelector = getVideoCodecSelector(mediaCodecSelector); int ffmpegVideoRenderMode = getFfmpegVideoRenderMode(videoRenderMode); + try { + ExoDv5GpuRenderer dv5Renderer = ExoDv5GpuRendererFactory.create( + PlaybackExperimentSetting.isDomainEnabled( + PlaybackExperimentPolicy.Domain.EXO), + context, + getCodecAdapterFactory(), + videoCodecSelector, + allowedVideoJoiningTimeMs, + enableDecoderFallback, + eventHandler, + eventListener, + frameSchedulingDecision); + if (dv5Renderer != null) out.add(dv5Renderer); + } catch (Throwable ignored) { + } if (decoderRuntimeSession != null && videoRenderMode == EXTENSION_RENDERER_MODE_OFF) { out.add(new ExoRuntimeAwareVideoRenderer( @@ -1230,9 +1245,27 @@ public class ExoUtil { if (format == null || !MimeTypes.VIDEO_DOLBY_VISION.equals(format.sampleMimeType) || format.codecs == null) return false; + if (ExoDv5GpuMappingPolicy.isProfile5( + format.sampleMimeType, format.codecs)) { + ExoDv5GpuMappingPolicy.Decision decision = + ExoDv5GpuMappingPolicy.decide( + new ExoDv5GpuMappingPolicy.Input( + true, + format.cryptoType != C.CRYPTO_TYPE_NONE, + false, + false, + Build.VERSION.SDK_INT, + false, + false, + false, + false, + false, + false, + true)); + return decision.route() + == ExoDv5GpuMappingPolicy.Route.LEGACY_HDR10_FALLBACK; + } String codecs = format.codecs.toLowerCase(java.util.Locale.US); - if (codecs.startsWith("dvhe.05.") - || codecs.startsWith("dvh1.05.")) return true; return dv7FallbackEnabled && (codecs.startsWith("dvhe.07.") || codecs.startsWith("dvh1.07.")); } diff --git a/app/src/main/java/com/fongmi/android/tv/player/exo/PlaybackAnalyticsListener.java b/app/src/main/java/com/fongmi/android/tv/player/exo/PlaybackAnalyticsListener.java index 3bcb84d6a6..ab1ed649b8 100644 --- a/app/src/main/java/com/fongmi/android/tv/player/exo/PlaybackAnalyticsListener.java +++ b/app/src/main/java/com/fongmi/android/tv/player/exo/PlaybackAnalyticsListener.java @@ -23,6 +23,7 @@ import com.fongmi.android.tv.setting.ExoPerformanceSetting; import com.fongmi.android.tv.setting.PlaybackPerformanceCatalog; import com.fongmi.android.tv.setting.PlaybackPerformanceSetting; import com.fongmi.android.tv.setting.PlayerSetting; +import com.fongmi.android.tv.player.PlaybackAutoContext; import com.fongmi.android.tv.player.PlaybackTrace; import com.github.catvod.crawler.DebugEventLimiter; import com.github.catvod.crawler.SpiderDebug; @@ -36,6 +37,19 @@ public class PlaybackAnalyticsListener implements AnalyticsListener, VideoFrameM private static volatile long lastMediaEstimateLogMs; private static volatile boolean loading; private static volatile boolean frameSchedulingExperimentActive; + private static volatile long seekSequence; + private static volatile long activeSeekSequence; + private static volatile long seekRequestedAtMs; + private static volatile long seekBufferingAtMs; + private static volatile long seekReadyAtMs; + private static volatile long seekTargetPositionMs; + private static volatile boolean seekFirstFrameLogged; + private static volatile long seekFirstVideoFrameAtMs; + private static volatile long seekFirstAudioAdvanceAtMs; + private static volatile long seekPlayingAtMs; + private static volatile long lastSeekVideoFrameAtMs; + private static volatile long lastSeekVideoPtsUs; + private static volatile int seekVideoFrameCount; private static volatile ForwardBufferTrend.Snapshot lastStableBufferTrend = ForwardBufferTrend.Snapshot.unknown(); private static final long BANDWIDTH_LOG_INTERVAL_MS = 5_000; @@ -43,6 +57,7 @@ public class PlaybackAnalyticsListener implements AnalyticsListener, VideoFrameM private static final long LOADING_LOG_INTERVAL_MS = 5_000; private static final long LOW_BUFFER_LOADING_LOG_INTERVAL_MS = 1_000; private static final long LOW_BUFFER_LOG_THRESHOLD_MS = 8_000; + private static final long SEEK_TRACE_TIMEOUT_MS = 30_000; private static final ObservedMediaBitrateEstimator BITRATE_ESTIMATOR = new ObservedMediaBitrateEstimator(); private static final ObservedVideoFrameRateEstimator FRAME_RATE_ESTIMATOR = new ObservedVideoFrameRateEstimator(); private static final ExoFrameTimingMetrics FRAME_TIMING_METRICS = new ExoFrameTimingMetrics(); @@ -153,6 +168,50 @@ public class PlaybackAnalyticsListener implements AnalyticsListener, VideoFrameM return BUFFER_TREND.snapshot(); } + public static boolean isSeekRecoveryActive() { + return ExoPlaybackThresholdCoordinator.process().isSeekPending( + ExoPlaybackThresholdCoordinator.currentSession(), + SystemClock.elapsedRealtime()); + } + + public static void onUserSeekRequested( + long originPositionMs, + long targetPositionMs, + @Player.State int state, + long bufferedPositionMs, + long totalBufferedDurationMs, + boolean isLoading, + boolean isPlaying) { + long now = SystemClock.elapsedRealtime(); + ExoPlaybackThresholdCoordinator.process().markSeek( + ExoPlaybackThresholdCoordinator.currentSession(), now); + long sequence = seekSequence == Long.MAX_VALUE ? 1 : seekSequence + 1; + seekSequence = sequence; + activeSeekSequence = sequence; + seekRequestedAtMs = now; + seekBufferingAtMs = 0; + seekReadyAtMs = 0; + seekTargetPositionMs = Math.max(0, targetPositionMs); + seekFirstFrameLogged = false; + seekFirstVideoFrameAtMs = 0; + seekFirstAudioAdvanceAtMs = 0; + seekPlayingAtMs = 0; + lastSeekVideoFrameAtMs = 0; + lastSeekVideoPtsUs = 0; + seekVideoFrameCount = 0; + seekTrace( + "phase=request seq=%d origin=%d target=%d delta=%d state=%s bufferedPosition=%d totalBuffered=%d loading=%s playing=%s", + sequence, + Math.max(0, originPositionMs), + seekTargetPositionMs, + targetPositionMs - originPositionMs, + stateName(state), + Math.max(0, bufferedPositionMs), + Math.max(0, totalBufferedDurationMs), + isLoading, + isPlaying); + } + static ForwardBufferTrend.Snapshot getLastStableBufferTrend() { return lastStableBufferTrend; } @@ -171,6 +230,18 @@ public class PlaybackAnalyticsListener implements AnalyticsListener, VideoFrameM lastMediaEstimateLogMs = 0; loading = false; frameSchedulingExperimentActive = false; + activeSeekSequence = 0; + seekRequestedAtMs = 0; + seekBufferingAtMs = 0; + seekReadyAtMs = 0; + seekTargetPositionMs = 0; + seekFirstFrameLogged = false; + seekFirstVideoFrameAtMs = 0; + seekFirstAudioAdvanceAtMs = 0; + seekPlayingAtMs = 0; + lastSeekVideoFrameAtMs = 0; + lastSeekVideoPtsUs = 0; + seekVideoFrameCount = 0; playbackTraceId = PlaybackTrace.NONE; BITRATE_ESTIMATOR.reset(); FRAME_RATE_ESTIMATOR.reset(); @@ -221,6 +292,10 @@ public class PlaybackAnalyticsListener implements AnalyticsListener, VideoFrameM @Override public void onPlaybackStateChanged(EventTime eventTime, @Player.State int state) { long now = SystemClock.elapsedRealtime(); + PlaybackAutoContext.SessionToken thresholdSession = + ExoPlaybackThresholdCoordinator.currentSession(); + boolean seekRecovery = ExoPlaybackThresholdCoordinator.process() + .isSeekPending(thresholdSession, now); Snapshot previous = snapshot; Snapshot next = snapshot.withState(stateName(state), eventTime.currentPlaybackPositionMs, eventTime.totalBufferedDurationMs); if (state == Player.STATE_BUFFERING) { @@ -228,13 +303,16 @@ public class PlaybackAnalyticsListener implements AnalyticsListener, VideoFrameM BITRATE_ESTIMATOR.disrupt(); BUFFER_TREND.reset(); FRAME_TIMING_METRICS.resetReleaseContinuity(); - if (next.everReady() && next.rebufferStartMs() <= 0) next = next.withRebufferStart(now); + if (next.everReady() && next.rebufferStartMs() <= 0 && !seekRecovery) { + next = next.withRebufferStart(now); + } } if (state != Player.STATE_BUFFERING && next.rebufferStartMs() > 0) next = next.withRebufferEnd(now); if (state == Player.STATE_READY) next = next.withEverReady(); boolean rebufferStarted = previous.rebufferStartMs() <= 0 && next.rebufferStartMs() > 0; boolean rebufferEnded = previous.rebufferStartMs() > 0 && next.rebufferStartMs() <= 0; snapshot = next; + logSeekState(eventTime, state, now); if (rebufferStarted) { FRAME_SCHEDULING_METRICS.observeBoundary( ExoFrameSchedulingExperimentMetrics.Boundary.REBUFFER); @@ -248,7 +326,7 @@ public class PlaybackAnalyticsListener implements AnalyticsListener, VideoFrameM || state == Player.STATE_IDLE || state == Player.STATE_ENDED) { ExoPlaybackThresholdCoordinator.process().endEpisode( - ExoPlaybackThresholdCoordinator.currentSession()); + thresholdSession); } if (!SpiderDebug.isEnabled()) return; if (rebufferStarted) { @@ -368,12 +446,49 @@ public class PlaybackAnalyticsListener implements AnalyticsListener, VideoFrameM if (!SpiderDebug.isEnabled()) return; traceLog("audio sink error type=%s message=%s", error == null ? "unknown" : error.getClass().getSimpleName(), error == null || error.getMessage() == null ? "" : error.getMessage()); + long now = nowElapsed(); + if (activeSeek(now)) { + seekTrace( + "phase=audio-sink-error seq=%d elapsed=%d type=%s message=%s position=%d buffered=%d", + activeSeekSequence, + elapsedSinceSeek(now), + error == null ? "unknown" : error.getClass().getSimpleName(), + error == null || error.getMessage() == null ? "" : error.getMessage(), + Math.max(0, eventTime.currentPlaybackPositionMs), + Math.max(0, eventTime.totalBufferedDurationMs)); + } } @Override public void onAudioUnderrun(EventTime eventTime, int bufferSize, long bufferSizeMs, long elapsedSinceLastFeedMs) { if (!SpiderDebug.isEnabled()) return; traceLog("audio underrun buffer=%d bufferMs=%d elapsedSinceFeedMs=%d", bufferSize, bufferSizeMs, elapsedSinceLastFeedMs); + long now = nowElapsed(); + if (activeSeek(now)) { + seekTrace( + "phase=audio-underrun seq=%d elapsed=%d buffer=%d bufferMs=%d elapsedSinceFeedMs=%d position=%d buffered=%d", + activeSeekSequence, + elapsedSinceSeek(now), + bufferSize, + bufferSizeMs, + elapsedSinceLastFeedMs, + Math.max(0, eventTime.currentPlaybackPositionMs), + Math.max(0, eventTime.totalBufferedDurationMs)); + } + } + + @Override + public void onAudioPositionAdvancing(EventTime eventTime, long playoutStartSystemTimeMs) { + long now = nowElapsed(); + if (!activeSeek(now) || seekFirstAudioAdvanceAtMs > 0) return; + seekFirstAudioAdvanceAtMs = now; + seekTrace( + "phase=audio-advancing seq=%d elapsed=%d position=%d buffered=%d playoutStart=%d", + activeSeekSequence, + elapsedSinceSeek(now), + Math.max(0, eventTime.currentPlaybackPositionMs), + Math.max(0, eventTime.totalBufferedDurationMs), + playoutStartSystemTimeMs); } @Override @@ -444,18 +559,61 @@ public class PlaybackAnalyticsListener implements AnalyticsListener, VideoFrameM @Override public void onPositionDiscontinuity(EventTime eventTime, Player.PositionInfo oldPosition, Player.PositionInfo newPosition, int reason) { + boolean seek = reason == Player.DISCONTINUITY_REASON_SEEK + || reason == Player.DISCONTINUITY_REASON_SEEK_ADJUSTMENT; + long now = nowElapsed(); BITRATE_ESTIMATOR.disrupt(); FRAME_RATE_ESTIMATOR.reset(); FRAME_TIMING_METRICS.resetReleaseContinuity(); - if (reason == Player.DISCONTINUITY_REASON_SEEK - || reason == Player.DISCONTINUITY_REASON_SEEK_ADJUSTMENT) { + if (seek) { FRAME_SCHEDULING_METRICS.observeBoundary( ExoFrameSchedulingExperimentMetrics.Boundary.SEEK); } BUFFER_TREND.reset(); lastStableBufferTrend = ForwardBufferTrend.Snapshot.unknown(); - ExoPlaybackThresholdCoordinator.process().disrupt( - ExoPlaybackThresholdCoordinator.currentSession()); + PlaybackAutoContext.SessionToken thresholdSession = + ExoPlaybackThresholdCoordinator.currentSession(); + ExoPlaybackThresholdCoordinator.process().disrupt(thresholdSession); + if (seek) { + ExoPlaybackThresholdCoordinator.process().markSeek( + thresholdSession, now); + if (!activeSeek(now) && SpiderDebug.isEnabled()) { + long sequence = seekSequence == Long.MAX_VALUE ? 1 : seekSequence + 1; + seekSequence = sequence; + activeSeekSequence = sequence; + seekRequestedAtMs = now; + seekBufferingAtMs = 0; + seekReadyAtMs = 0; + seekTargetPositionMs = Math.max(0, newPosition.positionMs); + seekFirstFrameLogged = false; + seekFirstVideoFrameAtMs = 0; + seekFirstAudioAdvanceAtMs = 0; + seekPlayingAtMs = 0; + lastSeekVideoFrameAtMs = 0; + lastSeekVideoPtsUs = 0; + seekVideoFrameCount = 0; + seekTrace( + "phase=request-observed seq=%d origin=%d target=%d state=%s buffered=%d loading=%s", + sequence, + Math.max(0, oldPosition.positionMs), + seekTargetPositionMs, + snapshot.state(), + Math.max(0, eventTime.totalBufferedDurationMs), + loading); + } + if (!activeSeek(now)) return; + seekTrace( + "phase=discontinuity seq=%d elapsed=%d reason=%d old=%d requested=%d actual=%d adjustment=%d buffered=%d loading=%s", + activeSeekSequence, + elapsedSinceSeek(now), + reason, + Math.max(0, oldPosition.positionMs), + seekTargetPositionMs, + Math.max(0, newPosition.positionMs), + newPosition.positionMs - seekTargetPositionMs, + Math.max(0, eventTime.totalBufferedDurationMs), + loading); + } } @Override @@ -465,6 +623,45 @@ public class PlaybackAnalyticsListener implements AnalyticsListener, VideoFrameM FRAME_TIMING_METRICS.observeFrameRelease( presentationTimeUs, releaseTimeNs, System.nanoTime()); } + long now = nowElapsed(); + PlaybackAutoContext.SessionToken thresholdSession = + ExoPlaybackThresholdCoordinator.currentSession(); + if ("READY".equals(snapshot.state()) + && ExoPlaybackThresholdCoordinator.process() + .isSeekPending(thresholdSession, now)) { + ExoPlaybackThresholdCoordinator.process().endEpisode(thresholdSession); + } + if (!activeSeek(now)) return; + seekVideoFrameCount++; + if (seekFirstVideoFrameAtMs <= 0) { + seekFirstVideoFrameAtMs = now; + lastSeekVideoFrameAtMs = now; + lastSeekVideoPtsUs = presentationTimeUs; + seekTrace( + "phase=video-frame-first seq=%d elapsed=%d frame=%d ptsUs=%d position=%d buffered=%d", + activeSeekSequence, + elapsedSinceSeek(now), + seekVideoFrameCount, + presentationTimeUs, + Math.max(0, snapshot.positionMs()), + Math.max(0, snapshot.bufferedMs())); + return; + } + long gapMs = Math.max(0, now - lastSeekVideoFrameAtMs); + if (gapMs >= 120) { + seekTrace( + "phase=video-frame-gap seq=%d elapsed=%d gap=%d frame=%d ptsDeltaUs=%d position=%d buffered=%d state=%s", + activeSeekSequence, + elapsedSinceSeek(now), + gapMs, + seekVideoFrameCount, + presentationTimeUs - lastSeekVideoPtsUs, + Math.max(0, snapshot.positionMs()), + Math.max(0, snapshot.bufferedMs()), + snapshot.state()); + } + lastSeekVideoFrameAtMs = now; + lastSeekVideoPtsUs = presentationTimeUs; } @Override @@ -473,6 +670,77 @@ public class PlaybackAnalyticsListener implements AnalyticsListener, VideoFrameM Object output, long renderTimeMs) { FRAME_SCHEDULING_METRICS.observeFirstFrame(renderTimeMs); + long now = nowElapsed(); + if (activeSeek(now) && !seekFirstFrameLogged) { + seekFirstFrameLogged = true; + seekTrace( + "phase=first-frame seq=%d elapsed=%d afterReady=%d position=%d buffered=%d loading=%s", + activeSeekSequence, + elapsedSinceSeek(now), + seekReadyAtMs <= 0 ? -1 : Math.max(0, now - seekReadyAtMs), + Math.max(0, eventTime.currentPlaybackPositionMs), + Math.max(0, eventTime.totalBufferedDurationMs), + loading); + } + } + + @Override + public void onIsPlayingChanged(EventTime eventTime, boolean isPlaying) { + if (!isPlaying) return; + long now = nowElapsed(); + if (!activeSeek(now)) return; + if (seekPlayingAtMs > 0) return; + seekPlayingAtMs = now; + seekTrace( + "phase=playing seq=%d elapsed=%d afterReady=%d position=%d buffered=%d loading=%s", + activeSeekSequence, + elapsedSinceSeek(now), + seekReadyAtMs <= 0 ? -1 : Math.max(0, now - seekReadyAtMs), + Math.max(0, eventTime.currentPlaybackPositionMs), + Math.max(0, eventTime.totalBufferedDurationMs), + loading); + } + + private static void logSeekState( + EventTime eventTime, + @Player.State int state, + long now) { + if (!activeSeek(now)) return; + if (state == Player.STATE_BUFFERING && seekBufferingAtMs <= 0) { + seekBufferingAtMs = now; + } else if (state == Player.STATE_READY && seekReadyAtMs <= 0) { + seekReadyAtMs = now; + } + long bufferingMs = seekBufferingAtMs <= 0 || state != Player.STATE_READY + ? -1 : Math.max(0, now - seekBufferingAtMs); + seekTrace( + "phase=state seq=%d elapsed=%d state=%s bufferingDuration=%d position=%d buffered=%d loading=%s", + activeSeekSequence, + elapsedSinceSeek(now), + stateName(state), + bufferingMs, + Math.max(0, eventTime.currentPlaybackPositionMs), + Math.max(0, eventTime.totalBufferedDurationMs), + loading); + } + + private static boolean activeSeek(long now) { + if (activeSeekSequence <= 0 || seekRequestedAtMs <= 0) return false; + if (now - seekRequestedAtMs <= SEEK_TRACE_TIMEOUT_MS) return true; + activeSeekSequence = 0; + return false; + } + + private static long elapsedSinceSeek(long now) { + return Math.max(0, now - seekRequestedAtMs); + } + + private static long nowElapsed() { + return SystemClock.elapsedRealtime(); + } + + private static void seekTrace(String format, Object... args) { + PlaybackTrace.log("exo-seek", playbackTraceId, format, args); } @Override diff --git a/app/src/main/java/com/fongmi/android/tv/player/exo/PreCache.java b/app/src/main/java/com/fongmi/android/tv/player/exo/PreCache.java index 384ee4f205..5a1ef850f4 100644 --- a/app/src/main/java/com/fongmi/android/tv/player/exo/PreCache.java +++ b/app/src/main/java/com/fongmi/android/tv/player/exo/PreCache.java @@ -46,6 +46,7 @@ public class PreCache implements Player.Listener { private static final long TICK_MS = 5000; private static final long BUFFER_GAP_MS = 1250; private static final long DISK_RANGE_GAP_TOLERANCE_MS = 2000; + private static final int PRELOAD_FAILURE_CIRCUIT_THRESHOLD = 2; private final PreloadLifecycleTracker lifecycle = new PreloadLifecycleTracker(); private final PlaybackDiskBufferStore diskBufferStore = PlaybackDiskBufferStore.process(); @@ -93,6 +94,9 @@ public class PreCache implements Player.Listener { private String mediaKey = ""; private boolean playable; private boolean refillActive; + private boolean seekPreloadSuppressed; + private boolean preloadErrorCircuitOpen; + private int preloadFailureStreak; private boolean externalPreloadCircuitOpen; private boolean diskPreloadCircuitOpen; private boolean memoryPreloadPaused; @@ -176,6 +180,9 @@ public class PreCache implements Player.Listener { clearSeek(); playable = false; refillActive = true; + seekPreloadSuppressed = false; + preloadErrorCircuitOpen = false; + preloadFailureStreak = 0; externalPreloadCircuitOpen = false; diskPreloadCircuitOpen = false; bufferGate = BufferGate.FIRST_FRAME; @@ -223,6 +230,9 @@ public class PreCache implements Player.Listener { clearSeek(); playable = false; refillActive = true; + seekPreloadSuppressed = false; + preloadErrorCircuitOpen = false; + preloadFailureStreak = 0; externalPreloadCircuitOpen = false; diskPreloadCircuitOpen = false; memoryPreloadPaused = false; @@ -287,7 +297,9 @@ public class PreCache implements Player.Listener { @Override public void onIsPlayingChanged(boolean isPlaying) { - if (!isPlaying || playable || player == null) return; + if (player == null) return; + if (isPlaying && seekPreloadSuppressed) check(); + if (!isPlaying || playable) return; if (!player.getCurrentTracks().containsType(C.TRACK_TYPE_VIDEO) && player.getCurrentTracks().containsType(C.TRACK_TYPE_AUDIO)) { markPlayable(); } @@ -310,9 +322,11 @@ public class PreCache implements Player.Listener { if (!isSeek(reason) || helper == null) return; transition(PreloadLifecycleTracker.State.CANCELLED_SEEK, "seek", "generation=%d oldPosition=%d newPosition=%d", generation, oldPosition.positionMs, newPosition.positionMs); if (autoPolicy != null) autoPolicy.disrupt(SystemClock.elapsedRealtime()); + seekPreloadSuppressed = true; + preloadFailureStreak = 0; stopCurrentTask("seek"); markSeek(newPosition.positionMs); - refillActive = true; + refillActive = false; if (playable) bufferGate = BufferGate.RECOVERY; check(); } @@ -343,6 +357,16 @@ public class PreCache implements Player.Listener { } int state = player.getPlaybackState(); if (isStopped(state)) return false; + if (seekPreloadSuppressed) { + SafeBufferStatus status = getSafeBufferStatus(); + if (!shouldReleaseSeekPreloadSuppression(state, player.isPlaying(), status.loading(), status.safe())) { + transition(PreloadLifecycleTracker.State.WAIT_RECOVERY_BUFFER, "seek-suppressed", "generation=%d state=%d playing=%s requiredMs=%d bufferedMs=%d loading=%s", generation, state, player.isPlaying(), status.requiredMs(), status.bufferedMs(), status.loading()); + return true; + } + seekPreloadSuppressed = false; + refillActive = true; + PlaybackTrace.log("exo-preload", playbackTraceId, "event=seek-suppressed-release session=%d generation=%d bufferedMs=%d requiredMs=%d", lifecycle.sessionId(), generation, status.bufferedMs(), status.requiredMs()); + } if (state != Player.STATE_READY) return true; if (!playable) { transition(PreloadLifecycleTracker.State.WAIT_FIRST_FRAME, "first-frame", "generation=%d position=%d buffered=%d loading=%s", generation, player.getCurrentPosition(), player.getTotalBufferedDuration(), player.isLoading()); @@ -372,6 +396,10 @@ public class PreCache implements Player.Listener { stop("live"); return false; } + if (preloadErrorCircuitOpen) { + transition(PreloadLifecycleTracker.State.PAUSED_AUTO, "preload-error-circuit-open", "generation=%d position=%d buffered=%d", generation, player.getCurrentPosition(), player.getTotalBufferedDuration()); + return false; + } if (diskPreloadCircuitOpen) { transition(PreloadLifecycleTracker.State.PAUSED_STORAGE, "disk-preload-circuit-open", "generation=%d position=%d buffered=%d", generation, player.getCurrentPosition(), player.getTotalBufferedDuration()); return false; @@ -660,7 +688,16 @@ public class PreCache implements Player.Listener { private void handleTaskError(PreloadLifecycleTracker.TaskEvent.Outcome outcome, String reason, Throwable error) { if (finishTask(outcome, reason, error) == null) return; if (ExoCacheWriteErrorClassifier.isDiskWriteFailure(error)) openDiskCircuit(reason, error); - else openExternalCircuit(reason, error); + else if (route == PlaybackRoute.EXTERNAL_LOOPBACK_PROXY) openExternalCircuit(reason, error); + else if (shouldOpenPreloadFailureCircuit(++preloadFailureStreak)) openPreloadErrorCircuit(reason, error); + } + + private void openPreloadErrorCircuit(String reason, Throwable error) { + if (preloadErrorCircuitOpen) return; + preloadErrorCircuitOpen = true; + PlaybackTrace.log("exo-preload", playbackTraceId, "event=preload-circuit-open session=%d generation=%d reason=%s error=%s action=stop-preload-keep-playback", lifecycle.sessionId(), generation, reason, error == null ? "-" : error.getClass().getSimpleName()); + stopCurrentTask("preload-error-circuit-open"); + transition(PreloadLifecycleTracker.State.PAUSED_AUTO, "preload-error-circuit-open", "generation=%d failures=%d", generation, preloadFailureStreak); } private void openDiskCircuit(String reason, Throwable error) { @@ -1233,6 +1270,7 @@ public class PreCache implements Player.Listener { PreloadLifecycleTracker.State state = outcome == PreloadLifecycleTracker.TaskEvent.Outcome.COMPLETED ? PreloadLifecycleTracker.State.WAIT_NEXT_RANGE : PreloadLifecycleTracker.State.WAIT_RETRY; transition(state, reason, "generation=%d task=%d", event.generation(), event.taskId()); if (outcome == PreloadLifecycleTracker.TaskEvent.Outcome.COMPLETED) { + preloadFailureStreak = 0; diskBufferStore.recordCompleted(mediaKey, event.startMs(), saturatedAdd(event.startMs(), event.lengthMs())); requestImmediateCheck(event.generation()); } @@ -1250,6 +1288,14 @@ public class PreCache implements Player.Listener { return value > Long.MAX_VALUE - increment ? Long.MAX_VALUE : value + increment; } + static boolean shouldReleaseSeekPreloadSuppression(int playbackState, boolean playing, boolean loading, boolean safeBuffer) { + return playbackState == Player.STATE_READY && playing && !loading && safeBuffer; + } + + static boolean shouldOpenPreloadFailureCircuit(int consecutiveFailures) { + return consecutiveFailures >= PRELOAD_FAILURE_CIRCUIT_THRESHOLD; + } + private void beginPreloadTraffic() { closePreloadTraffic(); preloadTrafficRegistration = ExoPreloadTrafficCoordinator.process().acquire( diff --git a/app/src/main/java/com/fongmi/android/tv/player/iso/IsoTrackMetadataResolver.java b/app/src/main/java/com/fongmi/android/tv/player/iso/IsoTrackMetadataResolver.java index 105e62c33f..8bc6bffcca 100644 --- a/app/src/main/java/com/fongmi/android/tv/player/iso/IsoTrackMetadataResolver.java +++ b/app/src/main/java/com/fongmi/android/tv/player/iso/IsoTrackMetadataResolver.java @@ -13,6 +13,7 @@ import androidx.media3.extractor.iso.udf.UdfFileSystem; import java.io.IOException; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; @@ -123,17 +124,28 @@ final class IsoTrackMetadataResolver { return 0; } - private static byte[] readEntry(CacheDataReader reader, IsoFileEntry entry) throws IOException { + static byte[] readEntry(CacheDataReader reader, IsoFileEntry entry) throws IOException { if (entry.length < 0 || entry.length > MAX_METADATA_FILE_BYTES) { throw new IOException("Blu-ray metadata file is too large: " + entry.name + " size=" + entry.length); } byte[] data = new byte[(int) entry.length]; - int read = 0; - while (read < data.length) { - int count = reader.read(entry.byteOffset + read, data, read, data.length - read); - if (count <= 0) throw new IOException("Unexpected EOF reading " + entry.name); - read += count; + int position = 0; + for (int i = 0; i < entry.extentOffsets.length && position < data.length; i++) { + int extentLength = (int) Math.min(entry.extentLengths[i], data.length - position); + if (entry.extentOffsets[i] == IsoFileEntry.UNRECORDED_EXTENT_OFFSET) { + Arrays.fill(data, position, position + extentLength, (byte) 0); + position += extentLength; + continue; + } + int extentRead = 0; + while (extentRead < extentLength) { + int count = reader.read(entry.extentOffsets[i] + extentRead, data, position, extentLength - extentRead); + if (count <= 0) throw new IOException("Unexpected EOF reading " + entry.name); + position += count; + extentRead += count; + } } + if (position != data.length) throw new IOException("Unexpected EOF reading " + entry.name); return data; } diff --git a/app/src/main/java/com/fongmi/android/tv/player/lut/LutEligibility.java b/app/src/main/java/com/fongmi/android/tv/player/lut/LutEligibility.java index 952cd42def..393f235238 100644 --- a/app/src/main/java/com/fongmi/android/tv/player/lut/LutEligibility.java +++ b/app/src/main/java/com/fongmi/android/tv/player/lut/LutEligibility.java @@ -32,7 +32,7 @@ public class LutEligibility { if (spec != null && spec.getDrm() != null) return ResUtil.getString(R.string.lut_unavailable_drm); if (!engine.supportsNativeLut() && PlayerSetting.isTunnel()) return ResUtil.getString(R.string.lut_unavailable_tunnel); if (!engine.supportsNativeLut() && engine.getDecode() == PlayerEngine.SOFT) return ResUtil.getString(R.string.lut_unavailable_soft_decode); - if (!engine.supportsNativeLut() && PlayerSetting.isVideoPrefer()) return ResUtil.getString(R.string.lut_unavailable_video_prefer); + if (!engine.supportsNativeLut() && PlayerSetting.isVideoPrefer(PlayerSetting.getActivePlayer())) return ResUtil.getString(R.string.lut_unavailable_video_prefer); if (isHdr(engine.getVideoFormat()) || isHdr(engine.getCurrentTracks())) return ResUtil.getString(R.string.lut_unavailable_hdr); if (isKnownAudioOnly(engine.getCurrentTracks())) return ResUtil.getString(R.string.lut_unavailable_no_video); return null; diff --git a/app/src/main/java/com/fongmi/android/tv/player/mpv/MpvAutoOutputPolicy.java b/app/src/main/java/com/fongmi/android/tv/player/mpv/MpvAutoOutputPolicy.java index f53e407271..5eace2e5f2 100644 --- a/app/src/main/java/com/fongmi/android/tv/player/mpv/MpvAutoOutputPolicy.java +++ b/app/src/main/java/com/fongmi/android/tv/player/mpv/MpvAutoOutputPolicy.java @@ -71,6 +71,20 @@ public final class MpvAutoOutputPolicy { return automaticOutput && currentlyDirect && requiresGpuSubtitle(externalSubtitleActive, userRequestedSubtitle); } + public static boolean canRevealDirectFrame(boolean automaticOutput, + boolean outputEvaluated, + boolean playbackReady, + boolean surfaceDirect, + int width, + int height) { + return automaticOutput + && !outputEvaluated + && playbackReady + && surfaceDirect + && width > 0 + && height > 0; + } + public enum Transition { KEEP_GPU, ENTER_SURFACE_DIRECT, diff --git a/app/src/main/java/com/fongmi/android/tv/player/mpv/MpvAutoRenderPolicy.java b/app/src/main/java/com/fongmi/android/tv/player/mpv/MpvAutoRenderPolicy.java new file mode 100644 index 0000000000..4d9018d025 --- /dev/null +++ b/app/src/main/java/com/fongmi/android/tv/player/mpv/MpvAutoRenderPolicy.java @@ -0,0 +1,40 @@ +package com.fongmi.android.tv.player.mpv; + +public final class MpvAutoRenderPolicy { + + private MpvAutoRenderPolicy() { + } + + public static Decision evaluate(boolean renderAutomatic, + boolean hardDecode, + int dolbyVisionProfile, + MpvAutoOutputPolicy.DolbyVisionSupport dolbyVisionSupport, + boolean nativeVulkan, + boolean deviceVulkan, + boolean currentlyVulkan, + boolean disabledForItem) { + if (disabledForItem) return keep("item-fallback"); + if (currentlyVulkan) return keep("already-vulkan"); + if (!renderAutomatic) return keep("render-overridden"); + if (!hardDecode) return keep("software-decode"); + if (dolbyVisionProfile != 5) return keep("not-dv5"); + if (dolbyVisionSupport != MpvAutoOutputPolicy.DolbyVisionSupport.UNSUPPORTED) { + return keep(dolbyVisionSupport == MpvAutoOutputPolicy.DolbyVisionSupport.SUPPORTED + ? "native-dv5-supported" : "native-dv5-unknown"); + } + if (!nativeVulkan || !deviceVulkan) return keep("vulkan-unavailable"); + return new Decision(Action.ENABLE_VULKAN, "dv5-gpu-mapping-vulkan"); + } + + private static Decision keep(String reason) { + return new Decision(Action.KEEP, reason); + } + + public enum Action { + KEEP, + ENABLE_VULKAN + } + + public record Decision(Action action, String reason) { + } +} diff --git a/app/src/main/java/com/fongmi/android/tv/service/PlaybackService.java b/app/src/main/java/com/fongmi/android/tv/service/PlaybackService.java index 981ad3f67b..fa7b895ddb 100644 --- a/app/src/main/java/com/fongmi/android/tv/service/PlaybackService.java +++ b/app/src/main/java/com/fongmi/android/tv/service/PlaybackService.java @@ -242,6 +242,7 @@ private AudioHistory.Record audioHistoryRecord; running = false; syncAudioHistoryProgress(true); clearAudioHistoryRecord(); + player.prepareTerminalRelease(); PlaybackEventCollector.get().onStop(player); if (desktopLyrics != null) desktopLyrics.release(); releaseSession(); @@ -275,6 +276,7 @@ private AudioHistory.Record audioHistoryRecord; keepAlive = false; syncAudioHistoryProgress(true); clearAudioHistoryRecord(); + player.prepareTerminalRelease(); stopAndClear(); removeForeground(); stopSelf(); diff --git a/app/src/main/java/com/fongmi/android/tv/setting/AppBranding.java b/app/src/main/java/com/fongmi/android/tv/setting/AppBranding.java index def24dca63..4a25c9c260 100644 --- a/app/src/main/java/com/fongmi/android/tv/setting/AppBranding.java +++ b/app/src/main/java/com/fongmi/android/tv/setting/AppBranding.java @@ -17,7 +17,10 @@ import androidx.core.graphics.drawable.RoundedBitmapDrawable; import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory; import com.fongmi.android.tv.R; +import com.fongmi.android.tv.api.config.VodConfig; +import com.fongmi.android.tv.bean.Config; import com.fongmi.android.tv.ui.activity.HomeActivity; +import com.fongmi.android.tv.utils.ImgUtil; import com.github.catvod.utils.Prefers; /** Owns the two supported built-in app branding choices. */ @@ -47,8 +50,14 @@ public final class AppBranding { return context.getString(R.string.app_name); } + /** + * 首页标题优先展示站点/配置自己的名字,只有两者都空时才回落到应用名。 + * 固定返回应用名会让所有站源都显示成「默影视」,看不出当前在哪个源。 + */ @NonNull public static String getDisplayName(@NonNull Context context, @Nullable String homeName, @Nullable String configName) { + if (homeName != null && !homeName.trim().isEmpty()) return homeName; + if (configName != null && !configName.trim().isEmpty()) return configName; return getName(context); } @@ -71,9 +80,15 @@ public final class AppBranding { return context.getString(iconLabelResource(getIconMode(context))); } - /** Uses the selected built-in icon in the app UI with a circular presentation. */ + /** + * 首帧先落品牌图标,避免闪白;随后若线路配置带 logo 就异步覆盖上去。 + * 只用品牌图标会让配置里自带的线路图标彻底失效。 + */ public static void applyLogo(@NonNull ImageView view) { view.setImageDrawable(logoDrawable(view.getContext())); + Config config = VodConfig.get().getConfig(); + String logo = config == null ? null : config.getLogo(); + if (logo != null && !logo.trim().isEmpty()) ImgUtil.logo(view, logo); } /** diff --git a/app/src/main/java/com/fongmi/android/tv/setting/PlaybackPerformanceCatalog.java b/app/src/main/java/com/fongmi/android/tv/setting/PlaybackPerformanceCatalog.java index 694cec832f..96028c65b2 100644 --- a/app/src/main/java/com/fongmi/android/tv/setting/PlaybackPerformanceCatalog.java +++ b/app/src/main/java/com/fongmi/android/tv/setting/PlaybackPerformanceCatalog.java @@ -140,7 +140,7 @@ public final class PlaybackPerformanceCatalog { options.add(option(MPV_INTERPOLATION, DECODE, "平滑运动", "怎么选:默认关闭。只有GPU余量充足、使用GPU渲染+显示重采样且想改善低帧率运动时才开启;电视4K、HDR、LUT或已经卡顿时必须关闭。代价:会明显增加GPU负载,电视直出时不生效。")); options.add(option(MPV_SOFT_TUNE, DECODE, "软解降负载", "作用:仅软件解码时减少滤波和解码工作。默认“温和”;软解仍掉帧可选“积极”;硬解视频无需靠它提速。代价:模式越积极,细节和画面连续性损失越大。")); options.add(option(MPV_VERBOSE_LOG, DECODE, "详细日志", "怎么选:正常播放保持“正常”(默认);只在排查崩溃、解码或缓冲问题时临时打开详细日志。代价:增加JNI、字符串处理和日志I/O,可能干扰低性能设备的流畅度。")); - options.add(option(DV7_HDR10_FALLBACK, DECODE, "DV7回退HDR10", "作用:MPV 自动输出使用 GPU 路径时,允许 Dolby Vision Profile 7 使用 HDR10 基底层播放,默认开启。关闭后会优先尝试原生 DV7 电视直出,适配能力声明不完整但实际可解码的设备;若设备确实不支持,可能黑屏或播放失败,MPV 字幕、LUT 和 GPU 滤镜也可能不可用。")); + options.add(option(DV7_HDR10_FALLBACK, DECODE, "DV7处理", "作用:设备能原生播放 Dolby Vision Profile 7 时始终保留原始 DV7;否则默认尝试“升级P8.1”保留动态元数据,也可选择直接“降级HDR10”。设备不支持P8.1或转换/解码失败时会自动回退HDR10。P8.1逐帧重写RPU,会比HDR10过滤增加少量CPU处理。")); options.add(option(AUDIO_PASSTHROUGH, AUDIO, "音频直通", "怎么选:电视/功放明确支持Dolby、DTS且需要多声道时开启;出现无声、杂音或同步异常立即关闭。代价:压缩音频交给外部设备后,MPV无法完成所有混音和重采样处理。")); options.add(option(PREFER_AAC, AUDIO, "AAC 优先", "怎么选:高级音轨无声或设备兼容性差时开启;功放支持原始多声道、希望保留最佳音轨时关闭。代价:可能从Dolby/DTS切到质量或声道较低的AAC。")); } diff --git a/app/src/main/java/com/fongmi/android/tv/setting/PlaybackPerformanceSetting.java b/app/src/main/java/com/fongmi/android/tv/setting/PlaybackPerformanceSetting.java index f4adabfc4c..38a4097159 100644 --- a/app/src/main/java/com/fongmi/android/tv/setting/PlaybackPerformanceSetting.java +++ b/app/src/main/java/com/fongmi/android/tv/setting/PlaybackPerformanceSetting.java @@ -55,6 +55,7 @@ public class PlaybackPerformanceSetting { private static final String KEY_DECODER_FALLBACK = "perf_decoder_fallback"; private static final String KEY_DV7_HDR10_FALLBACK_LEGACY = "perf_dv7_hdr10_fallback"; + private static final String KEY_MPV_DV7_HANDLING = "perf_mpv_dv7_handling"; private static final String KEY_DV7_HANDLING = "perf_dv7_handling"; private static final String KEY_DEFERRED_CUES = "perf_deferred_cues"; private static final String KEY_SOFT_VIDEO_TUNE = "perf_soft_video_tune"; @@ -118,6 +119,7 @@ public class PlaybackPerformanceSetting { Prefers.put("exo_4k_compat", true); } else if (kernel == PlayerSetting.MPV) { MpvPerformanceSetting.applyRecommended(); + put(KEY_MPV_DV7_HANDLING, DV7_HANDLING_P81); } else { IjkPerformanceSetting.applyRecommended(); } @@ -133,6 +135,7 @@ public class PlaybackPerformanceSetting { Prefers.put("exo_4k_compat", true); } else if (kernel == PlayerSetting.MPV) { MpvPerformanceSetting.applyAuto(); + put(KEY_MPV_DV7_HANDLING, DV7_HANDLING_P81); } else { IjkPerformanceSetting.applyRecommended(); } @@ -167,6 +170,7 @@ public class PlaybackPerformanceSetting { Prefers.put("exo_4k_compat", true); } else if (kernel == PlayerSetting.MPV) { MpvPerformanceSetting.applyLightweight(); + put(KEY_MPV_DV7_HANDLING, DV7_HANDLING_P81); } else { IjkPerformanceSetting.applyLightweight(); } @@ -206,10 +210,14 @@ public class PlaybackPerformanceSetting { } public static String getProfileName() { - int profile = getProfile(); + return getProfileName(PlayerSetting.getPlayer()); + } + + public static String getProfileName(int kernel) { + int profile = getProfile(kernel); return switch (profile) { case PROFILE_AUTO -> { - int count = getOverrideCount(PlayerSetting.getPlayer()); + int count = getOverrideCount(kernel); yield count == 0 ? "自动" : "自动(已覆盖" + count + "项)"; } case PROFILE_COMPATIBLE, @@ -386,15 +394,14 @@ public class PlaybackPerformanceSetting { public static boolean isDv7Hdr10FallbackEnabled() { ensureInitialized(); if (PlayerSetting.getPlayer() == PlayerSetting.MPV) { - return Prefers.getBoolean(KEY_DV7_HDR10_FALLBACK_LEGACY, true); + return getMpvDv7HandlingMode() == DV7_HANDLING_HDR10; } return getDv7HandlingMode() == DV7_HANDLING_HDR10; } public static void putDv7Hdr10FallbackEnabled(boolean value) { if (PlayerSetting.getPlayer() == PlayerSetting.MPV) { - putCustom(KEY_DV7_HDR10_FALLBACK_LEGACY, value, - PlaybackPerformanceCatalog.DV7_HDR10_FALLBACK); + putMpvDv7HandlingMode(value ? DV7_HANDLING_HDR10 : DV7_HANDLING_P81); } else { putDv7HandlingMode(value ? DV7_HANDLING_HDR10 : DV7_HANDLING_P81); } @@ -434,6 +441,32 @@ public class PlaybackPerformanceSetting { putCustom(KEY_DV7_HANDLING, clampDv7Handling(mode), PlaybackPerformanceCatalog.DV7_HDR10_FALLBACK); } + public static int getMpvDv7HandlingMode() { + ensureInitialized(); + if (Prefers.getPrefers().contains(KEY_MPV_DV7_HANDLING)) + return clampDv7Handling(Prefers.getInt(KEY_MPV_DV7_HANDLING, DV7_HANDLING_P81)); + if (Prefers.getPrefers().contains(KEY_DV7_HDR10_FALLBACK_LEGACY)) { + return Prefers.getBoolean(KEY_DV7_HDR10_FALLBACK_LEGACY, true) + ? DV7_HANDLING_HDR10 : DV7_HANDLING_P81; + } + return DV7_HANDLING_P81; + } + + public static void putMpvDv7HandlingMode(int mode) { + putCustom(KEY_MPV_DV7_HANDLING, clampDv7Handling(mode), + PlaybackPerformanceCatalog.DV7_HDR10_FALLBACK); + } + + public static String getMpvDv7HandlingText() { + return getMpvDv7HandlingMode() == DV7_HANDLING_P81 + ? "升级P8.1" : "降级HDR10"; + } + + public static String getMpvDv7HandlingOption() { + return getMpvDv7HandlingMode() == DV7_HANDLING_P81 + ? "p81" : "hdr10"; + } + public static boolean isSoftVideoTuneEnabled() { ensureInitialized(); return Prefers.getBoolean(KEY_SOFT_VIDEO_TUNE, true); diff --git a/app/src/main/java/com/fongmi/android/tv/setting/PlayerSetting.java b/app/src/main/java/com/fongmi/android/tv/setting/PlayerSetting.java index 7bd606c086..ebb4dc4d58 100644 --- a/app/src/main/java/com/fongmi/android/tv/setting/PlayerSetting.java +++ b/app/src/main/java/com/fongmi/android/tv/setting/PlayerSetting.java @@ -81,6 +81,12 @@ public class PlayerSetting { private static final String KEY_OSD_MINI = "player_osd_mini"; private static boolean legacyOsdMigrated; private static boolean legacyBrightnessMigrated; + /** + * 当前播放会话正在使用的内核(NONE 表示没有会话,按全局默认)。 + * 只存在于内存:进程内所有「现在用的是哪个内核」的判断都读它,退出播放后清空。 + * 由 PlayerManager 在建引擎/切引擎时写入,volatile 以便工作线程(取播放地址)读到最新值。 + */ + private static volatile int activePlayer = NONE; public static int getPlayer() { int player = Prefers.getInt("player", EXO); @@ -93,6 +99,25 @@ public class PlayerSetting { Prefers.put("player", sanitizePlayer(player)); } + /** + * 当前实际在跑的内核,与全局默认内核解耦。 + * 播放器里切内核只影响本次播放(并由 History 按剧集记住),不再回写全局默认, + * 因此运行期凡是问「现在用的是哪个内核」的地方都要读这里,而不是 getPlayer(); + * getPlayer() 只代表设置页里的全局默认值,也是没有播放会话时的兜底。 + */ + public static int getActivePlayer() { + int player = activePlayer; + return isPlayer(player) ? player : getPlayer(); + } + + public static void putActivePlayer(int player) { + activePlayer = isPlayer(player) ? player : NONE; + } + + public static void clearActivePlayer() { + activePlayer = NONE; + } + public static boolean isImmersiveAudioMode() { return Prefers.getBoolean("immersive_audio_mode", true); } diff --git a/app/src/main/java/com/fongmi/android/tv/ui/activity/PlaybackActivity.java b/app/src/main/java/com/fongmi/android/tv/ui/activity/PlaybackActivity.java index 3362f67631..f9ef3a89e3 100644 --- a/app/src/main/java/com/fongmi/android/tv/ui/activity/PlaybackActivity.java +++ b/app/src/main/java/com/fongmi/android/tv/ui/activity/PlaybackActivity.java @@ -60,6 +60,7 @@ import java.util.function.IntConsumer; public abstract class PlaybackActivity extends BaseActivity implements MediaController.Listener, Player.Listener, ServiceConnection { private static final String SIZE_TAG = "MPV_SIZE"; + private static final String STATE_PLAYBACK_KEY = "playback:ownershipKey"; private ListenableFuture mControllerFuture; private MediaController mController; @@ -68,6 +69,7 @@ public abstract class PlaybackActivity extends BaseActivity implements MediaCont private boolean redirect; private boolean playbackExiting; private String preparedPlaybackKey; + private String pinnedPlaybackKey; private boolean nativeOutputPending; private boolean bound; private boolean stop; @@ -123,7 +125,7 @@ public abstract class PlaybackActivity extends BaseActivity implements MediaCont this.redirect = redirect; if (mService == null) return; if (redirect) mService.clearNavigationCallback(getNavigationCallback()); - else mService.setNavigationCallback(getNavigationCallback(), getPlaybackKey()); + else mService.setNavigationCallback(getNavigationCallback(), activePlaybackKey()); } protected boolean isPlaybackExiting() { @@ -149,7 +151,7 @@ public abstract class PlaybackActivity extends BaseActivity implements MediaCont } protected void updateNavigationKey() { - if (mService != null) mService.setNavigationCallback(getNavigationCallback(), getPlaybackKey()); + if (mService != null) mService.setNavigationCallback(getNavigationCallback(), activePlaybackKey()); } protected boolean isAudioOnly() { @@ -188,8 +190,32 @@ public abstract class PlaybackActivity extends BaseActivity implements MediaCont return false; } + /** + * 本次播放会话的归属令牌。 + * + *

{@link #getPlaybackKey()} 由子类从 intent 现算,而 intent 的 id 会在起播之后被 + * 详情结果改写(TMDB 富集回来的 vodId,见 VideoActivity#updateVod)。播放器里的 key 是 + * 起播那一刻固化进 PlaySpec 的,之后无从更改;两者一旦不等,{@link #isOwner()} 便永久 + * 为 false,于是 STATE_READY 不再下发(转圈不收)、每秒的进度采样直接返回(进度不落库、 + * 刷新回起点)、切集也因 PlaybackService#isNavigationOwner 失配而不派发。 + * + *

该 key 的语义是"归属与路由令牌",必须在一次播放会话内保持稳定;History 行的 key + * 迁移是另一件事,二者解耦。因此起播时钉住,会话结束或换集重新起播时再更新。 + */ + protected final String activePlaybackKey() { + return pinnedPlaybackKey != null ? pinnedPlaybackKey : getPlaybackKey(); + } + + /** + * 丢弃上一次播放会话的归属令牌,让 {@link #activePlaybackKey()} 重新回落到 intent。 + * 换条目(onNewIntent)时调用:此时旧会话已作废,新会话尚未起播。 + */ + protected final void resetPlaybackOwnership() { + pinnedPlaybackKey = null; + } + protected boolean isOwner() { - String key = getPlaybackKey(); + String key = activePlaybackKey(); PlayerManager manager = player(); return key == null || (manager != null && key.equals(manager.getKey())); } @@ -400,10 +426,12 @@ public abstract class PlaybackActivity extends BaseActivity implements MediaCont onError(ResUtil.getString(R.string.error_play_url)); } else if (result.needParse() || useParse) { preparedPlaybackKey = null; + pinnedPlaybackKey = key; attachSurface(); player().parse(key, result, useParse, metadata, PlayerSetting.isAutoPlay(), startPositionMs); } else { preparedPlaybackKey = null; + pinnedPlaybackKey = key; attachSurface(); player().start(PlaySpec.from(result, key, metadata), timeout, PlayerSetting.isAutoPlay(), startPositionMs); } @@ -427,7 +455,7 @@ public abstract class PlaybackActivity extends BaseActivity implements MediaCont } private boolean isSelectedMpvPlayer() { - return mService != null ? player().isMpv() : PlayerSetting.getPlayer() == PlayerSetting.MPV; + return mService != null ? player().isMpv() : PlayerSetting.getActivePlayer() == PlayerSetting.MPV; } private void bindPlaybackService() { @@ -489,7 +517,7 @@ public abstract class PlaybackActivity extends BaseActivity implements MediaCont MediaItem controllerItem = mController.getCurrentMediaItem(); String managerMediaId = managerItem == null ? null : managerItem.mediaId; String controllerMediaId = controllerItem == null ? null : controllerItem.mediaId; - if (!PlaybackStateReconciliation.shouldReplayReady(getPlaybackKey(), preparedPlaybackKey, manager.getKey(), managerMediaId, controllerMediaId, manager.getPlaybackState(), mController.getPlaybackState())) return; + if (!PlaybackStateReconciliation.shouldReplayReady(activePlaybackKey(), preparedPlaybackKey, manager.getKey(), managerMediaId, controllerMediaId, manager.getPlaybackState(), mController.getPlaybackState())) return; onControllerReadyReconciled(); } @@ -875,6 +903,7 @@ public abstract class PlaybackActivity extends BaseActivity implements MediaCont protected void initView(Bundle savedInstanceState) { long start = System.currentTimeMillis(); super.initView(savedInstanceState); + restorePlaybackKey(savedInstanceState); if (!shouldBindPlaybackService()) return; ExoUtil.setPlayerView(getExoView()); RealtimeSubtitleController.get().bind(getExoView()); @@ -884,6 +913,20 @@ public abstract class PlaybackActivity extends BaseActivity implements MediaCont if (SpiderDebug.isEnabled()) SpiderDebug.log("playback-flow", "initView cost=%dms key=%s deferred=%s", System.currentTimeMillis() - start, getPlaybackKey(), deferPlaybackServiceBinding()); } + private void restorePlaybackKey(Bundle savedInstanceState) { + if (savedInstanceState == null) return; + String key = savedInstanceState.getString(STATE_PLAYBACK_KEY); + if (key != null) pinnedPlaybackKey = key; + } + + @Override + protected void onSaveInstanceState(@NonNull Bundle outState) { + super.onSaveInstanceState(outState); + if (!playbackExiting && pinnedPlaybackKey != null) { + outState.putString(STATE_PLAYBACK_KEY, pinnedPlaybackKey); + } + } + @Override public void onIsPlayingChanged(boolean isPlaying) { syncKeepScreenOn(); @@ -1029,7 +1072,7 @@ public void onPlayWhenReadyChanged(boolean playWhenReady, int reason) { mService.replaceBinding(this::closePiP); mService.setSessionActivity(buildSessionIntent()); mService.setPlaybackForeground(true); - mService.setNavigationCallback(getNavigationCallback(), getPlaybackKey()); + mService.setNavigationCallback(getNavigationCallback(), activePlaybackKey()); mService.addPlayerCallback(mPlayerCallback); getSeekView().setProgressPlayer(player().getPlayer()); player().setLutAllowed(isLutAllowed()); diff --git a/app/src/main/java/com/fongmi/android/tv/ui/activity/TmdbDetailActivity.java b/app/src/main/java/com/fongmi/android/tv/ui/activity/TmdbDetailActivity.java index d4003b8551..ede1c9e983 100644 --- a/app/src/main/java/com/fongmi/android/tv/ui/activity/TmdbDetailActivity.java +++ b/app/src/main/java/com/fongmi/android/tv/ui/activity/TmdbDetailActivity.java @@ -677,6 +677,7 @@ public class TmdbDetailActivity extends PlaybackActivity implements TrackDialog. protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); + resetPlaybackOwnership(); brokenSources.clear(); resetDetailState(); loadContent(null); @@ -6865,12 +6866,13 @@ public class TmdbDetailActivity extends PlaybackActivity implements TrackDialog. String key = getKeyText(); String flag = selectedFlag.getFlag(); String episodeUrl = selectedEpisode.getUrl(); + int playerKernel = inlineHistoryPlayerKernel(); stopInlinePlayerForReload(); showInlineLoading(); updateInlineDisplayPanel(); detailTasks.submit(() -> { try { - Result result = SiteApi.playerContent(key, flag, episodeUrl); + Result result = SiteApi.playerContent(key, flag, episodeUrl, playerKernel); runOnAliveUi(() -> { if (!isInlinePlaybackRequestCurrent(generation, key, flag, episodeUrl)) return; String resolvedUrl = result.getUrl() == null ? "" : result.getUrl().v(); @@ -6959,8 +6961,7 @@ public class TmdbDetailActivity extends PlaybackActivity implements TrackDialog. if (resumePosition == C.TIME_UNSET) resetInlineHistoryIfNearEnding(); inlineStartPosition = resumePosition == C.TIME_UNSET ? getInlineResumePosition() : Math.max(0, resumePosition); inlineStartPositionApplied = false; - player().switchPlayer(PlayerSetting.getPlayer()); - updateInlineHistoryPlayer(); + player().preparePlayer(inlineHistoryPlayerKernel()); setInlineSpeed(getInlinePlaybackSpeed()); updateInlineButtons(false); Site site = getCurrentSite(); @@ -7926,10 +7927,9 @@ public class TmdbDetailActivity extends PlaybackActivity implements TrackDialog. private String getInlineOsdTitle() { if (selectedEpisode == null) return ""; String name = playbackHistoryName(); - String episode = selectedEpisode.getName(); - String title = TextUtils.isEmpty(episode) ? name : name + " " + episode; - String progress = tmdbEpisodeInfo().compactText(this); - return TextUtils.isEmpty(progress) ? title : title + " · " + progress; + String episodeTitle = historyEpisodeTitle(selectedEpisode); + return TextUtils.isEmpty(episodeTitle) || TextUtils.equals(name, episodeTitle) + ? name : getString(R.string.detail_title, name, episodeTitle); } private void onInlineLut() { @@ -8240,7 +8240,8 @@ public class TmdbDetailActivity extends PlaybackActivity implements TrackDialog. inlineHttpRefreshAttempted = false; useParse = result.shouldUseParse(); inlinePlayerSwitchLoading = false; - player().switchPlayer(playerType, result, getHistoryKey(), metadata, useParse, position, speed, repeat); + player().switchPlayer(playerType, result, activePlaybackKey(), metadata, useParse, position, speed, repeat); + rememberInlinePlayerKernel(playerType); } finishInlinePlayerSwitch(); }); @@ -8280,7 +8281,6 @@ public class TmdbDetailActivity extends PlaybackActivity implements TrackDialog. } private void finishInlinePlayerSwitch() { - updateInlineHistoryPlayer(); syncInlineHistory(); binding.playerExternal.setText(player().getPlayerText()); setInlineDecodeText(inlineDecodeText(true)); @@ -9401,6 +9401,9 @@ public class TmdbDetailActivity extends PlaybackActivity implements TrackDialog. binding.playerPanel.requestFocus(); Util.toggleFullscreen(this, true); setInlineFullscreenOrientation(); + // 手动点全屏按钮不走 applyInlineShortDramaMode(那条只在 STATE_READY 触发), + // 这里也要按新形态重算手势,否则短剧进全屏后仍是长视频那套轴向。 + syncInlineShortDramaGesture(); scheduleMobileInlineSideControlMarginUpdate(); } @@ -9422,15 +9425,30 @@ public class TmdbDetailActivity extends PlaybackActivity implements TrackDialog. return; } inlineShortDramaMode = true; + syncInlineShortDramaGesture(); setInlineFullscreenOrientation(); setInlineShortDramaVideoFrame(!shouldUseShortDramaPortrait()); setInlinePreviewScale(SHORT_DRAMA_SCALE); hideInlineControls(); } + /** + * 手势轴向跟着呈现形态走:短剧内嵌全屏时整屏上下滑切集、长按后上下滑调亮度/音量。 + *

+ * 判据不用 {@code inlineShortDramaMode}:切集时 startInlinePlayback 会先 + * resetInlineShortDramaMode 再等 STATE_READY 重新 apply,那段缓冲窗口里形态并没变, + * 手势却会退回长视频那套,连滑两集时第二次落在侧边就被当成调亮度。 + * shouldUseInlineShortDramaMode 在尺寸未知时返回 true,正好覆盖这段窗口; + * 横屏短剧不走竖屏铺满形态,也就不换手势。 + */ + private void syncInlineShortDramaGesture() { + if (inlineGestureDetector != null) inlineGestureDetector.setShortDrama(inlineFullscreen && shouldUseInlineShortDramaMode()); + } + private void resetInlineShortDramaMode() { boolean restoreScale = inlineShortDramaMode; inlineShortDramaMode = false; + syncInlineShortDramaGesture(); setInlineShortDramaVideoFrame(false); if (restoreScale && inlineStarted) setInlineScale(getInlineScale()); } @@ -10594,10 +10612,7 @@ public class TmdbDetailActivity extends PlaybackActivity implements TrackDialog. } private void updateInlineHistoryProgress() { - if (history == null || service() == null || player() == null || player().isReleased() || !isOwner()) { - updateInlineHistoryPlayer(); - return; - } + if (history == null || service() == null || player() == null || player().isReleased() || !isOwner()) return; updateInlineHistoryProgress(System.currentTimeMillis(), player().getPosition(), player().getDuration()); } @@ -10606,11 +10621,22 @@ public class TmdbDetailActivity extends PlaybackActivity implements TrackDialog. history.setCreateTime(time); if (position > 0) history.setPosition(position); if (duration > 0) history.setDuration(duration); - updateInlineHistoryPlayer(); } - private void updateInlineHistoryPlayer() { - if (history != null && service() != null && player() != null && !player().isReleased()) history.setPlayer(player().getPlayerType()); + /** + * 用户显式换内核后记住选定值。 + * 记的是用户选的值而不是引擎状态:引擎会被播放失败后的自动回退改掉, + * 那不代表用户改了选择;例行的进度同步也一律不碰这个字段, + * 否则上一部剧遗留的会话内核会覆盖本剧记住的选择。 + */ + private void rememberInlinePlayerKernel(int type) { + if (history == null || !PlayerSetting.isPlayer(type)) return; + history.setPlayer(type); + } + + /** 本剧记住的内核;没有记录时退回设置页的全局默认。 */ + private int inlineHistoryPlayerKernel() { + return history == null ? PlayerSetting.getPlayer() : history.getPlayerOrDefault(); } private void requestIntroSkipPlan() { @@ -10660,7 +10686,6 @@ public class TmdbDetailActivity extends PlaybackActivity implements TrackDialog. updateInlineHistoryProgress(time, position, duration); } else { history.setCreateTime(time); - updateInlineHistoryPlayer(); } if (canUpdateProgress) PlaybackEventCollector.get().onProgress(history, player()); if (canUpdateProgress && history.canSave() && history.canSync()) syncInlineHistory(); diff --git a/app/src/main/java/com/fongmi/android/tv/ui/adapter/TmdbEpisodeAdapter.java b/app/src/main/java/com/fongmi/android/tv/ui/adapter/TmdbEpisodeAdapter.java index a53d97273e..96416959d8 100644 --- a/app/src/main/java/com/fongmi/android/tv/ui/adapter/TmdbEpisodeAdapter.java +++ b/app/src/main/java/com/fongmi/android/tv/ui/adapter/TmdbEpisodeAdapter.java @@ -58,6 +58,7 @@ public class TmdbEpisodeAdapter extends RecyclerView.Adapter 0) return height; ViewGroup.LayoutParams params = holder.binding.getRoot().getLayoutParams(); if (params != null && params.height > 0) return params.height; - if (isNativeEnhanced()) return ResUtil.dp2px(mode == Mode.GRID ? nativeEnhancedGridCardHeight(holder.itemView) : 160); + if (isNativeEnhanced()) { + int gridHeight = pageHasTmdbEpisodeData + ? nativeEnhancedGridCardHeight(holder.itemView) + : TmdbEpisodeGridPolicy.GRID_CARD_HEIGHT_DP; + return ResUtil.dp2px(mode == Mode.GRID ? gridHeight : 160); + } return ResUtil.dp2px(mode == Mode.GRID ? TmdbEpisodeGridPolicy.GRID_CARD_HEIGHT_DP : (isPhoneWidth(holder.itemView) ? 172 : 190)); } + private boolean hasPageTmdbEpisodeData() { + for (int position = 0; position < items.size(); position++) { + Episode episode = items.get(position); + if (episode == null) continue; + int number = episodeNumber(episode, position); + TmdbEpisode tmdbEpisode = tmdbItems.get(number); + if (TmdbEpisodeMatcher.shouldApply(episode, tmdbEpisode, number)) return true; + } + return false; + } + private boolean shouldSuppressSharedFallbackVisuals() { return false; } diff --git a/app/src/main/java/com/fongmi/android/tv/ui/custom/FocusRestorer.java b/app/src/main/java/com/fongmi/android/tv/ui/custom/FocusRestorer.java new file mode 100644 index 0000000000..93239a2738 --- /dev/null +++ b/app/src/main/java/com/fongmi/android/tv/ui/custom/FocusRestorer.java @@ -0,0 +1,66 @@ +package com.fongmi.android.tv.ui.custom; + +import androidx.core.view.OneShotPreDrawListener; +import androidx.recyclerview.widget.RecyclerView; + +/** + * 条目被移除后把 D-pad 焦点交回列表。 + * RecyclerView 自身的焦点恢复救不了这种场景:移除 scrap 时已经先 clearFocus(), + * 焦点被窗口兜底给了布局里第一个可聚焦控件(历史页是右上角的删除按钮), + * 等到 recoverFocusFromState() 时 hasFocus() 已为 false 直接返回; + * 适配器也没有 stable id,基于 id 的恢复路径同样是死的。 + */ +public final class FocusRestorer { + + private OneShotPreDrawListener pending; + private int generation; + + /** + * 网格中移除 position 后焦点应落到哪一项。 + * 原位仍有条目就留在原位(后面的条目补位);原位已越界说明删的是末位, + * 此时同行还有条目就退到新末位,整行被删空则上移一行保持同列。 + */ + public static int nextPosition(int position, int count, int spanCount) { + if (position < 0 || count <= 0) return RecyclerView.NO_POSITION; + if (position < count) return position; + int span = Math.max(1, spanCount); + int last = count - 1; + if (last / span == position / span) return last; + return Math.min(last, Math.max(0, position - span)); + } + + public void restore(RecyclerView recycler, int position) { + cancel(); + if (recycler == null || position < 0) return; + schedule(recycler, position, generation, true); + } + + /** 取消排队中的恢复,包含已经进入滚动重试阶段的那一次。 */ + public void cancel() { + generation++; + if (pending != null) pending.removeListener(); + pending = null; + } + + private void schedule(RecyclerView recycler, int position, int scheduled, boolean retry) { + pending = OneShotPreDrawListener.add(recycler, () -> { + if (scheduled != generation) return; + pending = null; + if (!recycler.isShown()) return; + if (focus(recycler, position)) return; + if (!retry) { + recycler.requestFocus(); + return; + } + // 目标行尚未 layout(列表已滚动过)时先滚过去;scrollToPosition 只是 requestLayout, + // 必须再等一次 pre-draw 才能拿到 holder,用 post 会跑在这次 layout 之前 + recycler.scrollToPosition(position); + schedule(recycler, position, scheduled, false); + }); + } + + private static boolean focus(RecyclerView recycler, int position) { + RecyclerView.ViewHolder holder = recycler.findViewHolderForAdapterPosition(position); + return holder != null && holder.itemView.requestFocus(); + } +} diff --git a/app/src/main/java/com/fongmi/android/tv/ui/custom/PlayerGesture.java b/app/src/main/java/com/fongmi/android/tv/ui/custom/PlayerGesture.java index fe473d82a7..6d0b8f89a0 100644 --- a/app/src/main/java/com/fongmi/android/tv/ui/custom/PlayerGesture.java +++ b/app/src/main/java/com/fongmi/android/tv/ui/custom/PlayerGesture.java @@ -35,9 +35,13 @@ public class PlayerGesture extends GestureDetector.SimpleOnGestureListener imple private boolean changeTime; private boolean multiTouch; private boolean animating; + private boolean shortDrama; private boolean touch; private boolean lock; private float bright; + private float anchorY = Float.NaN; + private float downX; + private float downY; private float volume; private float scale; private long time; @@ -59,12 +63,49 @@ public class PlayerGesture extends GestureDetector.SimpleOnGestureListener imple public boolean onTouchEvent(MotionEvent e) { int action = e.getActionMasked(); + boolean end = action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL; if (action == MotionEvent.ACTION_DOWN) multiTouch = false; + // 起点在这里记而不是 onDown:onDown 在边缘/缩放/锁定时会提前返回, + // 而 changeScale 会在 onScaleEnd 之后 500ms 才解除,那段窗口里按下的手势 + // 拿不到自己的起点,长按转调节时会拿上一次的起点算位移,一按就跳。 + if (action == MotionEvent.ACTION_DOWN) { + downX = e.getX(); + downY = e.getY(); + } if (action == MotionEvent.ACTION_POINTER_DOWN) multiTouch = true; - if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) listener.onTouchEnd(); - if (changeSpeed && action == MotionEvent.ACTION_UP) listener.onSpeedEnd(); + if (end) listener.onTouchEnd(); + // 短剧的亮度/音量在长按之后才生效,此时 GestureDetector 已不再回调 onScroll, + // 只能在这里自行处理移动事件,详见 handleAdjust。用实时指数判断而不是 multiTouch: + // 后者在 ACTION_POINTER_UP 时不会复位,会把抬起一根手指后的单指调节一起挡掉。 + if (shortDrama && action == MotionEvent.ACTION_MOVE && e.getPointerCount() == 1 && !lock && !changeScale) handleAdjust(e); + // 被父容器拦截或来电时只收到 CANCEL:倍速同样要交还,否则会卡在长按后的速率。 + if (changeSpeed && end) listener.onSpeedEnd(); + // seek 只在正常抬手时提交:CANCEL 属于手势被打断,维持原位置更符合预期。 if (changeTime && action == MotionEvent.ACTION_UP) listener.onSeekEnd(time); - return e.getPointerCount() == 2 ? scaleDetector.onTouchEvent(e) : detector.onTouchEvent(e); + boolean handled = e.getPointerCount() == 2 ? scaleDetector.onTouchEvent(e) : detector.onTouchEvent(e); + // 必须等 detector 处理完再清:onFling 是 detector 在 UP 时回调的,它要读 + // changeSpeed/changeBright/changeVolume 才能判断这次抬手是否该切集。 + if (end) clearGesture(); + return handled; + } + + /** + * 一次手势结束就把功能标记清干净。 + *

+ * {@link #reset()} 挂在 onDown 上,而 onDown 在边缘/缩放/锁定时会提前返回, + * 于是上一次手势的 changeBright/anchorY 可能活到下一次手势——短剧的亮度/音量 + * 由 onTouchEvent 直接驱动,不再有 onScroll 的兜底,残留状态会直接造成 + * 「没长按就跳亮度」。所以收尾统一在这里做,不依赖下一次 onDown 是否被接受。 + */ + private void clearGesture() { + changeTime = false; + changeSpeed = false; + changeBright = false; + changeVolume = false; + anchorY = Float.NaN; + // 不动 touch:它表示「本次手势还没选定功能」,是就绪态而非残留动作。 + // 在这里清成 false 会让缩放后 500ms 内(changeScale 还没解除时)起手的那一次 + // 拖动选不到任何功能,白滑一次。它由 reset() 置真、checkFunc 置假,无需插手。 } public void resetScale() { @@ -80,6 +121,17 @@ public class PlayerGesture extends GestureDetector.SimpleOnGestureListener imple this.lock = lock; } + /** + * 短剧竖屏形态下换用另一套手势轴向,参考红果短剧、抖音等主流竖屏播放器: + * 上下滑切上下集(全屏可用),亮度/音量改为长按后再上下滑,左半亮度右半音量。 + *

+ * 原来「中间竖滑切集 + 左右 1/4 竖滑调亮度音量」在铺满屏幕的竖屏短剧里极易误触 + * (用户反馈):想切集却滑到了边缘,调亮度又常常切了集。 + */ + public void setShortDrama(boolean shortDrama) { + this.shortDrama = shortDrama; + } + private boolean isMultiple(MotionEvent e) { return e.getPointerCount() > 1; } @@ -125,6 +177,7 @@ public class PlayerGesture extends GestureDetector.SimpleOnGestureListener imple private void reset() { time = 0; touch = true; + anchorY = Float.NaN; changeTime = false; changeSpeed = false; changeBright = false; @@ -159,6 +212,41 @@ public class PlayerGesture extends GestureDetector.SimpleOnGestureListener imple return true; } + /** + * 短剧的「长按后上下滑调亮度/音量」。 + *

+ * 不能挂在 {@link #onScroll} 上:GestureDetector 触发长按后会把后续 ACTION_MOVE + * 全部吞掉(mInLongPress 分支直接 break),onScroll 再也不会回调,所以这条手势 + * 必须由 onTouchEvent 自己驱动。 + */ + private void handleAdjust(MotionEvent e) { + // 只认「本次手势自己长按出来」的调节,避免上一次手势的残留标记把亮度带跑。 + if (!changeSpeed && Float.isNaN(anchorY)) return; + if (changeSpeed) { + float dx = e.getX() - downX; + float dy = e.getY() - downY; + if (Math.abs(dy) <= Math.abs(dx) || Math.abs(dy) < ResUtil.dp2px(20)) return; + startAdjust(e); + } + // 以「长按转调节」的那一刻为基准,避免把长按期间的位移一次性算进亮度/音量。 + float deltaY = anchorY - e.getY(); + if (changeBright) setBright(deltaY); + if (changeVolume) setVolume(deltaY); + } + + /** + * 长按倍速中途转为亮度/音量调节:先把倍速交还,再以当前触点为新基准。 + */ + private void startAdjust(MotionEvent e) { + listener.onSpeedEnd(); + changeSpeed = false; + touch = false; + anchorY = e.getY(); + bright = Util.getBrightness(activity); + volume = manager.getStreamVolume(AudioManager.STREAM_MUSIC); + checkSide(e); + } + @Override public boolean onDoubleTap(@NonNull MotionEvent e) { if (isMultiple(e) || isEdge(e) || changeScale) return true; @@ -175,15 +263,21 @@ public class PlayerGesture extends GestureDetector.SimpleOnGestureListener imple @Override public boolean onFling(MotionEvent e1, @NonNull MotionEvent e2, float velocityX, float velocityY) { - if (isMultiple(e1) || isEdge(e1) || isSide(e1) || changeScale || lock || animating) return true; + // 短剧上下滑切集不再受左右 1/4 的亮度/音量分区限制(那两块已改为长按触发), + // 但 isEdge 的 24dp 边框仍然保留:那里要让给系统的返回/通知栏手势。 + if (isMultiple(e1) || isEdge(e1) || (!shortDrama && isSide(e1)) || changeScale || lock || animating) return true; + // 这次手势已经用于调亮度/音量或倍速,抬手不应再被当成切集。 + if (changeSpeed || changeBright || changeVolume) return true; checkFunc(e1, e2); return true; } private void checkFunc(float distanceX, float distanceY, MotionEvent e2) { if ((float) Math.sqrt(distanceX * distanceX + distanceY * distanceY) < ResUtil.dp2px(20)) return; + // 短剧的上下滑整屏留给切集(onFling),亮度/音量改由 startAdjust(长按后再滑)接管, + // 所以这里只保留横滑拖进度,不再按左右 1/4 分派亮度/音量。 if (distanceX >= distanceY) changeTime = true; - else if (isSide(e2)) checkSide(e2); + else if (!shortDrama && isSide(e2)) checkSide(e2); touch = false; } @@ -191,10 +285,13 @@ public class PlayerGesture extends GestureDetector.SimpleOnGestureListener imple float dx = e2.getX() - e1.getX(); float dy = e2.getY() - e1.getY(); double angle = Math.toDegrees(Math.atan2(Math.abs(dy), Math.abs(dx))); + // 短剧的切集动画沿用同一套竖向回弹,但不跟随直播的「反转」开关: + // 竖屏短剧里上滑=下一集是抖音/红果的既定语义,反转会让用户完全迷失。 + boolean invert = !shortDrama && LiveSetting.isInvert(); if (angle > 70 && e1.getY() - e2.getY() > DISTANCE) { - videoView.animate().translationYBy(ResUtil.dp2px(LiveSetting.isInvert() ? 24 : -24)).setDuration(150).withStartAction(() -> animating = true).withEndAction(() -> videoView.animate().translationY(0).setDuration(100).withStartAction(listener::onFlingUp).withEndAction(() -> animating = false).start()).start(); + videoView.animate().translationYBy(ResUtil.dp2px(invert ? 24 : -24)).setDuration(150).withStartAction(() -> animating = true).withEndAction(() -> videoView.animate().translationY(0).setDuration(100).withStartAction(listener::onFlingUp).withEndAction(() -> animating = false).start()).start(); } else if (angle > 70 && e2.getY() - e1.getY() > DISTANCE) { - videoView.animate().translationYBy(ResUtil.dp2px(LiveSetting.isInvert() ? -24 : 24)).setDuration(150).withStartAction(() -> animating = true).withEndAction(() -> videoView.animate().translationY(0).setDuration(100).withStartAction(listener::onFlingDown).withEndAction(() -> animating = false).start()).start(); + videoView.animate().translationYBy(ResUtil.dp2px(invert ? -24 : 24)).setDuration(150).withStartAction(() -> animating = true).withEndAction(() -> videoView.animate().translationY(0).setDuration(100).withStartAction(listener::onFlingDown).withEndAction(() -> animating = false).start()).start(); } } @@ -217,6 +314,7 @@ public class PlayerGesture extends GestureDetector.SimpleOnGestureListener imple private void setVolume(float deltaY) { int height = Math.max(videoView.getMeasuredHeight(), 1); int maxVolume = manager.getStreamMaxVolume(AudioManager.STREAM_MUSIC); + if (maxVolume <= 0) return; float deltaV = deltaY * 2.0f / height * maxVolume; float index = volume + deltaV; if (index > maxVolume) index = maxVolume; diff --git a/app/src/main/java/com/fongmi/android/tv/ui/custom/PlayerOsdController.java b/app/src/main/java/com/fongmi/android/tv/ui/custom/PlayerOsdController.java index 0cf66afae9..c870a24943 100644 --- a/app/src/main/java/com/fongmi/android/tv/ui/custom/PlayerOsdController.java +++ b/app/src/main/java/com/fongmi/android/tv/ui/custom/PlayerOsdController.java @@ -438,9 +438,9 @@ public class PlayerOsdController { String audioText = summarizeAudio(audio, audioTrack, snapshot.audioDecoderName()); String render = PlayerSetting.getRender() == PlayerSetting.RENDER_SURFACE ? "Surface" : "Texture"; String tunnel = switchText(PlayerSetting.isTunnelingEnabled()); - String performance = PlaybackPerformanceSetting.getProfileName(); + String performance = PlaybackPerformanceSetting.getProfileName(player.getPlayerType()); String passThrough = player.getAudioPassThroughText(); - String preload = "预载" + switchText(PreloadSetting.isPreload()); + String preload = "预载" + switchText(PreloadSetting.isPreload(player.getPlayerType())); String frameRateMatch = player.isExo() ? "帧率匹配 开" : ""; String softTune = getSoftDecodeTuneText(player); String playerText = join(" / ", player.getPlayerText(), player.getDecodeText(), render, "隧道" + tunnel, "性能" + performance, frameRateMatch, preload, "直通" + passThrough, softTune, player.isExo() ? "兜底开" : ""); diff --git a/app/src/main/java/com/fongmi/android/tv/ui/dialog/PlaybackPerformanceDialog.java b/app/src/main/java/com/fongmi/android/tv/ui/dialog/PlaybackPerformanceDialog.java index 8f8dfe8fd6..ed90b66ef2 100644 --- a/app/src/main/java/com/fongmi/android/tv/ui/dialog/PlaybackPerformanceDialog.java +++ b/app/src/main/java/com/fongmi/android/tv/ui/dialog/PlaybackPerformanceDialog.java @@ -552,7 +552,7 @@ public final class PlaybackPerformanceDialog extends DialogFragment { case PlaybackPerformanceCatalog.DECODER_FALLBACK -> onOff(PlaybackPerformanceSetting.isDecoderFallbackEnabled()); case PlaybackPerformanceCatalog.DV7_HDR10_FALLBACK -> PlayerSetting.getPlayer() == PlayerSetting.MPV - ? onOff(PlaybackPerformanceSetting.isDv7Hdr10FallbackEnabled()) + ? PlaybackPerformanceSetting.getMpvDv7HandlingText() : PlaybackPerformanceSetting.getDv7HandlingText(); case PlaybackPerformanceCatalog.DEFERRED_CUES -> onOff(PlaybackPerformanceSetting.isDeferredCuesEnabled()); case PlaybackPerformanceCatalog.SOFT_VIDEO_TUNE -> onOff(PlaybackPerformanceSetting.isSoftVideoTuneEnabled()); @@ -634,8 +634,12 @@ public final class PlaybackPerformanceDialog extends DialogFragment { case PlaybackPerformanceCatalog.DECODER_FALLBACK -> () -> toggle(PlaybackPerformanceSetting::isDecoderFallbackEnabled, PlaybackPerformanceSetting::putDecoderFallbackEnabled); case PlaybackPerformanceCatalog.DV7_HDR10_FALLBACK -> () -> { if (PlayerSetting.getPlayer() == PlayerSetting.MPV) { - toggle(PlaybackPerformanceSetting::isDv7Hdr10FallbackEnabled, - PlaybackPerformanceSetting::putDv7Hdr10FallbackEnabled); + int mode = PlaybackPerformanceSetting.getMpvDv7HandlingMode(); + PlaybackPerformanceSetting.putMpvDv7HandlingMode( + mode == PlaybackPerformanceSetting.DV7_HANDLING_P81 + ? PlaybackPerformanceSetting.DV7_HANDLING_HDR10 + : PlaybackPerformanceSetting.DV7_HANDLING_P81); + refresh(); return; } int mode = PlaybackPerformanceSetting.getDv7HandlingMode(); diff --git a/app/src/main/java/com/fongmi/android/tv/ui/novel/NovelReaderHost.java b/app/src/main/java/com/fongmi/android/tv/ui/novel/NovelReaderHost.java index 415bff1f21..d53d29e11d 100644 --- a/app/src/main/java/com/fongmi/android/tv/ui/novel/NovelReaderHost.java +++ b/app/src/main/java/com/fongmi/android/tv/ui/novel/NovelReaderHost.java @@ -14,6 +14,9 @@ public interface NovelReaderHost { * 让播放器切换集数并执行解析(相当于点击了某集)。 * * @param chapterUrl 章节 URL(episode.getUrl()) + * @return 是否真的发出了解析请求。宿主只在「当前线路」的集数里按 URL 找章节, + * 而阅读器的章节表是跨线路合并的,点到别条线路的章节时会找不到而静默返回; + * 返回 false 让调用方立刻收尾,不必等在途标记靠时限过期。 */ - void labPlayEpisode(String chapterUrl); + boolean labPlayEpisode(String chapterUrl); } diff --git a/app/src/main/java/com/fongmi/android/tv/ui/novel/NovelRouter.java b/app/src/main/java/com/fongmi/android/tv/ui/novel/NovelRouter.java index 07cab4a3a8..5c8807bd0b 100644 --- a/app/src/main/java/com/fongmi/android/tv/ui/novel/NovelRouter.java +++ b/app/src/main/java/com/fongmi/android/tv/ui/novel/NovelRouter.java @@ -122,11 +122,14 @@ public final class NovelRouter { // 阅读器已在前台 → 回传解析结果,不重复启动(切换章节场景) WebReaderActivity reader = currentReader; if (reader != null && !reader.isFinishing() && !reader.isDestroyed()) { + if (!reader.hasPendingHostChapterRequest() && NovelRouter.consumeStaleChapterResult()) return false; + // 不在这里清表:结清哪一条只有阅读器知道(它持有本次请求的令牌), + // 在这里猜或整表清空都会抹掉另一次仍在途的请求,返回键会重新失效。 reader.onEpisodeResolved(kind, result.getRealUrl(), extractTitle(result.getRealUrl())); return true; } - // 用户刚关闭阅读器(1.5 秒内):这是返回后残留的回调,不再拉起 - if (readerClosedAt > 0 && System.currentTimeMillis() - readerClosedAt < 1500) return false; + // 刚关闭 / 属于已关阅读器的在途切章:都是返回后残留的回调,不再拉起 + if (shouldSuppressRelaunch()) return false; if (ctx instanceof NovelReaderHost) setHost((NovelReaderHost) ctx); @@ -236,12 +239,15 @@ public final class NovelRouter { // 阅读器已在前台 → 回传解析结果,不重复启动(切换章节场景) WebReaderActivity reader = currentReader; if (reader != null && !reader.isFinishing() && !reader.isDestroyed()) { + if (!reader.hasPendingHostChapterRequest() && NovelRouter.consumeStaleChapterResult()) return false; + // 不在这里清表:结清哪一条只有阅读器知道(它持有本次请求的令牌), + // 在这里猜或整表清空都会抹掉另一次仍在途的请求,返回键会重新失效。 reader.onEpisodeResolved(kind, payload, title); return true; } - // 用户刚关闭阅读器(1.5 秒内):这是返回后残留的 playerContent 回调,不再拉起 - if (readerClosedAt > 0 && System.currentTimeMillis() - readerClosedAt < 1500) return false; + // 刚关闭 / 属于已关阅读器的在途切章:都是返回后残留的 playerContent 回调,不再拉起 + if (shouldSuppressRelaunch()) return false; ArrayList ch = new ArrayList<>(); if (episodes != null) ch.addAll(episodes); @@ -440,9 +446,103 @@ public final class NovelRouter { java.lang.ref.WeakReference ref = hostRef; return ref == null ? null : ref.get(); } - /** 阅读器关闭时间戳,用于拦截「返回后残留 playerContent 回调又重新拉起阅读器」。 */ + /** 阅读器关闭时刻(单调时钟),用于拦截「返回后残留 playerContent 回调又重新拉起阅读器」。 */ public static volatile long readerClosedAt = 0L; + /** + * 阅读器关闭代号:每次交还前台自增一次。 + * + * 单靠 readerClosedAt 的 1500ms 窗口不够 —— 用户点了下一章又立刻返回时,爬虫可能几秒后才回, + * 这条迟到的结果落在窗口外就会重新拉起阅读器(就是「返回不了、只能强杀」的表现)。 + * 阅读器发起切章时记下代号,结果回来时比对:代号变过说明这期间阅读器被关过,结果作废。 + */ + private static volatile long readerCloseGen = 0L; + + /** + * 交给宿主解析、尚未收尾的切章请求数。 + * + * 只需要「数量」而不需要「身份」:抑制规则本身是「用户按返回那一刻若有请求在途, + * 它们的结果一律不许再拉起阅读器」。按身份追踪反而做不对 —— 结果送达那一刻 + * 拿不到「这是哪一章的」,之前按令牌 / 按最早 / 整表清空的写法都会删错条目。 + */ + private static final java.util.concurrent.atomic.AtomicInteger inFlightChapters = new java.util.concurrent.atomic.AtomicInteger(); + + /** 关闭时在途的请求数:它们的结果还在路上,必须逐个拦下。 */ + private static final java.util.concurrent.atomic.AtomicInteger staleChapterResults = new java.util.concurrent.atomic.AtomicInteger(); + + /** 上述待拦额度的失效时刻(单调时钟);过期即清,避免永久吞掉合法打开。 */ + private static volatile long staleUntil = 0L; + + /** + * 待拦结果的有效期。 + * + * 宿主解析有多条静默失败路径不回到本类(playerContent 报错走 onError、 + * 二次解析出来是普通视频地址),那些结果永远不会到达。用时限兜底, + * 否则额度下不去,用户之后主动打开别的书会被一直误吞。 + * 取 45s:HTML 侧切章看门狗 30s 就会放弃并回退章节。 + */ + private static final long PENDING_CHAPTER_TTL = 45_000L; + + /** 交还前台时调用:作废所有在途的切章结果。 */ + public static void markReaderClosed() { + // 单调时钟:wall clock 被 NTP 校正 / 用户改时间往回跳时, + // 「现在 - 关闭时刻」会变成大负数而恒小于窗口,静默期就永不结束, + // 之后所有阅读打开都被当成残留回调拦掉。 + readerClosedAt = android.os.SystemClock.elapsedRealtime(); + readerCloseGen++; + // 关闭这一刻仍在途的请求,其结果都属于「上一轮」,逐个拦下。 + // 没有在途请求时不留额度 —— 否则会无条件吞掉关闭后的第一次合法打开。 + int pending = inFlightChapters.getAndSet(0); + if (pending > 0) { + staleChapterResults.addAndGet(pending); + staleUntil = Math.max(staleUntil, readerClosedAt + PENDING_CHAPTER_TTL); + } + } + + /** 阅读器把切章交给宿主解析前调用。 */ + public static void noteChapterRequest() { + inFlightChapters.incrementAndGet(); + } + + /** 一次在途请求已收尾(结果送达或判失败)。 */ + public static void endChapterRequest() { + inFlightChapters.updateAndGet(n -> n > 0 ? n - 1 : 0); + } + + /** + * 这条结果是否属于「已经被关掉的那个阅读器」发起的切章。 + * 是则必须丢弃:用户已经返回,重新拉起阅读器就是返回键失效的根因。 + */ + private static boolean isStaleChapterResult() { + if (staleChapterResults.get() <= 0) return false; + if (android.os.SystemClock.elapsedRealtime() > staleUntil) { + staleChapterResults.set(0); + return false; + } + staleChapterResults.updateAndGet(n -> n > 0 ? n - 1 : 0); + return true; + } + + /** 公开一次性消费判定:true 表示这是已关闭阅读器的迟到结果。 */ + public static boolean consumeStaleChapterResult() { + return isStaleChapterResult(); + } + + + + /** 关闭后的静默期:刚返回时残留的回调一律不再拉起阅读器。 */ + private static boolean justClosed() { + return readerClosedAt > 0 && android.os.SystemClock.elapsedRealtime() - readerClosedAt < 1500; + } + + /** 前台没有阅读器时,判断这条结果该不该拉起新阅读器。 */ + private static boolean shouldSuppressRelaunch() { + // 两个判定都要执行,不能用 || 短路:isStaleChapterResult() 是一次性的读后清, + // 被短路掉标记就留了下来,等静默期过后用户主动打开另一本书时会被它误吞。 + boolean stale = isStaleChapterResult(); + return justClosed() || stale; + } + /** * 播放入口汇聚点(PlaybackActivity.startPlayer)调用: * playerContent 已返回 novel:// / pics:// / manga:// 这类「阅读内容协议」时, @@ -491,13 +591,16 @@ public final class NovelRouter { // 阅读器已在前台 → 回传解析结果,不重复启动(解决「切换章节回不到播放器」) WebReaderActivity reader = currentReader; if (reader != null && !reader.isFinishing() && !reader.isDestroyed()) { + if (!reader.hasPendingHostChapterRequest() && NovelRouter.consumeStaleChapterResult()) return false; + // 不在这里清表:结清哪一条只有阅读器知道(它持有本次请求的令牌), + // 在这里猜或整表清空都会抹掉另一次仍在途的请求,返回键会重新失效。 reader.onEpisodeResolved(kind, payload, extractTitle(payload)); return true; } // 用户刚关闭阅读器(1.5 秒内),说明这是返回后残留的 playerContent 回调, // 不再拉起阅读器,让播放器页面正常展示。 - if (readerClosedAt > 0 && System.currentTimeMillis() - readerClosedAt < 1500) { + if (shouldSuppressRelaunch()) { return false; } diff --git a/app/src/main/java/com/fongmi/android/tv/ui/novel/ReaderHistory.java b/app/src/main/java/com/fongmi/android/tv/ui/novel/ReaderHistory.java index 95e35e7d84..328f6c7d63 100644 --- a/app/src/main/java/com/fongmi/android/tv/ui/novel/ReaderHistory.java +++ b/app/src/main/java/com/fongmi/android/tv/ui/novel/ReaderHistory.java @@ -19,8 +19,10 @@ import java.util.Objects; * * 复用 History 表,因此阅读记录会和影视记录一起出现在历史列表里: * - episodeUrl / vodRemarks:上次读到的章节 URL 与章节名,用于重进时定位章节 - * - position / duration:章节内锚点序号与锚点总数。锚点即小说的段落、漫画的页, - * position/duration 恰好等于「已读比例」,历史列表的进度条无需特殊处理。 + * - position / duration:章节内锚点序号与锚点总数(锚点即小说的段落、漫画的页)。 + * position/duration 恰好等于「已读比例」,历史列表的进度条无需特殊处理; + * 读到最后一个锚点时 position 记为 duration,让「读完」显示 100%。 + * 恢复时用 {@link #toAnchor(long, long)} 换回锚点序号。 * * 记锚点序号而不记滚动百分比,是因为文档高度并不稳定:漫画图片分批懒加载且异步解码, * 小说段落用了 content-visibility:auto(屏外段落先按估算高度占位), @@ -69,10 +71,38 @@ public final class ReaderHistory { if (Setting.isIncognito() || record == null || !record.canUse()) return; if (total <= 0) return; long duration = total; - long position = Math.max(0, Math.min(duration, anchor)); + long position = toPosition(anchor, duration); Task.execute(() -> saveSync(record, chapterName, chapterUrl, position, duration)); } + /** + * 锚点序号 → 落库进度值。 + * + * 历史列表按 position/duration 画进度条。读到最后一个锚点时直接存 duration, + * 这样「读完」就是 100%(否则 2 页的漫画短章读完只显示 50%);其余情况沿用 + * 0 基序号,与升级前写入的存量记录同语义,不需要数据迁移。 + * + * 存量记录不会被误判成「读完」:旧代码的上限是 min(duration, anchor),而 anchor + * 最大只有 total-1,所以旧记录的 position 必然小于 duration。 + */ + static long toPosition(int anchor, long duration) { + long value = Math.max(0, Math.min(duration - 1, anchor)); + if (value < duration - 1) return value; + // 「读完」编码为 duration。但 duration 恰好等于 SCALE 时不能这么写: + // 那会让整条记录长得和旧版百分比记录(duration == SCALE)一模一样, + // 下次恢复走百分比分支,把锚点当成 0~1 的比例用。这种章少记一个锚点即可。 + return duration == SCALE ? duration - 1 : duration; + } + + /** 落库进度值 → 0 基锚点序号,供阅读器恢复定位。 */ + public static int toAnchor(long position, long duration) { + // total 无意义时不能把 position 原样当序号返回:那会让恢复逻辑去找一个不存在的锚点 + if (duration <= 0) return 0; + // position == duration 是「读完」的编码,换回最后一个锚点的序号 + if (position >= duration) return (int) (duration - 1); + return (int) Math.max(0, position); + } + private static void saveSync(Record record, String chapterName, String chapterUrl, long position, long duration) { String key = buildKey(record.siteKey, record.vodId); History history = find(record.siteKey, record.vodId); diff --git a/app/src/main/java/com/fongmi/android/tv/ui/web/WebReaderActivity.java b/app/src/main/java/com/fongmi/android/tv/ui/web/WebReaderActivity.java index c9d1832e5a..8a72603cc2 100644 --- a/app/src/main/java/com/fongmi/android/tv/ui/web/WebReaderActivity.java +++ b/app/src/main/java/com/fongmi/android/tv/ui/web/WebReaderActivity.java @@ -73,13 +73,14 @@ public class WebReaderActivity extends AppCompatActivity { String key = "reader_" + System.nanoTime(); if (payload != null) PAYLOAD_CACHE.put(key, payload); if (chapters != null) CHAPTER_CACHE.put(key, new ArrayList<>(chapters)); - CACHE_TIME.put(key, System.currentTimeMillis()); + // 单调时钟:wall clock 往回跳会让 now-创建时刻 变成负数而永不过期,缓存留到进程结束 + CACHE_TIME.put(key, android.os.SystemClock.elapsedRealtime()); return key; } /** 清理超过 TTL 的缓存:阅读器未真正启动时没人来取,否则会留到进程结束。 */ private static void evictStaleCache() { - long now = System.currentTimeMillis(); + long now = android.os.SystemClock.elapsedRealtime(); for (java.util.Map.Entry e : CACHE_TIME.entrySet()) { if (now - e.getValue() <= CACHE_TTL_MS) continue; String k = e.getKey(); @@ -164,6 +165,25 @@ public class WebReaderActivity extends AppCompatActivity { this.total = total; } } + /** + * 本页交给宿主解析、尚未收尾的切章请求数。 + * + * 只数不认身份:结果送达那一刻拿不到「这是哪一章的」,按身份追踪必然删错条目。 + * 抑制规则要的也只是「返回那一刻是否有请求在途」。 + */ + private final java.util.concurrent.atomic.AtomicInteger hostChapterRequests = new java.util.concurrent.atomic.AtomicInteger(); + + /** 收尾一次在途请求(结果送达或判失败);本页没有在途请求时什么都不做。 */ + private void endHostChapterRequest() { + if (hostChapterRequests.getAndUpdate(n -> n > 0 ? n - 1 : 0) > 0) { + NovelRouter.endChapterRequest(); + } + } + + public boolean hasPendingHostChapterRequest() { + return hostChapterRequests.get() > 0; + } + /** 待恢复的章节内锚点与总数(用完置 0)。 */ private long restoreAnchor = 0; private long restoreTotal = 0; @@ -1127,10 +1147,11 @@ public class WebReaderActivity extends AppCompatActivity { // 否则「传入的是不是目标章」会拿目标章和自己比,永远相等。 String incomingUrl = index >= 0 && index < chapters.size() ? chapters.get(index).getUrl() : null; index = at; - // position/duration 即锚点序号/总数;旧版小说记录存的是百分比×SCALE, - // HTML 侧按 total 是否等于 SCALE 兜底处理。 - restoreAnchor = h.getPosition(); + // position 是锚点序号(读完时记为 total),换回序号交给 HTML; + // 旧版小说记录存的是百分比×SCALE,HTML 侧按 total 是否等于 SCALE 兜底处理。 restoreTotal = h.getDuration(); + restoreAnchor = restoreTotal == ReaderHistory.SCALE + ? h.getPosition() : ReaderHistory.toAnchor(h.getPosition(), restoreTotal); String chapterName = h.getVodRemarks() == null ? "" : h.getVodRemarks(); lastProgress = new Progress(url, chapterName, (int) restoreAnchor, (int) restoreTotal); // 传入 payload 已是该章内容时无需重新解析 @@ -1164,8 +1185,15 @@ public class WebReaderActivity extends AppCompatActivity { /** 换章:HTML 点目录时回调。本地模式读目录章节,在线模式自行解析(无播放器时也能切章)。 */ @JavascriptInterface public void loadChapter(String chapterUrl) { - if (TextUtils.isEmpty(chapterUrl)) { chapterFailed(); return; } + // 空 URL 与任何宿主请求无关:不能让它收尾别人那一笔(会放行迟到结果、返回键失效) + if (TextUtils.isEmpty(chapterUrl)) { chapterFailed(false); return; } runOnUiThread(() -> { + // 本页已在交还前台:此刻再发宿主请求,它永远等不到下一次 markReaderClosed + // 把自己转成待拦额度,结果回来时就会把阅读器重新拉起(返回键失效)。 + if (isFinishing() || isDestroyed() || NovelRouter.currentReader != this) { + chapterFailed(false); + return; + } if (!localPath.isEmpty() && isLocalDir(chapterUrl)) { loadLocalChapter(chapterUrl); return; @@ -1177,8 +1205,14 @@ public class WebReaderActivity extends AppCompatActivity { return; } NovelReaderHost h = NovelRouter.getHost(); - if (h != null) h.labPlayEpisode(chapterUrl); - else chapterFailedWithToast(); + // 记下本次切章所属的关闭代号:用户点了下一章又马上返回时,爬虫几秒后才回的结果 + // 会落在 1500ms 静默期之外,靠代号比对才能认出它已过期,不该再拉起阅读器。 + if (h == null) { chapterFailedWithToast(); return; } + NovelRouter.noteChapterRequest(); + hostChapterRequests.incrementAndGet(); + // 宿主只在当前线路里找章节,找不到会静默返回 —— 立刻收尾并报失败, + // 否则这一笔要等 45s 才过期,期间用户主动打开别的书会被误吞。 + if (!h.labPlayEpisode(chapterUrl)) chapterFailedWithToast(true); }); } @@ -1187,6 +1221,20 @@ public class WebReaderActivity extends AppCompatActivity { * 少了这一步,HTML 会一直停在「切章中」,之后所有阅读进度都不再上报。 */ private void chapterFailed() { + chapterFailed(false); + } + + /** + * 通知 HTML 本次切章失败,并按令牌撤销在途标记。 + * + * @param ownHostRequest 这次失败是否对应本页发出的一笔宿主请求。空 URL、注入异常等 + * 与任何请求无关,传 false —— 否则会替别人收尾,让那一笔的迟到 + * 结果不再被拦,用户返回后又被重新拉起阅读器。 + */ + private void chapterFailed(boolean ownHostRequest) { + // 收尾放在 webView 判空之前:改的是 NovelRouter 的全局计数, + // 不该被本页的 view 引用是否还在决定(否则销毁中的页会让计数永久留着)。 + if (ownHostRequest) endHostChapterRequest(); if (webView == null) return; runOnUiThread(() -> { if (webView == null || isFinishing() || isDestroyed()) return; @@ -1197,8 +1245,12 @@ public class WebReaderActivity extends AppCompatActivity { } private void chapterFailedWithToast() { + chapterFailedWithToast(false); + } + + private void chapterFailedWithToast(boolean ownHostRequest) { Toast.makeText(this, R.string.reader_chapter_failed, Toast.LENGTH_SHORT).show(); - chapterFailed(); + chapterFailed(ownHostRequest); } /** @@ -1231,14 +1283,25 @@ public class WebReaderActivity extends AppCompatActivity { final boolean fh = needHost; runOnUiThread(() -> { if (isFinishing() || isDestroyed()) return; + boolean hostDispatched = false; if (fk != 0 && fp != null && !fp.isEmpty()) { if (at >= 0) index = at; - onEpisodeResolved(fk, fp, at >= 0 ? chapters.get(at).getName() : ""); + // 自解析成功:没经过宿主,不能替宿主请求收尾 + onEpisodeResolved(fk, fp, at >= 0 ? chapters.get(at).getName() : "", false); return; } NovelReaderHost h = NovelRouter.getHost(); - if (fh && h != null) h.labPlayEpisode(chapterUrl); - else chapterFailedWithToast(); + // 这条 parse=1 兜底才是实际会走到的宿主解析路径(loadChapter 里那条在 + // siteKey 非空时不可达,而所有真实启动入口都会带 siteKey)。它要走二次解析、 + // 耗时最长,最容易掉出关闭静默期,代号标记必须打在这里。 + if (fh && h != null) { + hostDispatched = true; + NovelRouter.noteChapterRequest(); + hostChapterRequests.incrementAndGet(); + if (!h.labPlayEpisode(chapterUrl)) chapterFailedWithToast(true); + return; + } + if (!hostDispatched) chapterFailedWithToast(); // 解析失败:放开占位层,并丢掉待恢复位置 —— 否则它会残留到用户下一次手动切章, // 把上一本/上一章的锚点套用到新章上(章短时直接跳到章末)。 restoreAnchor = 0; @@ -1303,6 +1366,18 @@ public class WebReaderActivity extends AppCompatActivity { * 把 novel:// / pics:// 解析成阅读数据注入 HTML。 */ public void onEpisodeResolved(int newKind, String payload, String title) { + onEpisodeResolved(newKind, payload, title, true); + } + + /** + * @param fromHost 结果是否来自宿主解析。自解析(resolveChapterSelf 直接拿到内容)时传 false: + * 那条路径没发过宿主请求,不能顺手把仍在途的宿主令牌丢掉 —— 丢了就再没有 + * 句柄去撤销它,只能等 45s TTL,期间用户主动打开别的书会被误吞。 + */ + private void onEpisodeResolved(int newKind, String payload, String title, boolean fromHost) { + // 宿主结果已到达,收尾一笔在途请求。只减计数、不认身份 —— 送达这一刻 + // 拿不到「这是哪一章的结果」,按身份删必然删错,反而放行别人的迟到结果。 + if (fromHost) endHostChapterRequest(); if (webView == null) return; // 漫画分支要下载 PDF(网络),不能在主线程做 RESOLVE_EXECUTOR.execute(() -> { @@ -1390,22 +1465,50 @@ public class WebReaderActivity extends AppCompatActivity { finish(); } + @Override + protected void onResume() { + super.onResume(); + // 重新登记:onPause 里交还前台时会把注册清掉(见 markClosed 的注释), + // 只在 onCreate 注册的话,两个阅读器叠栈时下层那个再次回到前台就永久失去注册, + // 之后它自己的切章会另起一个阅读器实例压在自己上面。 + NovelRouter.currentReader = this; + } + @Override protected void onPause() { // 切后台 / 返回都先落库,避免进程被回收后丢进度 persistProgress(); + // 先把关闭瞬间仍在途的请求转成全局待拦额度,再清理本页计数;否则 + // markReaderClosed() 看不到这些请求,迟到结果可能在静默期后重新拉起阅读器。 + if (isFinishing()) markClosed(); + // 本页仍在途的宿主请求随本页一起作废:它们的结果不会再回到这里, + // 不收尾的话全局在途计数永久偏高,下一次关闭会凭虚高的数字多留待拦额度, + // 把用户之后主动打开的书误吞掉。 + int inFlight = hostChapterRequests.getAndSet(0); + for (int i = 0; i < inFlight; i++) NovelRouter.endChapterRequest(); + // 关闭时间戳必须在这里打,不能等 onDestroy:Android 的生命周期顺序是 + // 本页 onPause -> 宿主 onResume -> 本页 onStop -> 本页 onDestroy。 + // 宿主 onResume 会因 shouldReclaim() 重新派发上一次的 playerContent 结果, + // 那一刻若时间戳还没写,NovelRouter 的两道防线同时失效(currentReader + // 已 isFinishing() 判不出「在前台」,时间戳又还是 0),于是立刻又拉起阅读器, + // 表现为返回键完全无效、只能强杀 APP。 super.onPause(); } + /** 交还前台:清掉阅读器注册并记下关闭时间/代号,拦截返回后残留的解析回调。 */ + private void markClosed() { + if (NovelRouter.currentReader != this) return; + NovelRouter.currentReader = null; + NovelRouter.markReaderClosed(); + } + @Override protected void onDestroy() { persistProgress(); // 清理阅读器静态引用 + 标记关闭时间,避免残留的 playerContent 回调在返回后重新拉起阅读器。 // 只在自己仍是「当前阅读器」时清:两个阅读器叠栈时,旧实例销毁不能把前台新实例的注册抹掉。 - if (NovelRouter.currentReader == this) { - NovelRouter.currentReader = null; - NovelRouter.readerClosedAt = System.currentTimeMillis(); - } + // onPause 已处理返回场景,这里兜住系统回收等不经过 finish() 的销毁。 + markClosed(); picTokens.clear(); // 只在真正结束时清缓存:配置变更 / 系统回收导致的重建会再次用同一个 cacheKey // 读取正文与章节列表(Intent 里只带 key,不带数据),提前清掉会渲染成空章。 diff --git a/app/src/main/java/com/fongmi/android/tv/utils/FileChooser.java b/app/src/main/java/com/fongmi/android/tv/utils/FileChooser.java index 8ff2f2af73..460a18dd77 100644 --- a/app/src/main/java/com/fongmi/android/tv/utils/FileChooser.java +++ b/app/src/main/java/com/fongmi/android/tv/utils/FileChooser.java @@ -21,14 +21,24 @@ import com.fongmi.android.tv.ui.activity.FileActivity; import com.github.catvod.utils.Path; import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; import java.io.InputStream; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; +import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; +import java.util.Locale; public class FileChooser { + private static final long MAX_IMPORT_BYTES = 32L * 1024L * 1024L; + private final ActivityResultLauncher launcher; public static FileChooser from(ActivityResultLauncher launcher) { @@ -86,6 +96,11 @@ public class FileChooser { return getPathFromUri(App.get(), uri); } + /** 为长期保存的配置导入项返回持久路径,避免系统 cache 清理或同名文件覆盖。 */ + public static String getPersistentPathFromUri(Uri uri) { + return getPathFromUri(App.get(), uri, true); + } + public static List getPathsFromIntent(Intent intent) { List paths = new ArrayList<>(); if (intent == null) return paths; @@ -103,12 +118,36 @@ public class FileChooser { } private static String getPathFromUri(Context context, Uri uri) { + return getPathFromUri(context, uri, false); + } + + private static String getPathFromUri(Context context, Uri uri, boolean persistent) { if (uri == null) return null; String path = null; + boolean encoded = true; if (DocumentsContract.isDocumentUri(context, uri)) path = getPathFromDocumentUri(context, uri); else if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) path = getDataColumn(context, uri); - else if (ContentResolver.SCHEME_FILE.equalsIgnoreCase(uri.getScheme())) path = uri.getPath(); - return path != null ? URLDecoder.decode(path, StandardCharsets.UTF_8) : createFileFromUri(context, uri); + else if (ContentResolver.SCHEME_FILE.equalsIgnoreCase(uri.getScheme())) { + // FileActivity 用 Uri.fromFile 生成,getPath() 已是明文;再解码会把 `+` 变成空格。 + path = uri.getPath(); + encoded = false; + } + if (path != null) { + String decoded = encoded ? decodePath(path) : path; + // 解码可能猜错:document/content 拿到的路径其实也已是明文,而 `+` 会被解成空格。 + // 解码结果不存在、原文存在时一律用原文——非持久分支同样受影响(字幕/弹幕都走这里)。 + if (!decoded.equals(path) && !new File(decoded).exists() && new File(path).exists()) return path; + if (!persistent || new File(decoded).exists()) return decoded; + } + return createFileFromUri(context, uri, persistent); + } + + private static String decodePath(String path) { + try { + return URLDecoder.decode(path, StandardCharsets.UTF_8); + } catch (IllegalArgumentException e) { + return path; + } } private static String getPathFromDocumentUri(Context context, Uri uri) { @@ -148,21 +187,90 @@ public class FileChooser { }; } - private static String createFileFromUri(Context context, Uri uri) { + private static String createFileFromUri(Context context, Uri uri, boolean persistent) { String[] projection = {MediaStore.MediaColumns.DISPLAY_NAME}; try (Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null)) { if (cursor == null || !cursor.moveToFirst()) return null; - InputStream is = context.getContentResolver().openInputStream(uri); - if (is == null) return null; int column = cursor.getColumnIndexOrThrow(projection[0]); - File file = Path.cache(cursor.getString(column)); - Path.copy(is, file); - return file.getAbsolutePath(); + String name = cursor.getString(column); + try (InputStream is = context.getContentResolver().openInputStream(uri)) { + if (is == null) return null; + if (!persistent) { + File target = Path.cache(name); + Path.copy(is, target); + return target.isFile() && target.length() > 0 ? target.getAbsolutePath() : null; + } + return persistentImport(is, name, Path.files("cat_source_imports")); + } } catch (Exception e) { return null; } } + /** + * 导入目录在内部存储里,系统「清理缓存」清不掉,所以不能每次导入都留一份新副本。 + * + *

按内容 md5 命名做天然去重:反复导入同一个包只占一份,而不同内容各自独立, + * 也不需要删除任何文件——已保存的配置仍指向自己那一份。先写临时文件再原子移动, + * 中断不会留下残缺文件。temp 在拿到流之后才建,避免 {@code openInputStream} + * 返回 null 时留下 0 字节的 {@code .import-*.tmp}。 + * + *

{@code dir} 由调用方传入,好让单测不依赖 {@code Path.files()} 背后的 Android Context。 + */ + static String persistentImport(InputStream is, String name, File dir) throws IOException { + dir.mkdirs(); + File temp = File.createTempFile(".import-", ".tmp", dir); + try { + MessageDigest digest; + try { + digest = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e) { + throw new IOException("MD5 不可用", e); + } + long total = 0; + try (FileOutputStream out = new FileOutputStream(temp)) { + byte[] buffer = new byte[65536]; + int length; + while ((length = is.read(buffer)) != -1) { + total += length; + if (total > MAX_IMPORT_BYTES) throw new IOException("导入文件超过大小限制"); + digest.update(buffer, 0, length); + out.write(buffer, 0, length); + } + } + if (total == 0) throw new IOException("导入文件为空"); + File target = new File(dir, hex(digest.digest()) + "_" + safeName(name)); + if (target.isFile() && target.length() == total) { + temp.delete(); + return target.getAbsolutePath(); + } + moveImport(temp, target); + return target.isFile() && target.length() > 0 ? target.getAbsolutePath() : null; + } catch (Exception e) { + if (temp.exists()) temp.delete(); + throw e; + } + } + + private static String safeName(String name) { + String base = name == null ? "import" : new File(name).getName(); + return base.replaceAll("[^A-Za-z0-9._-]", "_"); + } + + private static String hex(byte[] bytes) { + StringBuilder value = new StringBuilder(bytes.length * 2); + for (byte item : bytes) value.append(String.format(Locale.ROOT, "%02x", item & 0xff)); + return value.toString(); + } + + private static void moveImport(File source, File target) throws IOException { + try { + Files.move(source.toPath(), target.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } catch (AtomicMoveNotSupportedException e) { + Files.move(source.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING); + } + } + private static String getDataColumn(Context context, Uri uri) { String[] projection = {MediaStore.MediaColumns.DATA}; try (Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null)) { diff --git a/app/src/main/res/drawable/ic_launcher_history.xml b/app/src/main/res/drawable/ic_launcher_history.xml index b402b89673..b2caf529bb 100644 --- a/app/src/main/res/drawable/ic_launcher_history.xml +++ b/app/src/main/res/drawable/ic_launcher_history.xml @@ -1,5 +1,10 @@ - + + android:scaleX="0.6416667" + android:scaleY="0.6416667" + android:translateX="91.733337" + android:translateY="91.733337"> diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index a21393a1e8..e9745462e0 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -1401,6 +1401,7 @@ 选择章节 请输入配置… 选择文件夹(猫源本地包) + 读不到所选内容,请重新选择包目录或 zip 请输入名称… 请输入地址… @@ -1426,6 +1427,8 @@ 网络读取失败,请检查网络、请求头或更换线路 媒体解析失败或没有有效音视频轨道,请更换线路或播放器 音视频解码失败,请尝试切换软硬解或播放器 + 音频输出失败,请重新进入播放或切换解码方式 + 视频输出失败,请重新进入播放或切换解码方式 音视频输出失败,请重新进入播放或切换解码方式 DRM 鉴权或受保护媒体处理失败,请更换线路或播放器 播放失败,请重试或切换播放器 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 84aaf7aa55..0d869fa678 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -1360,6 +1360,7 @@ 選擇章節 請輸入配置… 選擇資料夾(貓源本地包) + 讀不到所選內容,請重新選擇包目錄或 zip 請輸入名稱… 請輸入網址… @@ -1385,6 +1386,8 @@ 網路讀取失敗,請檢查網路、請求標頭或更換線路 媒體解析失敗或沒有有效音視訊軌道,請更換線路或播放器 音視訊解碼失敗,請嘗試切換軟硬解或播放器 + 音訊輸出失敗,請重新進入播放或切換解碼方式 + 視訊輸出失敗,請重新進入播放或切換解碼方式 音視訊輸出失敗,請重新進入播放或切換解碼方式 DRM 驗證或受保護媒體處理失敗,請更換線路或播放器 播放失敗,請重試或切換播放器 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 464afab4b2..637d719870 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1432,6 +1432,7 @@ Select chapter Please enter the config… Choose folder (cat source local package) + Could not read the selected item, please pick the package folder or zip again Please enter the name… Please enter the url… @@ -1457,6 +1458,8 @@ Network reading failed. Check the network and request headers, or choose another line. Media parsing failed or no playable audio/video track was found. Choose another line or player. Audio/video decoding failed. Try another decode mode or player. + Audio output failed. Reopen playback or try another decode mode. + Video output failed. Reopen playback or try another decode mode. Audio/video output failed. Reopen playback or try another decode mode. DRM authorization or protected-media handling failed. Choose another line or player. Playback failed. Retry or switch player. diff --git a/app/src/mobile/java/com/fongmi/android/tv/ui/activity/VideoActivity.java b/app/src/mobile/java/com/fongmi/android/tv/ui/activity/VideoActivity.java index 142567315f..e2a617905f 100644 --- a/app/src/mobile/java/com/fongmi/android/tv/ui/activity/VideoActivity.java +++ b/app/src/mobile/java/com/fongmi/android/tv/ui/activity/VideoActivity.java @@ -55,9 +55,6 @@ import androidx.transition.ChangeBounds; import androidx.transition.TransitionManager; import androidx.viewbinding.ViewBinding; import com.bumptech.glide.request.transition.Transition; -import com.google.android.flexbox.FlexWrap; -import com.google.android.flexbox.FlexboxLayoutManager; -import com.google.android.flexbox.JustifyContent; import com.fongmi.android.tv.App; import com.fongmi.android.tv.Constant; import com.fongmi.android.tv.R; @@ -398,6 +395,7 @@ private int mAudioBackgroundRandomNonce; private boolean mNativePersonalDoubanLoading; private boolean mEpisodeGridMode = Setting.getTmdbEpisodeGridMode(); private int playerKernelSwitchRequestId; + private int mPendingPlayerKernel = PlayerSetting.NONE; private boolean decodeSwitchRefreshing; private int deferredFullscreenOrientation = Configuration.ORIENTATION_UNDEFINED; private int mEpisodeSpanCount; @@ -1298,6 +1296,7 @@ private final Task.Scope mPersonalRecommendationTasks = new Task.Scope(Task.reco @Override protected void onServiceConnected() { player().setDanmakuController(mBinding.exo.getDanmakuController()); + applyPendingPlayerKernel(); syncDesktopLyricsAudioContent(); setPlayerKernel(); setDecode(); @@ -1343,6 +1342,7 @@ private final Task.Scope mPersonalRecommendationTasks = new Task.Scope(Task.reco getIntent().removeExtra(EXTRA_RESUME_HISTORY_CID); getIntent().removeExtra(EXTRA_RESUME_HISTORY_KEY); getIntent().putExtras(intent); + resetPlaybackOwnership(); if (mTmdbUIAdapter != null) mTmdbUIAdapter.beginDetailRequest(); mSourceEpisodeSeasonCache.clear(); mSourceVodName = ""; @@ -1352,6 +1352,9 @@ private final Task.Scope mPersonalRecommendationTasks = new Task.Scope(Task.reco // 否则长视频会卡在竖屏全屏且无法旋转。仍是短剧则保持形态,避免无谓的进出全屏抖动。 if (shortDramaSession && !isShortDramaSource()) exitFullscreen(); shortDramaSession = false; + // 形态可能仍是短剧全屏(新条目也是短剧时上面不退出),所以按当前形态重算而不是一律清掉, + // 否则新条目在到达 STATE_READY 之前会用长视频那套手势,侧边竖滑又变成调亮度。 + syncShortDramaGesture(); setOrient(); checkId(); } @@ -1713,7 +1716,7 @@ private final Task.Scope mPersonalRecommendationTasks = new Task.Scope(Task.reco } private void setPlayer() { - mBinding.control.action.player.setText(service() == null ? ResUtil.getStringArray(R.array.select_player)[PlayerSetting.getPlayer()] : player().getPlayerText()); + mBinding.control.action.player.setText(service() == null ? ResUtil.getStringArray(R.array.select_player)[PlayerSetting.getActivePlayer()] : player().getPlayerText()); } private void setupActionButtons() { @@ -1884,6 +1887,50 @@ private final Task.Scope mPersonalRecommendationTasks = new Task.Scope(Task.reco mBinding.control.action.player.setText(player().getPlayerText()); } + /** + * 起播前把内核切到本剧记住的选择,并返回该内核给取址用——取播放地址要按内核区分线路。 + * 没有记录时 getPlayerOrDefault 会退回设置页的全局默认。 + * 播放服务还没连上时先只记会话内核(取址在工作线程上读它),引擎由 onServiceConnected 补齐。 + */ + private int applyHistoryPlayerKernel() { + int kernel = mHistory == null ? PlayerSetting.getPlayer() : mHistory.getPlayerOrDefault(); + PlayerSetting.putActivePlayer(kernel); + if (service() == null) { + mPendingPlayerKernel = kernel; + return kernel; + } + mPendingPlayerKernel = PlayerSetting.NONE; + player().preparePlayer(kernel); + setPlayerKernel(); + setDecode(); + return kernel; + } + + /** + * 服务连上后补齐本页在等的内核。 + * 服务可能是上一次播放留活下来的,它建 PlayerManager 时读到的还是上一部剧的内核, + * 所以本页在服务就绪前定下的选择要在这里落到引擎上;没有待办时不动引擎。 + */ + private void applyPendingPlayerKernel() { + int kernel = mPendingPlayerKernel; + mPendingPlayerKernel = PlayerSetting.NONE; + if (!PlayerSetting.isPlayer(kernel)) return; + player().preparePlayer(kernel); + } + + /** + * 把用户刚选定的内核写回本剧历史并落盘。 + * 只在用户显式换内核时调用,且用用户选的值而不是会话/引擎状态: + * 播放页可能重叠存在(上一部剧的 Activity 还没销毁),若挂在每次存历史上, + * 上一部剧的收尾存档会用别人的会话内核覆盖本剧记住的选择; + * 而引擎类型还会被播放失败后的自动回退改掉,也不代表用户改了选择。 + */ + private void rememberPlayerKernel(int type) { + if (mHistory == null || !PlayerSetting.isPlayer(type)) return; + mHistory.setPlayer(type); + syncHistory(); + } + private void setScale(int scale) { if (mHistory != null) mHistory.setScale(scale); if (SiteApi.PUSH.equals(getKey())) PlayerSetting.putScale(scale); @@ -2304,7 +2351,7 @@ private final Task.Scope mPersonalRecommendationTasks = new Task.Scope(Task.reco clearLyrics(); clearKaraokeState(); if (shouldUseImmersiveAudio()) setAudioStageVisible(true); - mViewModel.playerContent(getKey(), playFlag, episode.getUrl()); + mViewModel.playerContent(getKey(), playFlag, episode.getUrl(), applyHistoryPlayerKernel()); mBinding.control.title.setSelected(true); updateHistory(episode); showProgress(); @@ -2420,16 +2467,23 @@ private final Task.Scope mPersonalRecommendationTasks = new Task.Scope(Task.reco * 含 parse=1 二次解析)。解析结果经 NovelRouter.routeReaderEngine 回传给前台阅读页。 */ @Override - public void labPlayEpisode(String chapterUrl) { - if (chapterUrl == null || chapterUrl.isEmpty()) return; + public boolean labPlayEpisode(String chapterUrl) { + if (chapterUrl == null || chapterUrl.isEmpty()) return false; + // 宿主已在销毁中:解析结果不会再回到阅读器,直接报「没发出」让它立刻收尾。 + // 另外 SiteViewModel 被清理后 playerContent 会抛 RejectedExecutionException, + // 那个异常会顺着阅读器的 runOnUiThread 冒出去导致崩溃。 + if (isFinishing() || isDestroyed()) return false; Flag flag = getFlag(); - if (flag == null || flag.getEpisodes() == null) return; + if (flag == null || flag.getEpisodes() == null) return false; for (Episode ep : flag.getEpisodes()) { if (chapterUrl.equals(ep.getUrl())) { getPlayer(flag, ep); - return; + return true; } } + // 章节不在当前线路:阅读器的章节表跨线路合并,这种情况静默返回, + // 告知调用方没有发出请求,让它立刻收尾在途标记。 + return false; } @Override @@ -2614,11 +2668,8 @@ private final Task.Scope mPersonalRecommendationTasks = new Task.Scope(Task.reco private void updateEpisodeLayout(List items, boolean useTmdbCard) { if (!mEpisodeGridMode) { RecyclerView.LayoutManager manager = mBinding.episode.getLayoutManager(); - if (!(manager instanceof FlexboxLayoutManager)) { - FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(this); - layoutManager.setFlexWrap(FlexWrap.WRAP); - layoutManager.setJustifyContent(JustifyContent.CENTER); - mBinding.episode.setLayoutManager(layoutManager); + if (!(manager instanceof LinearLayoutManager) || manager instanceof GridLayoutManager || ((LinearLayoutManager) manager).getOrientation() != LinearLayoutManager.HORIZONTAL) { + mBinding.episode.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)); } updateEpisodeDecoration(new SpaceItemDecoration(8)); return; @@ -3013,6 +3064,7 @@ private final Task.Scope mPersonalRecommendationTasks = new Task.Scope(Task.reco } private void onSetting() { + setTrackVisible(); ControlDialog.create().parent(mBinding).history(mHistory).parse(isUseParse()).player(player()).show(this); } @@ -4310,7 +4362,7 @@ private final Task.Scope mPersonalRecommendationTasks = new Task.Scope(Task.reco if (result == null || result.hasMsg() || result.getRealUrl().isEmpty()) { player().toggleDecode(); } else { - player().switchDecode(result, getHistoryKey(), metadata, isUseParse(), position, speed, repeat); + player().switchDecode(result, activePlaybackKey(), metadata, isUseParse(), position, speed, repeat); } setR1Callback(); setDecodeSwitchPending(false); @@ -4386,6 +4438,7 @@ private final Task.Scope mPersonalRecommendationTasks = new Task.Scope(Task.reco player().switchPlayerManually(which); setPlayer(); setDecode(); + rememberPlayerKernel(which); } } else { playerKernelSwitchRequestId++; @@ -4445,7 +4498,8 @@ private final Task.Scope mPersonalRecommendationTasks = new Task.Scope(Task.reco if (result == null || result.hasMsg() || result.getRealUrl().isEmpty()) { Notify.show(result != null && result.hasMsg() ? result.getMsg() : getString(R.string.error_play_url)); } else { - player().switchPlayer(type, result, getHistoryKey(), metadata, isUseParse(), position, speed, repeat); + player().switchPlayer(type, result, activePlaybackKey(), metadata, isUseParse(), position, speed, repeat); + rememberPlayerKernel(type); } setPlayerKernel(); setDecode(); @@ -4497,6 +4551,9 @@ private final Task.Scope mPersonalRecommendationTasks = new Task.Scope(Task.reco setSizeText(); setRotate(current.isPortrait()); mKeyDown.resetScale(); + // 短剧会话退出全屏后再双击/点全屏按钮进来不走 enterShortDramaFullscreen, + // 这里也要按新形态重算,否则回到全屏时手势还是长视频那套轴向。 + syncShortDramaGesture(); App.post(mR3, 2000); hideControl(); logVideoFrame("enterFullscreen after"); @@ -4531,6 +4588,8 @@ private final Task.Scope mPersonalRecommendationTasks = new Task.Scope(Task.reco mBinding.video.setLayoutParams(mFrameParams); restoreEmbeddedVideoLayoutAfterFullscreen(); mKeyDown.resetScale(); + // 退出全屏就交还短剧手势:内嵌小窗上竖滑要留给详情页滚动,不能再切集。 + syncShortDramaGesture(); App.post(mR3, 2000); setRotate(false); hideControl(); @@ -4668,6 +4727,12 @@ private final Task.Scope mPersonalRecommendationTasks = new Task.Scope(Task.reco private void showControl() { if (service() == null || isInPictureInPictureMode()) return; + if (mAudioStageVisible && !isFullscreen()) { + hideWidgetOverlay(); + hideControl(); + return; + } + setTrackVisible(); setOsdSuppressed(true); boolean shortDrama = isShortDramaSession(); boolean showPiP = canShowPiP(shortDrama); @@ -4775,6 +4840,7 @@ private final Task.Scope mPersonalRecommendationTasks = new Task.Scope(Task.reco private void setTraffic() { Traffic.setSpeed(mBinding.progress.traffic, service() == null ? null : player()); + hidePlaybackProgressIfStale(); App.post(mR2, 1000); } @@ -6776,6 +6842,23 @@ private final Task.Scope mPersonalRecommendationTasks = new Task.Scope(Task.reco showPlaybackContent(); } + /** + * 加载圈的兜底收口。 + * + *

圈只在 {@code STATE_READY} 分支被收(onStateChanged),而那条回调受 isOwner() 把关。 + * 归属判定一旦因任何原因失配,圈就永久留在屏上——画面在动、圈不走。这里不依赖归属, + * 直接读播放器状态:已在播且已 READY 就收圈。要求 {@code !isEmpty()},避免详情尚未加载完 + * (播放器还空着)时把详情页自己的加载态误收。 + * + *

挂在 mR2(网速刷新,圈可见时每秒一跳)上,圈不可见时该循环本就已停,无额外开销。 + */ + private void hidePlaybackProgressIfStale() { + if (mBinding.progress.getRoot().getVisibility() != View.VISIBLE) return; + if (service() == null || player() == null || player().isReleased() || player().isEmpty()) return; + if (player().getPlaybackState() != Player.STATE_READY) return; + showPlaybackContent(); + } + @Override protected void onSeekStarted() { showProgress(); @@ -8170,11 +8253,23 @@ private final Task.Scope mPersonalRecommendationTasks = new Task.Scope(Task.reco setRequestedOrientation(isPort() ? ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT : ActivityInfo.SCREEN_ORIENTATION_FULL_USER); mKeyDown.resetScale(); } + syncShortDramaGesture(); setShortDramaScale(); hideControl(); ViewCompat.requestApplyInsets(mBinding.getRoot()); } + /** + * 手势轴向跟着呈现形态走:短剧竖屏全屏时整屏上下滑切集、长按后上下滑调亮度/音量。 + *

+ * 必须由「当前是否处于短剧全屏」推导,不能在进入时置一次了事:横屏短剧允许自由旋转, + * 转回竖屏会走 exitFullscreen 退回内嵌小窗,此时若手势仍是短剧那套,在详情页上 + * 竖滑就会误切集。同理换到另一部短剧时形态保持不变,标记也不该被清掉。 + */ + private void syncShortDramaGesture() { + if (mKeyDown != null) mKeyDown.setShortDrama(isFullscreen() && isShortDramaSession()); + } + private void setShortDramaScale() { int scale = (mHistory != null && mHistory.getScale() != -1) ? getScale() : SHORT_DRAMA_SCALE; applyResizeMode(scale); diff --git a/app/src/mobile/java/com/fongmi/android/tv/ui/custom/CustomKeyDown.java b/app/src/mobile/java/com/fongmi/android/tv/ui/custom/CustomKeyDown.java index 7c6e72cd10..5693448198 100644 --- a/app/src/mobile/java/com/fongmi/android/tv/ui/custom/CustomKeyDown.java +++ b/app/src/mobile/java/com/fongmi/android/tv/ui/custom/CustomKeyDown.java @@ -36,10 +36,14 @@ public class CustomKeyDown extends GestureDetector.SimpleOnGestureListener imple private boolean changeTime; private boolean multiTouch; private boolean animating; + private boolean shortDrama; private boolean touch; private boolean lock; private float bright; private float currentBright; + private float anchorY = Float.NaN; + private float downX; + private float downY; private float brightLimit = BrightnessPolicy.NO_LIMIT; private float volume; private float scale; @@ -65,13 +69,51 @@ public class CustomKeyDown extends GestureDetector.SimpleOnGestureListener imple int action = e.getActionMasked(); boolean end = action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL; if (action == MotionEvent.ACTION_DOWN) multiTouch = false; + // 起点在这里记而不是 onDown:onDown 在边缘/缩放/锁定时会提前返回, + // 而 changeScale 会在 onScaleEnd 之后 500ms 才解除,那段窗口里按下的手势 + // 拿不到自己的起点,长按转调节时会拿上一次的起点算位移,一按就跳。 + if (action == MotionEvent.ACTION_DOWN) { + downX = e.getX(); + downY = e.getY(); + } if (action == MotionEvent.ACTION_POINTER_DOWN) multiTouch = true; - if (action == MotionEvent.ACTION_UP) listener.onTouchEnd(); + // 被父容器拦截或来电时只收到 CANCEL:HUD 与倍速同样要收尾, + // 否则 widget 会一直盖在画面上、倍速卡在长按后的速率。 + if (end) listener.onTouchEnd(); + // 短剧的亮度/音量在长按之后才生效,此时 GestureDetector 已不再回调 onScroll, + // 只能在这里自行处理移动事件,详见 handleAdjust。用实时指数判断而不是 multiTouch: + // 后者在 ACTION_POINTER_UP 时不会复位,会把抬起一根手指后的单指调节一起挡掉。 + if (shortDrama && action == MotionEvent.ACTION_MOVE && e.getPointerCount() == 1 && !lock && !changeScale) handleAdjust(e); // 手势被父容器拦截或来电时只收到 CANCEL,同样要落盘,否则窗口已改而记忆值未更新 if (changeBright && end) PlayerSetting.putBrightness(currentBright); - if (changeSpeed && action == MotionEvent.ACTION_UP) listener.onSpeedEnd(); + if (changeSpeed && end) listener.onSpeedEnd(); + // seek 只在正常抬手时提交:CANCEL 属于手势被打断,维持原位置更符合预期。 if (changeTime && action == MotionEvent.ACTION_UP) listener.onSeekEnd(time); - return e.getPointerCount() == 2 ? scaleDetector.onTouchEvent(e) : detector.onTouchEvent(e); + boolean handled = e.getPointerCount() == 2 ? scaleDetector.onTouchEvent(e) : detector.onTouchEvent(e); + // 必须等 detector 处理完再清:onFling 是 detector 在 UP 时回调的,它要读 + // changeSpeed/changeBright/changeVolume 才能判断这次抬手是否该切集。 + // 提前清掉会让「调完亮度松手」被当成切集手势。 + if (end) clearGesture(); + return handled; + } + + /** + * 一次手势结束就把功能标记清干净。 + *

+ * {@link #reset()} 挂在 onDown 上,而 onDown 在边缘/缩放/锁定时会提前返回, + * 于是上一次手势的 changeBright/anchorY 可能活到下一次手势——短剧的亮度/音量 + * 由 onTouchEvent 直接驱动,不再有 onScroll 的兜底,残留状态会直接造成 + * 「没长按就跳亮度」。所以收尾统一在这里做,不依赖下一次 onDown 是否被接受。 + */ + private void clearGesture() { + changeTime = false; + changeSpeed = false; + changeBright = false; + changeVolume = false; + anchorY = Float.NaN; + // 不动 touch:它表示「本次手势还没选定功能」,是就绪态而非残留动作。 + // 在这里清成 false 会让缩放后 500ms 内(changeScale 还没解除时)起手的那一次 + // 拖动选不到任何功能,白滑一次。它由 reset() 置真、checkFunc 置假,无需插手。 } private void applyBrightness() { @@ -121,6 +163,17 @@ public class CustomKeyDown extends GestureDetector.SimpleOnGestureListener imple this.lock = lock; } + /** + * 短剧竖屏形态下换用另一套手势轴向,参考红果短剧、抖音等主流竖屏播放器: + * 上下滑切上下集(全屏可用),亮度/音量改为长按后再上下滑,左半亮度右半音量。 + *

+ * 原来「中间竖滑切集 + 左右 1/4 竖滑调亮度音量」在铺满屏幕的竖屏短剧里极易误触 + * (用户反馈):想切集却滑到了边缘,调亮度又常常切了集。 + */ + public void setShortDrama(boolean shortDrama) { + this.shortDrama = shortDrama; + } + public float getScale() { return scale; } @@ -170,6 +223,7 @@ public class CustomKeyDown extends GestureDetector.SimpleOnGestureListener imple private void reset() { time = 0; touch = true; + anchorY = Float.NaN; changeTime = false; changeSpeed = false; changeBright = false; @@ -208,6 +262,43 @@ public class CustomKeyDown extends GestureDetector.SimpleOnGestureListener imple return true; } + /** + * 短剧的「长按后上下滑调亮度/音量」。 + *

+ * 不能挂在 {@link #onScroll} 上:GestureDetector 触发长按后会把后续 ACTION_MOVE + * 全部吞掉(mInLongPress 分支直接 break),onScroll 再也不会回调,所以这条手势 + * 必须由 onTouchEvent 自己驱动。 + */ + private void handleAdjust(MotionEvent e) { + // 只认「本次手势自己长按出来」的调节,避免上一次手势的残留标记把亮度带跑。 + if (!changeSpeed && Float.isNaN(anchorY)) return; + if (changeSpeed) { + float dx = e.getX() - downX; + float dy = e.getY() - downY; + if (Math.abs(dy) <= Math.abs(dx) || Math.abs(dy) < ResUtil.dp2px(20)) return; + startAdjust(e); + } + // 以「长按转调节」的那一刻为基准,避免把长按期间的位移一次性算进亮度/音量。 + float deltaY = anchorY - e.getY(); + if (changeBright) setBright(deltaY); + if (changeVolume) setVolume(deltaY); + } + + /** + * 长按倍速中途转为亮度/音量调节:先把倍速交还,再以当前触点为新基准。 + */ + private void startAdjust(MotionEvent e) { + listener.onSpeedEnd(); + changeSpeed = false; + touch = false; + anchorY = e.getY(); + float saved = PlayerSetting.getBrightness(); + bright = saved >= 0 ? saved : Util.getBrightness(activity); + currentBright = bright; + volume = manager.getStreamVolume(AudioManager.STREAM_MUSIC); + checkSide(e); + } + @Override public boolean onDoubleTap(@NonNull MotionEvent e) { if (isMultiple(e) || isEdge(e) || changeScale) return true; @@ -224,15 +315,21 @@ public class CustomKeyDown extends GestureDetector.SimpleOnGestureListener imple @Override public boolean onFling(MotionEvent e1, @NonNull MotionEvent e2, float velocityX, float velocityY) { - if (isMultiple(e1) || isEdge(e1) || isSide(e1) || changeScale || lock || animating) return true; + // 短剧上下滑切集不再受左右 1/4 的亮度/音量分区限制(那两块已改为长按触发), + // 但 isEdge 的 24dp 边框仍然保留:那里要让给系统的返回/通知栏手势。 + if (isMultiple(e1) || isEdge(e1) || (!shortDrama && isSide(e1)) || changeScale || lock || animating) return true; + // 这次手势已经用于调亮度/音量或倍速,抬手不应再被当成切集。 + if (changeSpeed || changeBright || changeVolume) return true; checkFunc(e1, e2); return true; } private void checkFunc(float distanceX, float distanceY, MotionEvent e2) { if ((float) Math.sqrt(distanceX * distanceX + distanceY * distanceY) < ResUtil.dp2px(20)) return; + // 短剧的上下滑整屏留给切集(onFling),亮度/音量改由 startAdjust(长按后再滑)接管, + // 所以这里只保留横滑拖进度,不再按左右 1/4 分派亮度/音量。 if (distanceX >= distanceY) changeTime = true; - else if (isSide(e2)) checkSide(e2); + else if (!shortDrama && isSide(e2)) checkSide(e2); touch = false; } @@ -240,10 +337,13 @@ public class CustomKeyDown extends GestureDetector.SimpleOnGestureListener imple float dx = e2.getX() - e1.getX(); float dy = e2.getY() - e1.getY(); double angle = Math.toDegrees(Math.atan2(Math.abs(dy), Math.abs(dx))); + // 短剧的切集动画沿用同一套竖向回弹,但不跟随直播的「反转」开关: + // 竖屏短剧里上滑=下一集是抖音/红果的既定语义,反转会让用户完全迷失。 + boolean invert = !shortDrama && LiveSetting.isInvert(); if (angle > 70 && e1.getY() - e2.getY() > DISTANCE) { - videoView.animate().translationYBy(ResUtil.dp2px(LiveSetting.isInvert() ? 24 : -24)).setDuration(150).withStartAction(() -> animating = true).withEndAction(() -> videoView.animate().translationY(0).setDuration(100).withStartAction(listener::onFlingUp).withEndAction(() -> animating = false).start()).start(); + videoView.animate().translationYBy(ResUtil.dp2px(invert ? 24 : -24)).setDuration(150).withStartAction(() -> animating = true).withEndAction(() -> videoView.animate().translationY(0).setDuration(100).withStartAction(listener::onFlingUp).withEndAction(() -> animating = false).start()).start(); } else if (angle > 70 && e2.getY() - e1.getY() > DISTANCE) { - videoView.animate().translationYBy(ResUtil.dp2px(LiveSetting.isInvert() ? -24 : 24)).setDuration(150).withStartAction(() -> animating = true).withEndAction(() -> videoView.animate().translationY(0).setDuration(100).withStartAction(listener::onFlingDown).withEndAction(() -> animating = false).start()).start(); + videoView.animate().translationYBy(ResUtil.dp2px(invert ? -24 : 24)).setDuration(150).withStartAction(() -> animating = true).withEndAction(() -> videoView.animate().translationY(0).setDuration(100).withStartAction(listener::onFlingDown).withEndAction(() -> animating = false).start()).start(); } } @@ -265,8 +365,9 @@ public class CustomKeyDown extends GestureDetector.SimpleOnGestureListener imple } private void setVolume(float deltaY) { - int height = videoView.getMeasuredHeight(); + int height = Math.max(videoView.getMeasuredHeight(), 1); int maxVolume = manager.getStreamMaxVolume(AudioManager.STREAM_MUSIC); + if (maxVolume <= 0) return; float deltaV = deltaY * 2.0f / height * maxVolume; float index = volume + deltaV; if (index > maxVolume) index = maxVolume; diff --git a/app/src/mobile/java/com/fongmi/android/tv/ui/dialog/ConfigDialog.java b/app/src/mobile/java/com/fongmi/android/tv/ui/dialog/ConfigDialog.java index 35bd2f208a..119cee80a2 100644 --- a/app/src/mobile/java/com/fongmi/android/tv/ui/dialog/ConfigDialog.java +++ b/app/src/mobile/java/com/fongmi/android/tv/ui/dialog/ConfigDialog.java @@ -94,7 +94,8 @@ public class ConfigDialog extends BaseAlertDialog { binding.choose.setEndIconOnClickListener(this::onChoose); // 猫源本地包是一整个文件夹(index.js + index.config.js),文件选择器选不到目录, // 所以单独给一个入口。选 zip 仍走上面那个文件选择。 - binding.choose.setStartIconOnClickListener(this::onChooseDir); + binding.choose.setStartIconVisible(type == 0); + if (type == 0) binding.choose.setStartIconOnClickListener(this::onChooseDir); binding.url.addTextChangedListener(new CustomTextListener() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { @@ -221,8 +222,11 @@ public class ConfigDialog extends BaseAlertDialog { private final ActivityResultLauncher launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> { if (result.getResultCode() != Activity.RESULT_OK || result.getData() == null || result.getData().getData() == null) return; String name = binding.name.getText().toString().trim(); - String path = FileChooser.getPathFromUri(result.getData().getData()); - if (TextUtils.isEmpty(path)) return; + String path = FileChooser.getPersistentPathFromUri(result.getData().getData()); + if (TextUtils.isEmpty(path)) { + Notify.show(R.string.dialog_config_choose_failed); + return; + } String url = "file:/" + path.replace(Path.rootPath(), ""); ((ConfigListener) requireParentFragment()).setConfig(saveConfig(url, name)); dismiss(); diff --git a/app/src/mobile/java/com/fongmi/android/tv/ui/holder/EpisodeHoriHolder.java b/app/src/mobile/java/com/fongmi/android/tv/ui/holder/EpisodeHoriHolder.java index 6c0fdd1af4..bea71f1630 100644 --- a/app/src/mobile/java/com/fongmi/android/tv/ui/holder/EpisodeHoriHolder.java +++ b/app/src/mobile/java/com/fongmi/android/tv/ui/holder/EpisodeHoriHolder.java @@ -138,7 +138,10 @@ public class EpisodeHoriHolder extends BaseEpisodeHolder { binding.nativeFileSize.setText(fileSize); binding.nativeFileSize.setVisibility(visible ? View.VISIBLE : View.GONE); binding.nativeFileSize.setSelected(binding.text.isActivated() || binding.text.hasFocus()); - binding.text.setPadding(visible ? ResUtil.dp2px(92) : 0, binding.text.getPaddingTop(), binding.text.getPaddingEnd(), binding.text.getPaddingBottom()); + // 左右必须成对给:只改左边会让 shape_video_item 的 12dp 右内边距落单, + // 按钮里的文本就偏向一侧而不是居中。徽标占位时左边额外让出 92dp。 + int horizontal = ResUtil.dp2px(12); + binding.text.setPadding(visible ? ResUtil.dp2px(92) : horizontal, binding.text.getPaddingTop(), horizontal, binding.text.getPaddingBottom()); } private void bindFileSize(String fileSize) { diff --git a/app/src/test/java/androidx/media3/mpvplayer/MpvOsdSurfacePolicyTest.java b/app/src/test/java/androidx/media3/mpvplayer/MpvOsdSurfacePolicyTest.java index 035199a2ee..6874378a94 100644 --- a/app/src/test/java/androidx/media3/mpvplayer/MpvOsdSurfacePolicyTest.java +++ b/app/src/test/java/androidx/media3/mpvplayer/MpvOsdSurfacePolicyTest.java @@ -34,4 +34,20 @@ public class MpvOsdSurfacePolicyTest { assertFalse(MpvOsdSurfacePolicy.requiresSurface( false, "2", "2", "4", "4")); } + + @Test + public void disabledSubtitleSelectionsDoNotQueryCurrentTracks() { + assertFalse(MpvOsdSurfacePolicy.needsCurrentTrackQuery( + true, "no", "no")); + assertFalse(MpvOsdSurfacePolicy.needsCurrentTrackQuery( + false, "auto", "auto")); + } + + @Test + public void automaticOrUnknownSelectionStillQueriesCurrentTracks() { + assertTrue(MpvOsdSurfacePolicy.needsCurrentTrackQuery( + true, "auto", "no")); + assertTrue(MpvOsdSurfacePolicy.needsCurrentTrackQuery( + true, "", "no")); + } } diff --git a/app/src/test/java/androidx/media3/mpvplayer/MpvPauseIntentPolicyTest.java b/app/src/test/java/androidx/media3/mpvplayer/MpvPauseIntentPolicyTest.java new file mode 100644 index 0000000000..bb86bf661b --- /dev/null +++ b/app/src/test/java/androidx/media3/mpvplayer/MpvPauseIntentPolicyTest.java @@ -0,0 +1,38 @@ +package androidx.media3.mpvplayer; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class MpvPauseIntentPolicyTest { + + @Test + public void matchingPlayingStateNeedsNoAction() { + assertEquals(MpvPauseIntentPolicy.Action.NONE, + MpvPauseIntentPolicy.resolve(true, false, true)); + } + + @Test + public void matchingPausedStateNeedsNoAction() { + assertEquals(MpvPauseIntentPolicy.Action.NONE, + MpvPauseIntentPolicy.resolve(false, true, true)); + } + + @Test + public void delayedStartupPauseReassertsAutoplayIntent() { + assertEquals(MpvPauseIntentPolicy.Action.REASSERT_REQUESTED_STATE, + MpvPauseIntentPolicy.resolve(true, true, true)); + } + + @Test + public void delayedUnpauseReassertsUserPauseIntent() { + assertEquals(MpvPauseIntentPolicy.Action.REASSERT_REQUESTED_STATE, + MpvPauseIntentPolicy.resolve(false, false, true)); + } + + @Test + public void mismatchBeforeFileIsActiveWaitsForLoadBoundary() { + assertEquals(MpvPauseIntentPolicy.Action.WAIT_FOR_ACTIVE_MEDIA, + MpvPauseIntentPolicy.resolve(true, true, false)); + } +} diff --git a/app/src/test/java/androidx/media3/mpvplayer/MpvSurfaceTeardownPolicyTest.java b/app/src/test/java/androidx/media3/mpvplayer/MpvSurfaceTeardownPolicyTest.java new file mode 100644 index 0000000000..6261967b45 --- /dev/null +++ b/app/src/test/java/androidx/media3/mpvplayer/MpvSurfaceTeardownPolicyTest.java @@ -0,0 +1,36 @@ +package androidx.media3.mpvplayer; + +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class MpvSurfaceTeardownPolicyTest { + + @Test + public void transientSurfaceLossKeepsAttachAndDetachEnabled() { + MpvSurfaceTeardownPolicy policy = new MpvSurfaceTeardownPolicy(); + + assertTrue(policy.shouldBindSurface()); + assertTrue(policy.shouldDetachSurface()); + } + + @Test + public void terminalReleaseBlocksAttachAndDetach() { + MpvSurfaceTeardownPolicy policy = new MpvSurfaceTeardownPolicy(); + + assertTrue(policy.requestTerminalRelease()); + assertFalse(policy.shouldBindSurface()); + assertFalse(policy.shouldDetachSurface()); + } + + @Test + public void repeatedTerminalReleaseIsIdempotent() { + MpvSurfaceTeardownPolicy policy = new MpvSurfaceTeardownPolicy(); + + assertTrue(policy.requestTerminalRelease()); + assertFalse(policy.requestTerminalRelease()); + assertFalse(policy.shouldBindSurface()); + assertFalse(policy.shouldDetachSurface()); + } +} diff --git a/app/src/test/java/com/fongmi/android/tv/api/CatSourceConfigTest.java b/app/src/test/java/com/fongmi/android/tv/api/CatSourceConfigTest.java index 1aa65d86c5..dea859fe80 100644 --- a/app/src/test/java/com/fongmi/android/tv/api/CatSourceConfigTest.java +++ b/app/src/test/java/com/fongmi/android/tv/api/CatSourceConfigTest.java @@ -4,6 +4,8 @@ import com.github.catvod.utils.Json; import org.junit.Test; +import java.util.Locale; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -53,6 +55,18 @@ public class CatSourceConfigTest { CatSource.isConfig("{\"sites\":[{\"key\":\"csp_Demo\"}]}")); } + @Test + public void bundleSuffixDetectionIsLocaleIndependent() { + Locale previous = Locale.getDefault(); + try { + Locale.setDefault(new Locale("tr", "TR")); + assertTrue("bundle 地址判定不能受默认 Locale 影响", + CatSource.isBundle("HTTPS://HOST/INDEX.JS")); + } finally { + Locale.setDefault(previous); + } + } + @Test public void rejectsEmptyFlatArray() { assertFalse("空数组说明这个端口没在服务站点,应继续探下一个", CatSource.isConfig("[]")); diff --git a/app/src/test/java/com/fongmi/android/tv/bean/HistoryPushKeyStabilityTest.java b/app/src/test/java/com/fongmi/android/tv/bean/HistoryPushKeyStabilityTest.java new file mode 100644 index 0000000000..6bc6325a0a --- /dev/null +++ b/app/src/test/java/com/fongmi/android/tv/bean/HistoryPushKeyStabilityTest.java @@ -0,0 +1,61 @@ +package com.fongmi.android.tv.bean; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; + +/** + * 网盘(push)历史记录的 key 必须稳定。 + * + *

push 的 key 第二段就是那条播放地址本身(SiteApi#pushDetail 把 id 原样塞进 Vod), + * 而从历史进入播放正是靠 {@link History#getVodId()} 反解这一段。普通站点的 vodId 是稳定的 + * 条目 id,迁移无害;push 迁移会把记录改写成详情阶段解析出的另一条地址,那条地址往往带 + * 时效,下次从历史打开必然失败,用户只能回网盘重新找。 + */ +public class HistoryPushKeyStabilityTest { + + @Test + public void pushHistoryIsExcludedFromKeyMigration() throws Exception { + String source = read("app/src/main/java/com/fongmi/android/tv/bean/History.java"); + + int replace = source.indexOf("public void replace(String key)"); + int guard = source.indexOf("if (isPushHistory()) return;", replace); + int firstWrite = source.indexOf("String previous = getKey();", replace); + + assertTrue("replace must exist", replace > 0); + assertTrue("push records must bail out of key migration", guard > replace); + assertTrue("the guard must run before any migration work", guard < firstWrite); + } + + @Test + public void pushExemptionsStayConsistentAcrossMergeAndMigration() throws Exception { + String source = read("app/src/main/java/com/fongmi/android/tv/bean/History.java"); + + // 按名合并早已对 push 豁免(多个网盘链接常同名);key 迁移是同一类问题的另一面, + // 两处必须共用同一个判据,避免其中一处被改动时另一处静默失配 + assertTrue("the push predicate must be shared", source.contains("private boolean isPushHistory()")); + assertTrue("name merging must stay exempt", source.contains("return !isPushHistory();")); + assertTrue("the predicate must key off the push site prefix", + source.contains("key.startsWith(SiteApi.PUSH + AppDatabase.SYMBOL)")); + } + + @Test + public void pushKeysSurviveTheVodIdRoundTrip() { + // 迁移被挡住的前提是 key 保持原样,反解才能拿回可用地址 + History history = new History(); + history.setKey("push_agent@@@https://pan.quark.cn/s/eab19bde98be@@@48"); + + assertTrue("a push key must still resolve to its playable url", + history.getVodId().startsWith("https://pan.quark.cn/")); + } + + private static String read(String path) throws Exception { + Path direct = Path.of(path); + if (Files.exists(direct)) return Files.readString(direct, StandardCharsets.UTF_8); + return Files.readString(Path.of(path.substring("app/".length())), StandardCharsets.UTF_8); + } +} diff --git a/app/src/test/java/com/fongmi/android/tv/bean/HistorySeasonSnapshotProjectionTest.java b/app/src/test/java/com/fongmi/android/tv/bean/HistorySeasonSnapshotProjectionTest.java new file mode 100644 index 0000000000..c1e9e732fb --- /dev/null +++ b/app/src/test/java/com/fongmi/android/tv/bean/HistorySeasonSnapshotProjectionTest.java @@ -0,0 +1,79 @@ +package com.fongmi.android.tv.bean; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import com.fongmi.android.tv.history.HistoryDisplayPolicy; + +import org.junit.Test; + +import java.util.List; + +public class HistorySeasonSnapshotProjectionTest { + + @Test + public void ownSeasonSnapshotSupersedesOlderUnknownHistoryRoute() { + History unknown = history("tv", 88, 100, "site-a@@@vod-a"); + unknown.setCid(7); + unknown.setTmdbEpisodePositionWithUnknownSeason(1); + unknown.setPosition(296); + unknown.setDuration(2_276_000); + TmdbSeasonProgress snapshot = TmdbSeasonProgress.of( + 7, "tv", 88, 6, 1, 1_080_193, 2_276_000, unknown.getKey()); + snapshot.updatedAt = 300; + + List result = HistoryDisplayPolicy.project(List.of(unknown), List.of(snapshot), true); + + assertEquals(1, result.size()); + assertEquals(6, result.get(0).getTmdbSeasonNumber()); + assertEquals(1_080_193, result.get(0).getPosition()); + } + + @Test + public void newerUnknownHistoryRouteStaysBesideOldSnapshot() { + History unknown = history("tv", 88, 300, "site-a@@@vod-a"); + unknown.setCid(7); + unknown.setTmdbEpisodePositionWithUnknownSeason(1); + TmdbSeasonProgress snapshot = TmdbSeasonProgress.of( + 7, "tv", 88, 6, 1, 1_080_193, 2_276_000, unknown.getKey()); + snapshot.updatedAt = 100; + + List result = HistoryDisplayPolicy.project(List.of(unknown), List.of(snapshot), true); + + assertEquals(2, result.size()); + assertTrue(result.stream().anyMatch(item -> item.getTmdbSeasonNumber() == -1)); + assertTrue(result.stream().anyMatch(item -> item.getTmdbSeasonNumber() == 6)); + } + + @Test + public void explicitUnknownSeasonPreservedWhenCanonicalEpisodeNumberIsKnown() { + History history = new History(); + history.setTmdbEpisodePosition(6, 12); + + assertTrue(history.setTmdbEpisodePositionWithUnknownSeason(13)); + + assertEquals(-1, history.getTmdbSeasonNumber()); + assertEquals(13, history.getTmdbEpisodeNumber()); + } + + @Test + public void nullEpisodeStillClearsCanonicalPosition() { + History history = new History(); + history.setTmdbEpisodePosition(6, 12); + + history.setTmdbEpisodePosition(null); + + assertEquals(0, history.getTmdbSeasonNumber()); + assertEquals(0, history.getTmdbEpisodeNumber()); + } + + private static History history(String mediaType, int tmdbId, long createTime, String key) { + History history = new History(); + history.setKey(key); + history.setMediaType(mediaType); + history.setTmdbId(tmdbId); + history.setCreateTime(createTime); + return history; + } +} diff --git a/app/src/test/java/com/fongmi/android/tv/node/NodeBundleInstallTest.java b/app/src/test/java/com/fongmi/android/tv/node/NodeBundleInstallTest.java new file mode 100644 index 0000000000..c46d5e48a6 --- /dev/null +++ b/app/src/test/java/com/fongmi/android/tv/node/NodeBundleInstallTest.java @@ -0,0 +1,465 @@ +package com.fongmi.android.tv.node; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; + +/** + * 猫源本地包的安装、缓存判定和失败回滚——这些是有状态的路径,出错的后果是「装了 A 跑 B」 + * 或者「缓存永久坏掉只能清数据」,所以要真建目录、真装、真读磁盘来验证。 + * + *

{@code NodeBundle} 的这些入口都接一个运行目录(而不是 Context),正是为了能这样测。 + */ +public class NodeBundleInstallTest { + + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + + private File runtime; + + private File runtime() throws IOException { + if (runtime == null) runtime = folder.newFolder("node-bundle"); + return runtime; + } + + @Test + public void installsLocalDirectoryAndMarksItCached() throws IOException { + File dir = runtime(); + File source = pack("pkg", "module.exports={a:1};", "module.exports={site:1};"); + + assertNull("完整的本地目录包必须能装上", NodeBundle.ensure(dir, source.getAbsolutePath(), null)); + assertEquals("module.exports={a:1};", read(new File(dir, "index.js"))); + assertEquals("module.exports={site:1};", read(new File(dir, "index.config.js"))); + assertTrue("来源键必须落盘,否则下次判不出缓存归属", read(new File(dir, "source.key")).startsWith("local:")); + assertEquals("stamp 必须是实际内容的 md5", md5("module.exports={a:1};"), read(new File(dir, "index.js.md5"))); + } + + /** 内容变了必须真的换掉运行目录里的文件,否则改完配置仍跑旧 config。 */ + @Test + public void reinstallingChangedSourceReplacesRuntimeFiles() throws IOException { + File dir = runtime(); + File source = pack("pkg", "module.exports={a:1};", "module.exports={site:1};"); + assertNull(NodeBundle.ensure(dir, source.getAbsolutePath(), null)); + String firstKey = read(new File(dir, "source.key")); + + Files.write(new File(source, "index.config.js").toPath(), "module.exports={site:2};".getBytes(StandardCharsets.UTF_8)); + assertNull(NodeBundle.ensure(dir, source.getAbsolutePath(), null)); + + assertEquals("新 config 必须生效", "module.exports={site:2};", read(new File(dir, "index.config.js"))); + assertFalse("来源键必须随内容变化", firstKey.equals(read(new File(dir, "source.key")))); + } + + /** + * 解压出来的目录是用户可写的,改 index.config.js 换站点是本地包的主要用法,marker + * 不会跟着更新。硬校验会把这批当前可用的包判死,且用户没有自救路径。 + */ + @Test + public void markerMismatchInDirectoryDoesNotBlockInstall() throws IOException { + File dir = runtime(); + File source = pack("pkg", "module.exports={a:1};", "module.exports={site:1};"); + Files.write(new File(source, "index.js.md5").toPath(), "ffffffffffffffffffffffffffffffff".getBytes(StandardCharsets.UTF_8)); + + assertNull("marker 与内容不符只该告警,不该阻断", NodeBundle.ensure(dir, source.getAbsolutePath(), null)); + assertEquals("装进去的必须是实际内容", "module.exports={a:1};", read(new File(dir, "index.js"))); + assertEquals("stamp 记的必须是实际内容的 md5,而不是那个过期 marker", + md5("module.exports={a:1};"), read(new File(dir, "index.js.md5"))); + } + + /** + * md5sum 生成的 marker 是「hash 文件名」两段格式。zip 形态是硬校验,认不出这个格式 + * 就会把整包判成「校验值无效」——而这类包在改动前是能正常安装的。 + */ + @Test + public void md5sumStyleMarkerIsAcceptedInZip() throws IOException { + File dir = runtime(); + String body = "module.exports={a:1};"; + File zip = zip("md5sum.zip", md5(body) + " index.js", body, "module.exports={site:1};"); + + assertNull("md5sum 格式的 marker 必须能用", NodeBundle.ensure(dir, zip.getAbsolutePath(), null)); + assertEquals(body, read(new File(dir, "index.js"))); + } + + /** zip 里的内容用户改不了,marker 不符就是包损坏,必须拒绝而不是装进去。 */ + @Test + public void corruptZipIsRejected() throws IOException { + File dir = runtime(); + File zip = zip("bad.zip", "ffffffffffffffffffffffffffffffff", "module.exports={a:1};", "module.exports={site:1};"); + + String error = NodeBundle.ensure(dir, zip.getAbsolutePath(), null); + assertNotNull("marker 与内容不符的 zip 必须拒绝", error); + assertFalse("拒绝后不能留下运行文件", new File(dir, "index.js").isFile()); + } + + @Test + public void installsZipPackage() throws IOException { + File dir = runtime(); + String body = "module.exports={a:2};"; + File zip = zip("ok.zip", md5(body), body, "module.exports={site:9};"); + + assertNull(NodeBundle.ensure(dir, zip.getAbsolutePath(), null)); + assertEquals(body, read(new File(dir, "index.js"))); + assertTrue(read(new File(dir, "source.key")).startsWith("local:")); + } + + @Test + public void missingConfigIsRejectedWithActionableMessage() throws IOException { + File dir = runtime(); + File source = folder.newFolder("partial"); + Files.write(new File(source, "index.js.md5").toPath(), md5("x").getBytes(StandardCharsets.UTF_8)); + Files.write(new File(source, "index.js").toPath(), "x".getBytes(StandardCharsets.UTF_8)); + + String error = NodeBundle.ensure(dir, source.getAbsolutePath(), null); + assertNotNull("缺 config 的包必须报错", error); + assertTrue("错误要指明缺什么:" + error, error.contains("index.config.js")); + assertFalse("失败时不能留下半截运行文件", new File(dir, "index.js").isFile()); + } + + /** 装到一半被杀会留下 staging 目录和临时文件,不清会一直吃内部存储。 */ + @Test + public void ensureSweepsLeftoversFromKilledProcess() throws IOException { + File dir = runtime(); + File stage = new File(dir, ".stage-abandoned"); + stage.mkdirs(); + Files.write(new File(stage, "index.js").toPath(), "leftover".getBytes(StandardCharsets.UTF_8)); + File backup = new File(dir, "index.js.backup-123.tmp"); + Files.write(backup.toPath(), "old".getBytes(StandardCharsets.UTF_8)); + + File source = pack("pkg", "module.exports={a:1};", "module.exports={site:1};"); + assertNull(NodeBundle.ensure(dir, source.getAbsolutePath(), null)); + + assertFalse("staging 残留必须被清掉", stage.exists()); + assertFalse("backup 残留必须被清掉", backup.exists()); + } + + @Test + public void sweepKeepsInstalledFilesAndRemovesOnlyLeftovers() throws IOException { + File dir = runtime(); + File source = pack("pkg", "module.exports={a:1};", "module.exports={site:1};"); + assertNull(NodeBundle.ensure(dir, source.getAbsolutePath(), null)); + + File stage = new File(dir, ".stage-x"); + stage.mkdirs(); + File temp = new File(dir, "index.js.999.tmp"); + Files.write(temp.toPath(), "t".getBytes(StandardCharsets.UTF_8)); + + NodeBundle.sweep(dir); + + assertFalse(stage.exists()); + assertFalse("writeAtomic 的临时文件也要清", temp.exists()); + assertTrue("已装好的 bundle 不能被清掉", new File(dir, "index.js").isFile()); + assertTrue(new File(dir, "index.config.js").isFile()); + assertTrue(new File(dir, "source.key").isFile()); + } + + // ---- isCached:缓存判定的每条拒绝理由都要真的生效,否则会把不对的内容当就绪跑起来 ---- + + @Test + public void isCachedAcceptsOnlySelfConsistentVerifiedFiles() throws IOException { + File dir = runtime(); + String body = "module.exports={a:1};"; + File target = new File(dir, "index.js"); + File stamp = new File(dir, "index.js.md5"); + File source = new File(dir, "source.key"); + Files.write(target.toPath(), body.getBytes(StandardCharsets.UTF_8)); + Files.write(stamp.toPath(), md5(body).getBytes(StandardCharsets.UTF_8)); + Files.write(source.toPath(), "remote:https://h/x:k".getBytes(StandardCharsets.UTF_8)); + + assertTrue("内容、stamp、来源键、服务端校验值全部一致才算命中", + NodeBundle.isCached(target, stamp, source, "remote:https://h/x:k", md5(body))); + assertTrue("服务端校验值拿不到时退回自洽判定", + NodeBundle.isCached(target, stamp, source, "remote:https://h/x:k", "")); + + assertFalse("来源键为空不能命中", NodeBundle.isCached(target, stamp, source, "", md5(body))); + assertFalse("来源键不属于这份缓存不能命中", + NodeBundle.isCached(target, stamp, source, "remote:https://h/other:k", md5(body))); + assertFalse("服务端校验值与实际内容不符不能命中", + NodeBundle.isCached(target, stamp, source, "remote:https://h/x:k", "ffffffffffffffffffffffffffffffff")); + assertFalse("目标文件不存在不能命中", + NodeBundle.isCached(new File(dir, "absent.js"), stamp, source, "remote:https://h/x:k", md5(body))); + + Files.write(stamp.toPath(), "ffffffffffffffffffffffffffffffff".getBytes(StandardCharsets.UTF_8)); + assertFalse("stamp 与实际内容不符不能命中(回滚失败留下的混合态)", + NodeBundle.isCached(target, stamp, source, "remote:https://h/x:k", "")); + + Files.write(stamp.toPath(), "TODO".getBytes(StandardCharsets.UTF_8)); + assertFalse("stamp 不是合法 md5 不能命中", + NodeBundle.isCached(target, stamp, source, "remote:https://h/x:k", "")); + } + + @Test + public void isCachedRejectsEmptyTarget() throws IOException { + File dir = runtime(); + File target = new File(dir, "index.js"); + File stamp = new File(dir, "index.js.md5"); + File source = new File(dir, "source.key"); + Files.write(target.toPath(), new byte[0]); + Files.write(stamp.toPath(), md5("").getBytes(StandardCharsets.UTF_8)); + Files.write(source.toPath(), "k".getBytes(StandardCharsets.UTF_8)); + + assertFalse("0 字节的目标文件不是有效缓存", NodeBundle.isCached(target, stamp, source, "k", "")); + } + + // ---- 来源键补齐:不补会让每次加载配置都白白重启一遍 :node 子进程 ---- + + /** + * 旧版本落盘的来源键没有内容指纹。两个文件都命中缓存时要就地补成当前身份, + * 否则 servesCurrentSource 每次都判「身份不符」→ 每次都重启子进程。 + */ + @Test + public void legacySourceKeyIsRefreshedOnceContentIsVerified() throws IOException { + File dir = runtime(); + String bundle = "module.exports={a:1};"; + String config = "module.exports={site:1};"; + String url = "https://host/cat/index.js.md5"; + seedInstalled(dir, bundle, config, "remote:https://host/cat/index.js"); + String key = NodeBundle.remoteSourceKey(url, md5(bundle), md5(config)); + + // 旧格式的键仍然「属于」这个地址,所以缓存判定本身能命中——这是补齐的前提。 + assertTrue("旧格式的键必须仍被认作该地址的缓存", + NodeBundle.installedIsRemoteOf(read(new File(dir, "source.key")), url)); + assertTrue("内容与服务端一致时缓存必须命中,不该重下", + NodeBundle.isCached(new File(dir, "index.js"), new File(dir, "index.js.md5"), + new File(dir, "source.key"), read(new File(dir, "source.key")), md5(bundle))); + + assertTrue("来源键必须被补成当前身份", NodeBundle.refreshSourceKey(dir, key)); + assertEquals(key, read(new File(dir, "source.key"))); + assertFalse("已经是当前身份时不该重复改写", NodeBundle.refreshSourceKey(dir, key)); + assertFalse("空身份不能覆盖掉已有的键", NodeBundle.refreshSourceKey(dir, "")); + assertEquals("拒绝改写时键必须原样保留", key, read(new File(dir, "source.key"))); + } + + /** + * 守卫:身份里的摘要必须与两个 stamp 一致才允许写入。只靠调用点的前置条件的话, + * 将来有人从别处调它就会静默写入一个与内容不符的身份,让下次复用判定认错。 + */ + @Test + public void refreshRejectsKeyThatDoesNotMatchInstalledStamps() throws IOException { + File dir = runtime(); + String bundle = "module.exports={a:1};"; + String config = "module.exports={site:1};"; + String url = "https://host/cat/index.js.md5"; + seedInstalled(dir, bundle, config, "remote:https://host/cat/index.js"); + String stale = "ffffffffffffffffffffffffffffffff"; + + assertFalse("bundle 摘要与 stamp 不符时不能写入", + NodeBundle.refreshSourceKey(dir, NodeBundle.remoteSourceKey(url, stale, md5(config)))); + assertFalse("config 摘要不符同样不能写入", + NodeBundle.refreshSourceKey(dir, NodeBundle.remoteSourceKey(url, md5(bundle), stale))); + assertFalse("拆不出摘要的旧格式身份不能写入", + NodeBundle.refreshSourceKey(dir, "remote:https://host/cat/index.js")); + assertEquals("被拒绝时键必须原样保留", + "remote:https://host/cat/index.js", read(new File(dir, "source.key"))); + + assertTrue("摘要与两个 stamp 都一致时才允许写入", + NodeBundle.refreshSourceKey(dir, NodeBundle.remoteSourceKey(url, md5(bundle), md5(config)))); + } + + /** + * 服务端只改 index.config.js(最常规的更新形态)时,index.js 一字未变,必须仍判命中。 + * 把两个文件的指纹揉进一个键、再拿它当单文件的缓存键,就会每次配置更新都重下整包。 + */ + @Test + public void updatingOnlyConfigKeepsBundleCached() throws IOException { + File dir = runtime(); + String bundle = "module.exports={a:1};"; + String oldConfig = "module.exports={site:1};"; + String newConfig = "module.exports={site:2};"; + String url = "https://host/cat/index.js.md5"; + seedInstalled(dir, bundle, oldConfig, NodeBundle.remoteSourceKey(url, md5(bundle), md5(oldConfig))); + + // 服务端公布的新校验值:bundle 没变、config 变了 + boolean[] cached = NodeBundle.remoteCacheState(dir, url, md5(bundle), md5(newConfig)); + assertTrue("index.js 没变就必须命中,不能因为 config 更新了而重下整包", cached[0]); + assertFalse("index.config.js 变了必须判未命中", cached[1]); + } + + /** 两个都没变时必须全命中,否则每次加载都白跑一遍下载。 */ + @Test + public void unchangedRemoteBundleIsFullyCached() throws IOException { + File dir = runtime(); + String bundle = "module.exports={a:1};"; + String config = "module.exports={site:1};"; + String url = "https://host/cat/index.js.md5"; + seedInstalled(dir, bundle, config, NodeBundle.remoteSourceKey(url, md5(bundle), md5(config))); + + boolean[] cached = NodeBundle.remoteCacheState(dir, url, md5(bundle), md5(config)); + assertTrue(cached[0]); + assertTrue(cached[1]); + } + + /** 旧格式来源键也要能命中,否则升级后白重下几十 MB。 */ + @Test + public void legacyKeyStillYieldsCacheHits() throws IOException { + File dir = runtime(); + String bundle = "module.exports={a:1};"; + String config = "module.exports={site:1};"; + String url = "https://host/cat/index.js.md5"; + seedInstalled(dir, bundle, config, "remote:https://host/cat/index.js"); + + boolean[] cached = NodeBundle.remoteCacheState(dir, url, md5(bundle), md5(config)); + assertTrue("旧格式键的缓存必须仍可命中", cached[0]); + assertTrue(cached[1]); + } + + /** 缓存属于别的地址时一律不能命中,否则会拿 A 源的 bundle 当 B 源用。 */ + @Test + public void cacheBelongingToAnotherUrlNeverHits() throws IOException { + File dir = runtime(); + String bundle = "module.exports={a:1};"; + String config = "module.exports={site:1};"; + seedInstalled(dir, bundle, config, + NodeBundle.remoteSourceKey("https://host/cat/index.js.md5", md5(bundle), md5(config))); + + boolean[] cached = NodeBundle.remoteCacheState(dir, "https://host/other/index.js.md5", md5(bundle), md5(config)); + assertFalse(cached[0]); + assertFalse(cached[1]); + } + + // ---- installedDigests:离线交叉校验的期望值来源,拆错会让校验静默失效 ---- + + @Test + public void installedDigestsExtractsVerifiedChecksums() { + String a = "b24cea4ad00908b04d0fbe8d0a01999e"; + String b = "ffffffffffffffffffffffffffffffff"; + + String[] parsed = NodeBundle.installedDigests("remote:https://host/cat/index.js:" + a + ":" + b); + assertEquals(a, parsed[0]); + assertEquals(b, parsed[1]); + + assertEquals("带端口的地址不能影响拆分", a, + NodeBundle.installedDigests("remote:http://host:8080/x/index.js:" + a + ":" + b)[0]); + + for (String bad : new String[]{"remote:https://host/cat/index.js", "remote:", ":", "", null, + "remote:https://host/a:b:c"}) { + String[] empty = NodeBundle.installedDigests(bad); + assertEquals("旧格式/畸形输入必须拆不出摘要:" + bad, "", empty[0]); + assertEquals("", empty[1]); + } + } + + // ---- install 的回滚:失败后必须回到旧缓存,或把缓存标记为不可信,绝不留下混合态 ---- + + @Test + public void installReplacesBothFilesAndStamps() throws IOException { + File dir = runtime(); + // 先铺一份旧的,否则 install 里 backup 分支根本不会执行,下面的 backup 断言就是空的。 + seedInstalled(dir, "old-bundle", "old-config", "local:/old:a:b"); + NodeBundle.PreparedFile bundle = staged(dir, "index.js", "new-bundle"); + NodeBundle.PreparedFile config = staged(dir, "index.config.js", "new-config"); + + assertNull(NodeBundle.install(dir, bundle, config, "local:/pkg:a:b")); + assertEquals("new-bundle", read(new File(dir, "index.js"))); + assertEquals("new-config", read(new File(dir, "index.config.js"))); + assertEquals(md5("new-bundle"), read(new File(dir, "index.js.md5"))); + assertEquals(md5("new-config"), read(new File(dir, "index.config.js.md5"))); + assertEquals("local:/pkg:a:b", read(new File(dir, "source.key"))); + // staging 目录由 ensure 的 finally 清理,install 只负责不留自己的 backup 临时文件。 + assertFalse("发布成功后必须删掉 backup", hasTempLeftover(dir)); + } + + /** + * config 的 staging 文件缺失(进程被杀、磁盘满)时 install 必然失败。此时 bundle 已经 + * 发布出去了,必须把旧的搬回来——否则下次启动跑的是新 JS + 旧 config 的混合态。 + */ + @Test + public void installRollsBackWhenSecondFileCannotBePublished() throws IOException { + File dir = runtime(); + seedInstalled(dir, "old-bundle", "old-config", "local:/old:a:b"); + + NodeBundle.PreparedFile bundle = staged(dir, "index.js", "new-bundle"); + NodeBundle.PreparedFile missing = new NodeBundle.PreparedFile(new File(dir, ".stage-gone/index.config.js"), md5("x")); + + assertNotNull("staging 文件缺失必须报错", NodeBundle.install(dir, bundle, missing, "local:/new:c:d")); + assertEquals("bundle 必须回滚成旧内容", "old-bundle", read(new File(dir, "index.js"))); + assertEquals("config 不能被动过", "old-config", read(new File(dir, "index.config.js"))); + assertEquals("stamp 必须回滚", md5("old-bundle"), read(new File(dir, "index.js.md5"))); + assertEquals("来源键必须回滚", "local:/old:a:b", read(new File(dir, "source.key"))); + assertFalse("回滚后不能留下 backup 残留", hasTempLeftover(dir)); + } + + /** 首次安装(无旧缓存)失败时不能留下半截文件,否则 isCached 可能把它当有效缓存。 */ + @Test + public void installLeavesNothingBehindWhenFirstInstallFails() throws IOException { + File dir = runtime(); + NodeBundle.PreparedFile bundle = staged(dir, "index.js", "new-bundle"); + NodeBundle.PreparedFile missing = new NodeBundle.PreparedFile(new File(dir, ".stage-gone/index.config.js"), md5("x")); + + assertNotNull(NodeBundle.install(dir, bundle, missing, "local:/new:c:d")); + assertFalse("已发布的 bundle 必须被撤销", new File(dir, "index.js").isFile()); + assertFalse("不能留下 stamp", new File(dir, "index.js.md5").isFile()); + assertFalse("不能留下来源键", new File(dir, "source.key").isFile()); + } + + private NodeBundle.PreparedFile staged(File dir, String name, String body) throws IOException { + File staging = new File(dir, ".stage-" + name); + staging.mkdirs(); + File file = new File(staging, name); + Files.write(file.toPath(), body.getBytes(StandardCharsets.UTF_8)); + return new NodeBundle.PreparedFile(file, md5(body)); + } + + private void seedInstalled(File dir, String bundle, String config, String key) throws IOException { + Files.write(new File(dir, "index.js").toPath(), bundle.getBytes(StandardCharsets.UTF_8)); + Files.write(new File(dir, "index.config.js").toPath(), config.getBytes(StandardCharsets.UTF_8)); + Files.write(new File(dir, "index.js.md5").toPath(), md5(bundle).getBytes(StandardCharsets.UTF_8)); + Files.write(new File(dir, "index.config.js.md5").toPath(), md5(config).getBytes(StandardCharsets.UTF_8)); + Files.write(new File(dir, "source.key").toPath(), key.getBytes(StandardCharsets.UTF_8)); + } + + private static boolean hasTempLeftover(File dir) { + File[] files = dir.listFiles(); + if (files == null) return false; + for (File file : files) if (file.getName().endsWith(".tmp")) return true; + return false; + } + + private File pack(String name, String bundle, String config) throws IOException { + File dir = folder.newFolder(name); + Files.write(new File(dir, "index.js").toPath(), bundle.getBytes(StandardCharsets.UTF_8)); + Files.write(new File(dir, "index.config.js").toPath(), config.getBytes(StandardCharsets.UTF_8)); + Files.write(new File(dir, "index.js.md5").toPath(), md5(bundle).getBytes(StandardCharsets.UTF_8)); + return dir; + } + + private File zip(String name, String marker, String bundle, String config) throws IOException { + File file = new File(folder.getRoot(), name); + try (java.util.zip.ZipOutputStream out = new java.util.zip.ZipOutputStream(new java.io.FileOutputStream(file))) { + entry(out, "index.js.md5", marker); + entry(out, "index.js", bundle); + entry(out, "index.config.js", config); + } + return file; + } + + private static void entry(java.util.zip.ZipOutputStream out, String name, String body) throws IOException { + out.putNextEntry(new java.util.zip.ZipEntry(name)); + out.write(body.getBytes(StandardCharsets.UTF_8)); + out.closeEntry(); + } + + private static String read(File file) throws IOException { + return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8).trim(); + } + + private static String md5(String text) { + try { + byte[] digest = java.security.MessageDigest.getInstance("MD5").digest(text.getBytes(StandardCharsets.UTF_8)); + StringBuilder value = new StringBuilder(); + for (byte item : digest) value.append(String.format(java.util.Locale.ROOT, "%02x", item & 0xff)); + return value.toString(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } +} diff --git a/app/src/test/java/com/fongmi/android/tv/node/NodeLocalBundleTest.java b/app/src/test/java/com/fongmi/android/tv/node/NodeLocalBundleTest.java index 2ba252a976..871f2fcb3a 100644 --- a/app/src/test/java/com/fongmi/android/tv/node/NodeLocalBundleTest.java +++ b/app/src/test/java/com/fongmi/android/tv/node/NodeLocalBundleTest.java @@ -8,9 +8,11 @@ import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.util.Locale; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -32,6 +34,69 @@ public class NodeLocalBundleTest { assertEquals("目录里有 index.js.md5 就是本地包", dir, NodeBundle.localDir(dir.getAbsolutePath(), null)); } + @Test + public void md5MarkersMustContainOnlyHexDigits() { + assertTrue(NodeBundle.isMd5("b24cea4ad00908b04d0fbe8d0a01999e")); + assertFalse("校验值不能只看长度", NodeBundle.isMd5("b24cea4ad00908b04d0fbe8d0a01999g")); + assertFalse(NodeBundle.isMd5("b24cea4ad00908b04d0fbe8d0a01999")); + } + + /** + * {@code md5sum > index.js.md5} 生成的是「{@code index.js}」两段格式。 + * 只按整行判定会把这种包判成「校验值无效」,而它在改动前是能正常安装的。 + */ + @Test + public void markerAcceptsMd5sumOutputFormat() throws Exception { + String hash = "b24cea4ad00908b04d0fbe8d0a01999e"; + java.lang.reflect.Method marker = NodeBundle.class.getDeclaredMethod("marker", String.class); + marker.setAccessible(true); + + assertEquals("裸校验值要原样返回", hash, marker.invoke(null, hash)); + assertEquals("md5sum 双空格格式要取第一段", hash, marker.invoke(null, hash + " index.js")); + assertEquals("单空格格式也要支持", hash, marker.invoke(null, hash + " index.js")); + assertEquals("制表符分隔同样处理", hash, marker.invoke(null, hash + "\tindex.js")); + assertEquals("前后换行/空白要去掉", hash, marker.invoke(null, " " + hash + "\n")); + assertEquals("", marker.invoke(null, "")); + assertEquals("", marker.invoke(null, (Object) null)); + } + + @Test + public void localSourceKeyChangesWhenBundleContentChanges() throws IOException { + File dir = pack("fingerprint"); + String before = NodeBundle.sourceKey(dir.getAbsolutePath(), null); + Files.write(new File(dir, "index.js").toPath(), "module.exports={changed:true};".getBytes(StandardCharsets.UTF_8)); + String after = NodeBundle.sourceKey(dir.getAbsolutePath(), null); + + assertTrue("本地包内容变化后不能继续使用旧来源指纹", before.startsWith("local:") && !before.equals(after)); + } + + /** config 变了、index.js 没变,也必须换身份——否则改完配置仍跑旧 config。 */ + @Test + public void localSourceKeyChangesWhenConfigContentChanges() throws IOException { + File dir = pack("config-fingerprint"); + String before = NodeBundle.sourceKey(dir.getAbsolutePath(), null); + Files.write(new File(dir, "index.config.js").toPath(), "module.exports={site:2};".getBytes(StandardCharsets.UTF_8)); + + assertNotEquals("config 内容变化也必须换来源身份", before, NodeBundle.sourceKey(dir.getAbsolutePath(), null)); + } + + /** 本地来源永远不能与远端来源撞身份,否则换源时会复用彼此的运行缓存。 */ + @Test + public void localAndRemoteKeysNeverCollide() throws IOException { + File dir = pack("namespaced"); + String local = NodeBundle.sourceKey(dir.getAbsolutePath(), null); + String md5 = "b24cea4ad00908b04d0fbe8d0a01999e"; + String remote = NodeBundle.remoteSourceKey("https://host/cat/index.js.md5", md5, md5); + + assertTrue("本地身份必须有 local: 前缀", local.startsWith("local:")); + assertTrue("远端身份必须有 remote: 前缀", remote.startsWith("remote:")); + assertNotEquals("本地与远端身份不能相等", local, remote); + assertFalse("本地身份不能被误判成某个远端地址的缓存", + NodeBundle.installedIsRemoteOf(local, "https://host/cat/index.js.md5")); + assertEquals("非法地址不能产出身份", "", NodeBundle.sourceKey("", null)); + assertEquals("", NodeBundle.sourceKey(null, null)); + } + @Test public void recognizesFileInsidePackageAndReturnsItsDirectory() throws IOException { File dir = pack("pkg"); @@ -86,6 +151,69 @@ public class NodeLocalBundleTest { assertFalse(NodeBundle.isRemote("")); } + /** + * 远端身份必须带上服务端公布的校验值。只用 URL 的话,服务端原地更新 bundle + * (地址不变、md5 变了)后仍会命中「同一来源」,继续跑旧 JS 直到进程被杀。 + */ + @Test + public void remoteSourceKeyTracksServerPublishedChecksums() { + String url = "https://host/cat/index.js.md5"; + String a = "b24cea4ad00908b04d0fbe8d0a01999e"; + String b = "ffffffffffffffffffffffffffffffff"; + + String first = NodeBundle.remoteSourceKey(url, a, a); + assertTrue("远端身份要有 remote: 前缀", first.startsWith("remote:")); + assertNotEquals("bundle 校验值变化必须换身份", first, NodeBundle.remoteSourceKey(url, b, a)); + assertNotEquals("config 校验值变化必须换身份", first, NodeBundle.remoteSourceKey(url, a, b)); + assertEquals("同样的校验值必须得到同样的身份", first, NodeBundle.remoteSourceKey(url, a, a)); + assertEquals("带不带 .md5 后缀是同一个来源", + first, NodeBundle.remoteSourceKey("https://host/cat/index.js", a, a)); + assertEquals("校验值大小写不该影响身份", first, NodeBundle.remoteSourceKey(url, a.toUpperCase(Locale.ROOT), a)); + } + + /** 拿不到校验值时必须返回空身份,让上层走「重新准备」而不是凭地址复用。 */ + @Test + public void remoteSourceKeyIsEmptyWithoutValidChecksums() { + String url = "https://host/cat/index.js.md5"; + String ok = "b24cea4ad00908b04d0fbe8d0a01999e"; + assertEquals("", NodeBundle.remoteSourceKey(url, "", ok)); + assertEquals("", NodeBundle.remoteSourceKey(url, ok, "")); + assertEquals("非法 md5 不能产出身份", "", NodeBundle.remoteSourceKey(url, "TODO", ok)); + assertEquals("", NodeBundle.remoteSourceKey(url, null, ok)); + } + + /** + * 断网降级只允许复用「确实属于该地址」的缓存。前缀比较必须带分隔符, + * 否则 {@code https://host/cat} 的缓存会被 {@code https://host/cat2} 命中。 + */ + @Test + public void offlineFallbackOnlyAcceptsCacheBelongingToTheSameUrl() { + String md5 = "b24cea4ad00908b04d0fbe8d0a01999e"; + String installed = NodeBundle.remoteSourceKey("https://host/cat/index.js.md5", md5, md5); + + assertTrue(NodeBundle.installedIsRemoteOf(installed, "https://host/cat/index.js.md5")); + assertTrue("带不带 .md5 后缀是同一个来源", NodeBundle.installedIsRemoteOf(installed, "https://host/cat/index.js")); + assertFalse("别的地址不能复用这份缓存", NodeBundle.installedIsRemoteOf(installed, "https://host/other/index.js.md5")); + assertFalse("前缀相同但不是同一地址也不行", NodeBundle.installedIsRemoteOf(installed, "https://host/cat/index.js2")); + assertFalse("本地来源不能被当成远端缓存", NodeBundle.installedIsRemoteOf("local:/sdcard/pkg:a:b", "https://host/cat/index.js.md5")); + assertFalse(NodeBundle.installedIsRemoteOf("", "https://host/cat/index.js.md5")); + } + + /** + * 旧版本落盘的来源键没有内容指纹({@code remote:})。不认它的话,老用户升级后在 + * 断网状态下会被判成「没有该地址的缓存」,尽管两个文件都完好躺在磁盘上。 + */ + @Test + public void offlineFallbackStillAcceptsLegacySourceKeys() { + String url = "https://host/cat/index.js.md5"; + assertTrue("旧格式(无内容指纹)必须仍被认作该地址的缓存", + NodeBundle.installedIsRemoteOf("remote:https://host/cat/index.js", url)); + assertFalse("旧格式同样不能跨地址复用", + NodeBundle.installedIsRemoteOf("remote:https://host/other/index.js", url)); + assertFalse("前缀是子串但不是同一地址也不行", + NodeBundle.installedIsRemoteOf("remote:https://host/cat/index.js2", url)); + } + @Test public void rejectsRemoteAndMissingPaths() throws IOException { assertNull(NodeBundle.localDir(null, null)); @@ -102,6 +230,64 @@ public class NodeLocalBundleTest { assertNull("zip 不是解压目录,localDir 不该认它", NodeBundle.localDir(zip.getAbsolutePath(), null)); } + /** + * 指纹和安装必须用同一个 root 解析路径。相对地址在 {@code /path} 和 {@code /path} + * 两处都存在时,若一边传 null 一边传 root,就会「算 A 包的指纹、装 B 包的内容」。 + */ + @Test + public void sourceKeyResolvesPathsWithTheSameRootAsInstall() throws IOException { + File root = folder.newFolder("sdcard"); + // 带随机后缀,避免依赖开发机上恰好没有 /Download/pkg(resolve 的最后一级回退是 "/" + path) + String relative = "Download/pkg-" + java.util.UUID.randomUUID(); + File dir = new File(root, relative); + write(dir); + + String viaRoot = NodeBundle.sourceKey(relative, root); + assertTrue("相对路径要能按 root 解析出指纹", viaRoot.startsWith("local:")); + assertTrue("指纹必须指向 root 下解析到的那个包", viaRoot.contains(dir.getCanonicalPath())); + assertEquals("同一个 root 解析同一个地址必须稳定", viaRoot, NodeBundle.sourceKey(relative, root)); + assertEquals("换掉 root 后该相对路径不再存在,不能仍然返回旧指纹", + "", NodeBundle.sourceKey(relative, folder.newFolder("other"))); + } + + /** 目录和 zip 是同一份包的两种形态,来源身份必须都带内容指纹。 */ + @Test + public void zipSourceKeyCoversContentNotJustPath() throws IOException { + File zip = zip("keyed.zip", true); + String key = NodeBundle.sourceKey(zip.getAbsolutePath(), null); + assertTrue("zip 也要有本地来源指纹", key.startsWith("local:")); + assertTrue("指纹必须包含 zip 自身路径", key.contains(zip.getCanonicalPath())); + + // 同一个路径重新打一份内容不同的 zip:身份必须变,否则改完包仍跑旧 JS。 + try (java.util.zip.ZipOutputStream out = new java.util.zip.ZipOutputStream(new java.io.FileOutputStream(zip))) { + entry(out, "index.js.md5", "b24cea4ad00908b04d0fbe8d0a01999e"); + entry(out, "index.js", "module.exports={changed:true};"); + entry(out, "index.config.js", "module.exports={};"); + } + assertNotEquals("zip 内容变化必须换来源身份", key, NodeBundle.sourceKey(zip.getAbsolutePath(), null)); + } + + /** marker 内容不是合法 md5 的 zip 不能产出来源身份,否则伪造 marker 就能命中缓存。 */ + @Test + public void zipWithBadMarkerHasNoSourceKey() throws IOException { + File file = new File(folder.getRoot(), "bad.zip"); + try (java.util.zip.ZipOutputStream out = new java.util.zip.ZipOutputStream(new java.io.FileOutputStream(file))) { + entry(out, "index.js.md5", "TODO"); + entry(out, "index.js", "module.exports={};"); + entry(out, "index.config.js", "module.exports={};"); + } + assertEquals("marker 非法时不能算出来源身份", "", NodeBundle.sourceKey(file.getAbsolutePath(), null)); + } + + /** 缺 index.config.js 的目录不是完整包,不能算出来源身份。 */ + @Test + public void directoryMissingConfigHasNoSourceKey() throws IOException { + File dir = folder.newFolder("partial"); + Files.write(new File(dir, "index.js.md5").toPath(), "b24cea4ad00908b04d0fbe8d0a01999e".getBytes(StandardCharsets.UTF_8)); + Files.write(new File(dir, "index.js").toPath(), "module.exports={};".getBytes(StandardCharsets.UTF_8)); + assertEquals("缺 config 的包不能算出来源身份", "", NodeBundle.sourceKey(dir.getAbsolutePath(), null)); + } + @Test public void rejectsUnrelatedZipAndNonZipFile() throws IOException { assertNull("不含 index.js.md5 的 zip 只是普通压缩包", NodeBundle.localZip(zip("other.zip", false).getAbsolutePath(), null)); diff --git a/app/src/test/java/com/fongmi/android/tv/node/NodePortSelectionTest.java b/app/src/test/java/com/fongmi/android/tv/node/NodePortSelectionTest.java index ba386363ad..28ffe8e98c 100644 --- a/app/src/test/java/com/fongmi/android/tv/node/NodePortSelectionTest.java +++ b/app/src/test/java/com/fongmi/android/tv/node/NodePortSelectionTest.java @@ -114,6 +114,104 @@ public class NodePortSelectionTest { assertTrue("CatSource 等待必须有时间上限", source.contains("latch.await(60, TimeUnit.SECONDS)")); } + @Test + public void timeoutInvalidatesLateRepliesAndKeepsTheStoppingServiceVisible() throws IOException { + String runtime = read("com/fongmi/android/tv/node/NodeRuntime.java"); + int timeout = runtime.indexOf("private static synchronized void timeout("); + int stop = runtime.indexOf("NodeService.stop(context);", timeout); + int invalidate = runtime.indexOf("START_GENERATION.incrementAndGet();", timeout); + int clearUrl = runtime.indexOf("servingUrl = \"\";", timeout); + int nextMethod = runtime.indexOf("private static boolean same(", timeout); + + assertTrue("timeout must invalidate the old generation before stopping its service", + timeout >= 0 && invalidate > timeout && invalidate < stop); + assertTrue("timeout must keep the stopping service visible until the next start waits for process death", + clearUrl < timeout || clearUrl > nextMethod); + assertTrue("start and timeout must serialize the state transition so a retry cannot race the generation invalidation", + runtime.contains("public static synchronized void start(") + && runtime.contains("private static synchronized void timeout(")); + } + + @Test + public void nodeServiceStopsAfterReportingStartupError() throws IOException { + String service = read("com/fongmi/android/tv/node/NodeService.java"); + int method = service.indexOf("private void sendError("); + int send = service.indexOf("reply.send(msg)", method); + int stop = service.indexOf("stopSelf();", method); + + assertTrue("报告启动错误后必须停止前台 Service,不能让失败的 :node 常驻", + method >= 0 && send > method && stop > send); + } + + @Test + public void staleSuppressionCreditsAccumulateAcrossReaderClosures() throws IOException { + String router = read("com/fongmi/android/tv/ui/novel/NovelRouter.java"); + assertTrue("多次关闭时不能覆盖尚未消费的迟到结果额度", + router.contains("staleChapterResults.addAndGet(pending);") + && router.contains("Math.max(staleUntil, readerClosedAt + PENDING_CHAPTER_TTL)")); + } + + /** + * 复用运行中的 Node 必须过 {@code servesCurrentSource}(比完整来源身份), + * 而不是自己拼一个只看地址的条件——后者在服务端原地更新 bundle 后会继续跑旧 JS。 + * {@code servingSourceKey} 只能在 READY 时从磁盘读实际安装值,不能提前写请求值。 + */ + @Test + public void runtimeReuseGoesThroughFullSourceIdentityCheck() throws IOException { + String runtime = read("com/fongmi/android/tv/node/NodeRuntime.java"); + int reuse = runtime.indexOf("NodeBundle.servesCurrentSource(url, servingSourceKey)"); + int start = runtime.indexOf("if (!STARTING.compareAndSet(false, true))"); + + assertTrue("复用判定必须调用 servesCurrentSource", reuse >= 0); + assertTrue("复用判定必须在真正启动之前", start > reuse); + + // 枚举所有赋值,而不是排除某一种拼写:右值只允许「清空」或「从磁盘读实际安装值」。 + // 否则任何新写法(比如把请求侧算出的 key 直接塞进来)都能绕过检查。 + java.util.List assigned = new java.util.ArrayList<>(); + java.util.regex.Matcher matcher = java.util.regex.Pattern + .compile("servingSourceKey\\s*=\\s*([^;]+);").matcher(runtime); + while (matcher.find()) assigned.add(matcher.group(1).trim()); + + assertTrue("必须有 servingSourceKey 的赋值", !assigned.isEmpty()); + assertTrue("已安装来源键只能在 READY 后从磁盘读取", + assigned.contains("NodeBundle.installedSourceKey(App.get())")); + for (String value : assigned) { + assertTrue("servingSourceKey 不能被赋成 " + value + "(只允许 \"\" 或 installedSourceKey)", + value.equals("\"\"") || value.equals("NodeBundle.installedSourceKey(App.get())")); + } + } + + @Test + public void bundleMetadataAndFirstDownloadsUseBoundedFailClosedValidation() throws IOException { + String bundle = read("com/fongmi/android/tv/node/NodeBundle.java"); + int metadata = bundle.indexOf("private static String remoteMd5(String url)"); + int download = bundle.indexOf("private static PreparedFile download("); + + assertTrue("远端 md5 响应必须限长读取,避免错误响应造成无界内存占用", + metadata >= 0 + && bundle.indexOf("MAX_METADATA_BYTES", metadata) > metadata + && bundle.indexOf("readLimited", metadata) > metadata + && !bundle.contains("OkHttp.string(md5Url(url))")); + assertTrue("首次下载必须要求有效 md5,不能在元数据失败时接受任意响应", + download >= 0 + && bundle.indexOf("if (!isMd5(expected))", download) > download + && bundle.indexOf("if (isMd5(expected) && !expected.equalsIgnoreCase(actual))", download) > download); + } + + /** + * {@code ByteArrayOutputStream.toString(Charset)} 是 API 33 才有的重载,而 minSdk 是 24, + * {@code desugar_jdk_libs_nio} 也不覆盖 {@code java.io.ByteArrayOutputStream}。用了它, + * Android 13 以下一进 readLimited 就 NoSuchMethodError——而 source.key/stamp 的读取全走这里, + * 等于整个猫源功能在旧系统上必崩。单元测试跑在 JVM 上,测不出来,只能锁源码。 + */ + @Test + public void textDecodingStaysWithinMinSdkApiSurface() throws IOException { + String bundle = read("com/fongmi/android/tv/node/NodeBundle.java"); + assertTrue("readLimited 必须用 API 24 就有的 toString(String),不能用 API 33 的 toString(Charset)", + bundle.contains("output.toString(StandardCharsets.UTF_8.name())") + && !bundle.contains("output.toString(StandardCharsets.UTF_8)")); + } + @Test public void readPortsParsesListAndTolueratesLegacySingleValue() throws Exception { assertEquals("多端口按逗号解析,顺序保持落盘顺序(猫源在前)", diff --git a/app/src/test/java/com/fongmi/android/tv/player/DolbyVisionFormatLabelTest.java b/app/src/test/java/com/fongmi/android/tv/player/DolbyVisionFormatLabelTest.java index 4bda31876c..93869a1d46 100644 --- a/app/src/test/java/com/fongmi/android/tv/player/DolbyVisionFormatLabelTest.java +++ b/app/src/test/java/com/fongmi/android/tv/player/DolbyVisionFormatLabelTest.java @@ -31,7 +31,7 @@ public class DolbyVisionFormatLabelTest { @Test public void p81ConversionMarksUpgradeBesideTheSourceCodec() { PlayerEngine.VideoPlaybackDetails details = new PlayerEngine.VideoPlaybackDetails( - "dvhe.07.06", 7, 6, "dvhe.08.06", + "dvhe.07.06", 8, 6, "dvhe.08.06", "c2.qti.hevc.decoder", "", null, false, true); assertEquals("Dolby Vision DV.07", diff --git a/app/src/test/java/com/fongmi/android/tv/player/engine/MpvAudioCapabilitiesTest.java b/app/src/test/java/com/fongmi/android/tv/player/engine/MpvAudioCapabilitiesTest.java index 2baac7badd..f9a27eff84 100644 --- a/app/src/test/java/com/fongmi/android/tv/player/engine/MpvAudioCapabilitiesTest.java +++ b/app/src/test/java/com/fongmi/android/tv/player/engine/MpvAudioCapabilitiesTest.java @@ -2,6 +2,9 @@ package com.fongmi.android.tv.player.engine; import androidx.media3.common.C; +import android.media.AudioFormat; +import android.os.Build; + import org.junit.Test; import java.util.Set; @@ -50,4 +53,43 @@ public class MpvAudioCapabilitiesTest { assertEquals("ac3,eac3,dts,dts-hd,truehd", MpvAudioCapabilities.getAudioSpdifCodecs(advertised, codec -> true)); } + + @Test + public void keepsTrueHdOnSevenPointOneForOlderAndroidTvCompatibility() { + assertEquals( + java.util.List.of(new MpvAudioCapabilities.CarrierFormat( + 192000, AudioFormat.CHANNEL_OUT_7POINT1_SURROUND)), + MpvAudioCapabilities.getCarrierFormats("truehd", Build.VERSION_CODES.R)); + } + + @Test + public void probesBothDtsHdCarrierLayoutsOnAndroidTwelveAndNewer() { + assertEquals( + java.util.List.of( + new MpvAudioCapabilities.CarrierFormat( + 192000, AudioFormat.CHANNEL_OUT_STEREO), + new MpvAudioCapabilities.CarrierFormat( + 192000, AudioFormat.CHANNEL_OUT_7POINT1_SURROUND)), + MpvAudioCapabilities.getCarrierFormats("dts-hd", Build.VERSION_CODES.S)); + } + + @Test + public void keepsDtsHdStereoProbeBeforeAndroidTwelve() { + assertEquals( + java.util.List.of(new MpvAudioCapabilities.CarrierFormat( + 192000, AudioFormat.CHANNEL_OUT_STEREO)), + MpvAudioCapabilities.getCarrierFormats("dts-hd", Build.VERSION_CODES.R)); + } + + @Test + public void preservesExistingCoreAndEnhancedCarrierRates() { + assertEquals( + java.util.List.of(new MpvAudioCapabilities.CarrierFormat( + 48000, AudioFormat.CHANNEL_OUT_STEREO)), + MpvAudioCapabilities.getCarrierFormats("ac3", Build.VERSION_CODES.VANILLA_ICE_CREAM)); + assertEquals( + java.util.List.of(new MpvAudioCapabilities.CarrierFormat( + 192000, AudioFormat.CHANNEL_OUT_STEREO)), + MpvAudioCapabilities.getCarrierFormats("eac3", Build.VERSION_CODES.VANILLA_ICE_CREAM)); + } } diff --git a/app/src/test/java/com/fongmi/android/tv/player/engine/MpvDolbyVisionFallbackPolicyTest.java b/app/src/test/java/com/fongmi/android/tv/player/engine/MpvDolbyVisionFallbackPolicyTest.java index b37689629d..e91887c8f3 100644 --- a/app/src/test/java/com/fongmi/android/tv/player/engine/MpvDolbyVisionFallbackPolicyTest.java +++ b/app/src/test/java/com/fongmi/android/tv/player/engine/MpvDolbyVisionFallbackPolicyTest.java @@ -2,8 +2,12 @@ package com.fongmi.android.tv.player.engine; import androidx.media3.mpvplayer.MpvPlayer; +import com.fongmi.android.tv.player.mpv.MpvAutoOutputPolicy; +import com.fongmi.android.tv.setting.PlaybackPerformanceSetting; + import org.junit.Test; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -41,6 +45,33 @@ public class MpvDolbyVisionFallbackPolicyTest { details(7), true, false)); } + @Test + public void nativeDv7AlwaysWinsOverFallbackPreference() { + assertEquals(MpvPlayerEngine.DV7_PRESERVE, + MpvPlayerEngine.selectDv7Handling( + MpvAutoOutputPolicy.DolbyVisionSupport.SUPPORTED, + MpvAutoOutputPolicy.DolbyVisionSupport.SUPPORTED, + PlaybackPerformanceSetting.DV7_HANDLING_HDR10)); + } + + @Test + public void supportedP81UsesP81Preference() { + assertEquals(MpvPlayerEngine.DV7_P81, + MpvPlayerEngine.selectDv7Handling( + MpvAutoOutputPolicy.DolbyVisionSupport.UNSUPPORTED, + MpvAutoOutputPolicy.DolbyVisionSupport.SUPPORTED, + PlaybackPerformanceSetting.DV7_HANDLING_P81)); + } + + @Test + public void unsupportedP81FallsBackToHdr10() { + assertEquals(MpvPlayerEngine.DV7_HDR10, + MpvPlayerEngine.selectDv7Handling( + MpvAutoOutputPolicy.DolbyVisionSupport.UNSUPPORTED, + MpvAutoOutputPolicy.DolbyVisionSupport.UNSUPPORTED, + PlaybackPerformanceSetting.DV7_HANDLING_P81)); + } + private static MpvPlayer.VideoTrackDiagnostics details(int profile) { return new MpvPlayer.VideoTrackDiagnostics( "dvhe.0" + profile + ".06", profile, 6, diff --git a/app/src/test/java/com/fongmi/android/tv/player/exo/AutoLoadControlTest.java b/app/src/test/java/com/fongmi/android/tv/player/exo/AutoLoadControlTest.java index d9a93bc583..49a4bb9cdc 100644 --- a/app/src/test/java/com/fongmi/android/tv/player/exo/AutoLoadControlTest.java +++ b/app/src/test/java/com/fongmi/android/tv/player/exo/AutoLoadControlTest.java @@ -10,6 +10,59 @@ import static org.junit.Assert.assertTrue; public class AutoLoadControlTest { + @Test + public void seekRecoveryUsesMedia3UserActionThresholdWithoutWeakeningRebuffer() { + assertEquals(ExoPlaybackThresholdCoordinator.Episode.REBUFFER, + AutoLoadControl.playbackEpisode(true, true)); + assertEquals(ExoPlaybackThresholdCoordinator.Episode.SEEK, + AutoLoadControl.playbackEpisode(false, true)); + assertEquals(ExoPlaybackThresholdCoordinator.Episode.STARTUP, + AutoLoadControl.playbackEpisode(false, false)); + + ExoPlaybackThresholdPolicy.Decision policy = ExoPlaybackThresholdPolicy.resolve( + ExoPlaybackThresholdPolicy.Inputs.unknown()); + ExoPlaybackThresholdCoordinator.Selection criticalSeek = + new ExoPlaybackThresholdCoordinator.Selection( + com.fongmi.android.tv.player.PlaybackAutoContext.SessionToken.none(), + ExoPlaybackThresholdCoordinator.Episode.SEEK, + 8_000, + 15_000, + policy, + true, + ExoPlaybackThresholdCoordinator.Action.LOCK); + ExoPlaybackThresholdCoordinator.Selection conservativeRebuffer = + new ExoPlaybackThresholdCoordinator.Selection( + com.fongmi.android.tv.player.PlaybackAutoContext.SessionToken.none(), + ExoPlaybackThresholdCoordinator.Episode.REBUFFER, + 8_000, + 15_000, + policy, + true, + ExoPlaybackThresholdCoordinator.Action.LOCK); + + assertEquals(1_000, criticalSeek.thresholdMs()); + assertEquals(15_000, conservativeRebuffer.thresholdMs()); + } + + @Test + public void seekMarkerIsSessionBoundAndExpires() { + ExoPlaybackThresholdCoordinator coordinator = + new ExoPlaybackThresholdCoordinator(); + com.fongmi.android.tv.player.PlaybackAutoContext.SessionToken session = + new com.fongmi.android.tv.player.PlaybackAutoContext.SessionToken( + "p-seek-1", 1); + + coordinator.markSeek(session, 10_000); + + assertTrue(coordinator.isSeekPending(session, 10_001)); + assertFalse(coordinator.isSeekPending( + com.fongmi.android.tv.player.PlaybackAutoContext.SessionToken.none(), + 10_001)); + assertFalse(coordinator.isSeekPending( + session, + 10_000 + ExoPlaybackThresholdCoordinator.SEEK_RECOVERY_TIMEOUT_MS + 1)); + } + @Test public void usesAdaptiveVodRebufferThreshold() { assertFalse(AutoLoadControl.reachedAdaptiveThreshold(2_999_000, 1f, C.TIME_UNSET, 3_000)); diff --git a/app/src/test/java/com/fongmi/android/tv/player/exo/ExoDv5GpuMappingPolicyTest.java b/app/src/test/java/com/fongmi/android/tv/player/exo/ExoDv5GpuMappingPolicyTest.java new file mode 100644 index 0000000000..3de7a2bbab --- /dev/null +++ b/app/src/test/java/com/fongmi/android/tv/player/exo/ExoDv5GpuMappingPolicyTest.java @@ -0,0 +1,264 @@ +package com.fongmi.android.tv.player.exo; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class ExoDv5GpuMappingPolicyTest { + + @Test + public void detectsOnlyDolbyVisionProfile5() { + assertTrue(ExoDv5GpuMappingPolicy.isProfile5( + "video/dolby-vision", "dvhe.05.06")); + assertTrue(ExoDv5GpuMappingPolicy.isProfile5( + "video/dolby-vision", " DVH1.05.09 , hev1.2.4.L153.B0")); + assertFalse(ExoDv5GpuMappingPolicy.isProfile5( + "video/dolby-vision", "dvhe.07.06")); + assertFalse(ExoDv5GpuMappingPolicy.isProfile5( + "video/dolby-vision", "dvh1.08.06")); + assertFalse(ExoDv5GpuMappingPolicy.isProfile5( + "video/hevc", "dvhe.05.06")); + } + + @Test + public void nativeDolbyVisionWinsWhenDisplayAndDecoderAreAvailable() { + ExoDv5GpuMappingPolicy.Decision decision = decide(input() + .nativeDisplay(true) + .nativeDecoder(true) + .codecToneMapAccepted(true) + .rendererAvailable(true) + .probePassed(true) + .experimentEnabled(true)); + + assertRoute( + decision, + ExoDv5GpuMappingPolicy.Route.NATIVE_DOLBY_VISION, + ExoDv5GpuMappingPolicy.Reason.NATIVE_DOLBY_VISION_AVAILABLE); + } + + @Test + public void nativeDolbyVisionRequiresBothDisplayAndDecoder() { + ExoDv5GpuMappingPolicy.Decision decision = decide(input() + .nativeDisplay(true) + .rendererAvailable(true) + .probePassed(true) + .experimentEnabled(true)); + + assertRoute( + decision, + ExoDv5GpuMappingPolicy.Route.GPU_MAPPING, + ExoDv5GpuMappingPolicy.Reason.GPU_MAPPING_ELIGIBLE); + } + + @Test + public void acceptedCodecToneMapRequiresApi31AndPrecedesGpuMapping() { + ExoDv5GpuMappingPolicy.Decision accepted = decide(input() + .apiLevel(31) + .codecToneMapAccepted(true) + .rendererAvailable(true) + .probePassed(true) + .experimentEnabled(true)); + ExoDv5GpuMappingPolicy.Decision tooOld = decide(input() + .apiLevel(30) + .codecToneMapAccepted(true) + .rendererAvailable(true) + .probePassed(true) + .experimentEnabled(true)); + + assertRoute( + accepted, + ExoDv5GpuMappingPolicy.Route.CODEC_TONE_MAP, + ExoDv5GpuMappingPolicy.Reason.CODEC_TONE_MAP_ACCEPTED); + assertEquals(ExoDv5GpuMappingPolicy.Route.GPU_MAPPING, tooOld.route()); + } + + @Test + public void gpuMappingRequiresEveryRuntimeGate() { + ExoDv5GpuMappingPolicy.Decision decision = decide(input() + .rendererAvailable(true) + .probePassed(true) + .experimentEnabled(true)); + + assertRoute( + decision, + ExoDv5GpuMappingPolicy.Route.GPU_MAPPING, + ExoDv5GpuMappingPolicy.Reason.GPU_MAPPING_ELIGIBLE); + assertTrue(decision.usesGpuMapping()); + assertEquals(ExoDv5GpuMappingPolicy.Reason.NONE, + decision.gpuBlockReason()); + } + + @Test + public void drmNeverEntersGpuMapping() { + ExoDv5GpuMappingPolicy.Decision decision = decide(input() + .drmProtected(true) + .rendererAvailable(true) + .probePassed(true) + .experimentEnabled(true) + .legacyFallbackAllowed(true)); + + assertBlocked( + decision, ExoDv5GpuMappingPolicy.Reason.DRM_REQUIRES_SECURE_OUTPUT); + } + + @Test + public void gpuMappingReportsEachMissingCapability() { + assertBlocked(decide(input().apiLevel(25) + .rendererAvailable(true).probePassed(true).experimentEnabled(true)), + ExoDv5GpuMappingPolicy.Reason.API_BELOW_26); + assertBlocked(decide(input().rendererAvailable(true).probePassed(true)), + ExoDv5GpuMappingPolicy.Reason.EXPERIMENT_DISABLED); + assertBlocked(decide(input().tunneling(true) + .rendererAvailable(true).probePassed(true).experimentEnabled(true)), + ExoDv5GpuMappingPolicy.Reason.TUNNELING_UNSUPPORTED); + assertBlocked(decide(input().hevcDecoder(false) + .rendererAvailable(true).probePassed(true).experimentEnabled(true)), + ExoDv5GpuMappingPolicy.Reason.HEVC_DECODER_UNAVAILABLE); + assertBlocked(decide(input().probePassed(true).experimentEnabled(true)), + ExoDv5GpuMappingPolicy.Reason.RENDERER_UNAVAILABLE); + assertBlocked(decide(input().rendererAvailable(true).experimentEnabled(true)), + ExoDv5GpuMappingPolicy.Reason.VULKAN_AHB_PROBE_FAILED); + } + + @Test + public void legacyFallbackIsExplicitAndRetainsGpuBlockReason() { + ExoDv5GpuMappingPolicy.Decision allowed = decide(input() + .legacyFallbackAllowed(true)); + ExoDv5GpuMappingPolicy.Decision rejected = decide(input()); + + assertRoute( + allowed, + ExoDv5GpuMappingPolicy.Route.LEGACY_HDR10_FALLBACK, + ExoDv5GpuMappingPolicy.Reason.LEGACY_HDR10_FALLBACK_ALLOWED); + assertEquals( + ExoDv5GpuMappingPolicy.Reason.EXPERIMENT_DISABLED, + allowed.gpuBlockReason()); + assertBlocked( + rejected, ExoDv5GpuMappingPolicy.Reason.EXPERIMENT_DISABLED); + } + + @Test + public void nonProfile5NeverSelectsAnyFallback() { + ExoDv5GpuMappingPolicy.Decision decision = decide(input().profile5(false)); + + assertBlocked(decision, ExoDv5GpuMappingPolicy.Reason.NOT_PROFILE_5); + } + + private static void assertRoute( + ExoDv5GpuMappingPolicy.Decision decision, + ExoDv5GpuMappingPolicy.Route route, + ExoDv5GpuMappingPolicy.Reason reason) { + assertEquals(route, decision.route()); + assertEquals(reason, decision.reason()); + } + + private static void assertBlocked( + ExoDv5GpuMappingPolicy.Decision decision, + ExoDv5GpuMappingPolicy.Reason reason) { + assertRoute(decision, ExoDv5GpuMappingPolicy.Route.UNSUPPORTED, reason); + assertEquals(reason, decision.gpuBlockReason()); + assertFalse(decision.usesGpuMapping()); + } + + private static ExoDv5GpuMappingPolicy.Decision decide(InputBuilder input) { + return ExoDv5GpuMappingPolicy.decide(input.build()); + } + + private static InputBuilder input() { + return new InputBuilder(); + } + + private static final class InputBuilder { + + private boolean profile5 = true; + private boolean drmProtected; + private boolean nativeDisplay; + private boolean nativeDecoder; + private int apiLevel = 34; + private boolean codecToneMapAccepted; + private boolean hevcDecoder = true; + private boolean rendererAvailable; + private boolean probePassed; + private boolean experimentEnabled; + private boolean tunneling; + private boolean legacyFallbackAllowed; + + InputBuilder profile5(boolean value) { + profile5 = value; + return this; + } + + InputBuilder drmProtected(boolean value) { + drmProtected = value; + return this; + } + + InputBuilder nativeDisplay(boolean value) { + nativeDisplay = value; + return this; + } + + InputBuilder nativeDecoder(boolean value) { + nativeDecoder = value; + return this; + } + + InputBuilder apiLevel(int value) { + apiLevel = value; + return this; + } + + InputBuilder codecToneMapAccepted(boolean value) { + codecToneMapAccepted = value; + return this; + } + + InputBuilder hevcDecoder(boolean value) { + hevcDecoder = value; + return this; + } + + InputBuilder rendererAvailable(boolean value) { + rendererAvailable = value; + return this; + } + + InputBuilder probePassed(boolean value) { + probePassed = value; + return this; + } + + InputBuilder experimentEnabled(boolean value) { + experimentEnabled = value; + return this; + } + + InputBuilder tunneling(boolean value) { + tunneling = value; + return this; + } + + InputBuilder legacyFallbackAllowed(boolean value) { + legacyFallbackAllowed = value; + return this; + } + + ExoDv5GpuMappingPolicy.Input build() { + return new ExoDv5GpuMappingPolicy.Input( + profile5, + drmProtected, + nativeDisplay, + nativeDecoder, + apiLevel, + codecToneMapAccepted, + hevcDecoder, + rendererAvailable, + probePassed, + experimentEnabled, + tunneling, + legacyFallbackAllowed); + } + } +} diff --git a/app/src/test/java/com/fongmi/android/tv/player/exo/ExoDv5GpuRendererTest.java b/app/src/test/java/com/fongmi/android/tv/player/exo/ExoDv5GpuRendererTest.java new file mode 100644 index 0000000000..6b0ad426fb --- /dev/null +++ b/app/src/test/java/com/fongmi/android/tv/player/exo/ExoDv5GpuRendererTest.java @@ -0,0 +1,112 @@ +package com.fongmi.android.tv.player.exo; + +import org.junit.Test; + +import java.nio.ByteBuffer; +import java.util.List; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class ExoDv5GpuRendererTest { + + @Test + public void rendererFactoryRequiresExplicitOptInAndCompleteProbe() { + ExoDv5Native.Probe available = new ExoDv5Native.Probe( + true, ExoDv5Native.REQUIRED_CAPABILITIES, "available"); + ExoDv5Native.Probe unavailable = new ExoDv5Native.Probe( + false, ExoDv5Native.CAPABILITY_IMAGE_READER, "missing-capability"); + + assertFalse(ExoDv5GpuRendererFactory.shouldCreate(false, available)); + assertFalse(ExoDv5GpuRendererFactory.shouldCreate(true, unavailable)); + assertFalse(ExoDv5GpuRendererFactory.shouldCreate(true, null)); + assertTrue(ExoDv5GpuRendererFactory.shouldCreate(true, available)); + } + + @Test + public void frameActionWaitsSchedulesAndDropsWithinBounds() { + assertEquals( + ExoDv5VideoSink.FrameAction.WAIT, + ExoDv5VideoSink.frameAction(false, false, 0)); + assertEquals( + ExoDv5VideoSink.FrameAction.RENDER, + ExoDv5VideoSink.frameAction(false, true, 0)); + assertEquals( + ExoDv5VideoSink.FrameAction.WAIT, + ExoDv5VideoSink.frameAction(true, false, 50_001)); + assertEquals( + ExoDv5VideoSink.FrameAction.RENDER, + ExoDv5VideoSink.frameAction(true, false, 50_000)); + assertEquals( + ExoDv5VideoSink.FrameAction.RENDER, + ExoDv5VideoSink.frameAction(true, false, -30_000)); + assertEquals( + ExoDv5VideoSink.FrameAction.DROP, + ExoDv5VideoSink.frameAction(true, false, -30_001)); + } + + @Test + public void imageTimestampUsesPresentationTimeAndSaturates() { + assertEquals(1_234_000L, + ExoDv5VideoSink.imageTimestampNsFor(1_234)); + assertEquals(-1_234_000L, + ExoDv5VideoSink.imageTimestampNsFor(-1_234)); + assertEquals(Long.MAX_VALUE, + ExoDv5VideoSink.imageTimestampNsFor(Long.MAX_VALUE)); + assertEquals(Long.MIN_VALUE, + ExoDv5VideoSink.imageTimestampNsFor(Long.MIN_VALUE)); + } + + @Test + public void probeCapabilityBitsAreIndependentlyVisible() { + ExoDv5Native.Probe probe = new ExoDv5Native.Probe( + false, + ExoDv5Native.CAPABILITY_IMAGE_READER + | ExoDv5Native.CAPABILITY_AHB_IMPORT, + "missing-capability"); + + assertTrue(probe.has(ExoDv5Native.CAPABILITY_IMAGE_READER)); + assertTrue(probe.has(ExoDv5Native.CAPABILITY_AHB_IMPORT)); + assertFalse(probe.has(ExoDv5Native.CAPABILITY_YCBCR_CONVERSION)); + assertFalse(probe.has(ExoDv5Native.CAPABILITY_VULKAN_12)); + } + + @Test + public void emptyStatsExposeRenderOutcomeCounters() { + ExoDv5Native.Stats stats = ExoDv5Native.Stats.empty(); + + assertEquals(0, stats.renderedFrames()); + assertEquals(0, stats.renderFailures()); + } + + @Test + public void extractsRpuFromAnnexBWithoutMutatingInput() { + ByteBuffer sample = ByteBuffer.wrap(new byte[] { + 0, 0, 0, 1, 0x40, 1, 9, + 0, 0, 1, 0x7c, 1, 2, 3, + }); + sample.position(2); + int position = sample.position(); + + List rpus = ExoDv5GpuRenderer.findRpuNalus(sample); + + assertEquals(position, sample.position()); + assertEquals(1, rpus.size()); + assertArrayEquals(new byte[] {0x7c, 1, 2, 3}, rpus.get(0)); + } + + @Test + public void extractsRpuFromFourByteLengthPrefixedAccessUnit() { + ByteBuffer sample = ByteBuffer.wrap(new byte[] { + 0, 0, 0, 3, 0x40, 1, 9, + 0, 0, 0, 4, 0x7c, 1, 2, 3, + }); + + List rpus = ExoDv5GpuRenderer.findRpuNalus(sample); + + assertEquals(1, rpus.size()); + assertArrayEquals(new byte[] {0x7c, 1, 2, 3}, rpus.get(0)); + } +} diff --git a/app/src/test/java/com/fongmi/android/tv/player/exo/PreCachePolicyTest.java b/app/src/test/java/com/fongmi/android/tv/player/exo/PreCachePolicyTest.java index 637f8edbde..a61e4b6392 100644 --- a/app/src/test/java/com/fongmi/android/tv/player/exo/PreCachePolicyTest.java +++ b/app/src/test/java/com/fongmi/android/tv/player/exo/PreCachePolicyTest.java @@ -1,5 +1,7 @@ package com.fongmi.android.tv.player.exo; +import androidx.media3.common.Player; + import org.junit.Test; import static org.junit.Assert.assertEquals; @@ -33,6 +35,21 @@ public class PreCachePolicyTest { assertFalse(PreCachePolicy.hasSafeBuffer(7_999, true, 8_000, true)); } + @Test + public void seekSuppressionRequiresReadyIdleAndSafeBuffer() { + assertFalse(PreCache.shouldReleaseSeekPreloadSuppression(Player.STATE_BUFFERING, true, false, true)); + assertFalse(PreCache.shouldReleaseSeekPreloadSuppression(Player.STATE_READY, false, false, true)); + assertFalse(PreCache.shouldReleaseSeekPreloadSuppression(Player.STATE_READY, true, true, true)); + assertFalse(PreCache.shouldReleaseSeekPreloadSuppression(Player.STATE_READY, true, false, false)); + assertTrue(PreCache.shouldReleaseSeekPreloadSuppression(Player.STATE_READY, true, false, true)); + } + + @Test + public void repeatedPreloadFailuresOpenCircuitAtThreshold() { + assertFalse(PreCache.shouldOpenPreloadFailureCircuit(1)); + assertTrue(PreCache.shouldOpenPreloadFailureCircuit(2)); + } + @Test public void loadControlIdleFallbackStillKeepsAReserve() { assertFalse(PreCachePolicy.hasSafeBuffer(1_999, false, 5_000, false)); diff --git a/app/src/test/java/com/fongmi/android/tv/player/mpv/MpvAutoOutputPolicyTest.java b/app/src/test/java/com/fongmi/android/tv/player/mpv/MpvAutoOutputPolicyTest.java index 6c9938df50..dc7625033e 100644 --- a/app/src/test/java/com/fongmi/android/tv/player/mpv/MpvAutoOutputPolicyTest.java +++ b/app/src/test/java/com/fongmi/android/tv/player/mpv/MpvAutoOutputPolicyTest.java @@ -65,6 +65,26 @@ public class MpvAutoOutputPolicyTest { assertTrue(MpvAutoOutputPolicy.canEvaluateWithoutTracks(3840, 2160)); } + @Test + public void revealsSuccessfulDirectFrameBeforeTrackMetadataCompletes() { + assertTrue(MpvAutoOutputPolicy.canRevealDirectFrame( + true, false, true, true, 3840, 2160)); + } + + @Test + public void keepsShutterForUnprovenOrNonDirectOutput() { + assertFalse(MpvAutoOutputPolicy.canRevealDirectFrame( + true, false, false, true, 3840, 2160)); + assertFalse(MpvAutoOutputPolicy.canRevealDirectFrame( + true, false, true, false, 3840, 2160)); + assertFalse(MpvAutoOutputPolicy.canRevealDirectFrame( + true, false, true, true, 0, 2160)); + assertFalse(MpvAutoOutputPolicy.canRevealDirectFrame( + true, true, true, true, 3840, 2160)); + assertFalse(MpvAutoOutputPolicy.canRevealDirectFrame( + false, false, true, true, 3840, 2160)); + } + @Test public void subtitlesUseDirectOutputOverlay() { assertTrue(MpvAutoOutputPolicy.evaluate(3840, 2160, true, true, false, false).eligible()); diff --git a/app/src/test/java/com/fongmi/android/tv/player/mpv/MpvAutoRenderPolicyTest.java b/app/src/test/java/com/fongmi/android/tv/player/mpv/MpvAutoRenderPolicyTest.java new file mode 100644 index 0000000000..5521b4e571 --- /dev/null +++ b/app/src/test/java/com/fongmi/android/tv/player/mpv/MpvAutoRenderPolicyTest.java @@ -0,0 +1,89 @@ +package com.fongmi.android.tv.player.mpv; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class MpvAutoRenderPolicyTest { + + @Test + public void enablesVulkanForUnsupportedNativeDv5() { + assertDecision(MpvAutoRenderPolicy.Action.ENABLE_VULKAN, + "dv5-gpu-mapping-vulkan", true, true, 5, + MpvAutoOutputPolicy.DolbyVisionSupport.UNSUPPORTED, + true, true, false, false); + } + + @Test + public void preservesManualRenderOverride() { + assertDecision(MpvAutoRenderPolicy.Action.KEEP, "render-overridden", + false, true, 5, + MpvAutoOutputPolicy.DolbyVisionSupport.UNSUPPORTED, + true, true, false, false); + } + + @Test + public void preservesNativeOrUnknownDolbyVisionRouting() { + assertDecision(MpvAutoRenderPolicy.Action.KEEP, "native-dv5-supported", + true, true, 5, + MpvAutoOutputPolicy.DolbyVisionSupport.SUPPORTED, + true, true, false, false); + assertDecision(MpvAutoRenderPolicy.Action.KEEP, "native-dv5-unknown", + true, true, 5, + MpvAutoOutputPolicy.DolbyVisionSupport.UNKNOWN, + true, true, false, false); + } + + @Test + public void preservesNonDv5AndSoftwareDecode() { + assertDecision(MpvAutoRenderPolicy.Action.KEEP, "not-dv5", + true, true, 7, + MpvAutoOutputPolicy.DolbyVisionSupport.UNSUPPORTED, + true, true, false, false); + assertDecision(MpvAutoRenderPolicy.Action.KEEP, "software-decode", + true, false, 5, + MpvAutoOutputPolicy.DolbyVisionSupport.UNSUPPORTED, + true, true, false, false); + } + + @Test + public void requiresBothVulkanCapabilities() { + assertDecision(MpvAutoRenderPolicy.Action.KEEP, "vulkan-unavailable", + true, true, 5, + MpvAutoOutputPolicy.DolbyVisionSupport.UNSUPPORTED, + false, true, false, false); + assertDecision(MpvAutoRenderPolicy.Action.KEEP, "vulkan-unavailable", + true, true, 5, + MpvAutoOutputPolicy.DolbyVisionSupport.UNSUPPORTED, + true, false, false, false); + } + + @Test + public void doesNotRebuildAnActiveOrFailedItem() { + assertDecision(MpvAutoRenderPolicy.Action.KEEP, "already-vulkan", + true, true, 5, + MpvAutoOutputPolicy.DolbyVisionSupport.UNSUPPORTED, + true, true, true, false); + assertDecision(MpvAutoRenderPolicy.Action.KEEP, "item-fallback", + true, true, 5, + MpvAutoOutputPolicy.DolbyVisionSupport.UNSUPPORTED, + true, true, false, true); + } + + private static void assertDecision(MpvAutoRenderPolicy.Action action, + String reason, + boolean renderAutomatic, + boolean hardDecode, + int profile, + MpvAutoOutputPolicy.DolbyVisionSupport support, + boolean nativeVulkan, + boolean deviceVulkan, + boolean currentlyVulkan, + boolean disabledForItem) { + MpvAutoRenderPolicy.Decision decision = MpvAutoRenderPolicy.evaluate( + renderAutomatic, hardDecode, profile, support, + nativeVulkan, deviceVulkan, currentlyVulkan, disabledForItem); + assertEquals(action, decision.action()); + assertEquals(reason, decision.reason()); + } +} diff --git a/app/src/test/java/com/fongmi/android/tv/setting/AppBrandingContractTest.java b/app/src/test/java/com/fongmi/android/tv/setting/AppBrandingContractTest.java index 250b788f4e..eb8b90ef11 100644 --- a/app/src/test/java/com/fongmi/android/tv/setting/AppBrandingContractTest.java +++ b/app/src/test/java/com/fongmi/android/tv/setting/AppBrandingContractTest.java @@ -52,7 +52,8 @@ public class AppBrandingContractTest { assertTrue(appBranding.contains("public static void applyLogo(@NonNull ImageView view)")); assertTrue(appBranding.contains("view.setImageDrawable(logoDrawable(view.getContext()));")); assertTrue(appBranding.contains("getActivityIcon(launcherIntent(context).getComponent())")); - assertFalse(appBranding.contains("Glide")); + // 首帧落品牌图标后要让配置自带的线路 logo 覆盖上来,否则自定义线路图标失效 + assertTrue(appBranding.contains("ImgUtil.logo(view, logo);")); assertTrue(appBranding.contains("Prefers.getPrefers().edit().putInt(ICON_KEY, normalizeIconMode(mode)).commit();")); assertFalse(appBranding.contains("ICON_CUSTOM")); assertFalse(appBranding.contains("Shortcut")); @@ -67,6 +68,15 @@ public class AppBrandingContractTest { assertFalse(mobile.contains("ImgUtil.logo(mBinding.logo);")); } + @Test + public void homeTitlePrefersSiteAndConfigNameOverAppName() throws Exception { + String appBranding = read("app/src/main/java/com/fongmi/android/tv/setting/AppBranding.java"); + + // 固定返回应用名会让所有站源都显示成「默影视」 + assertTrue(appBranding.contains("if (homeName != null && !homeName.trim().isEmpty()) return homeName;")); + assertTrue(appBranding.contains("if (configName != null && !configName.trim().isEmpty()) return configName;")); + } + @Test public void homeLogoIsBrandedBeforeFirstFrame() throws Exception { String layout = read("app/src/leanback/res/layout/activity_home.xml"); diff --git a/app/src/test/java/com/fongmi/android/tv/ui/activity/PlaybackOwnershipSourceTest.java b/app/src/test/java/com/fongmi/android/tv/ui/activity/PlaybackOwnershipSourceTest.java new file mode 100644 index 0000000000..47e3e10215 --- /dev/null +++ b/app/src/test/java/com/fongmi/android/tv/ui/activity/PlaybackOwnershipSourceTest.java @@ -0,0 +1,185 @@ +package com.fongmi.android.tv.ui.activity; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; + +/** + * 播放会话的归属令牌必须在会话内保持稳定。 + * + *

getPlaybackKey() 由子类从 intent 现算,而 intent 的 id 会在起播之后被详情结果改写 + * (TMDB 富集回来的 vodId,见 VideoActivity#updateVod)。播放器里的 key 是起播那一刻固化进 + * PlaySpec 的,之后无从更改。两者一旦不等,isOwner() 便永久为 false,同时打断三条链: + * STATE_READY 不再下发(转圈不收)、每秒进度采样直接返回(进度不落库、刷新回起点)、 + * 切集因 PlaybackService#isNavigationOwner 失配而不派发。 + */ +public class PlaybackOwnershipSourceTest { + + private static final String PLAYBACK = "app/src/main/java/com/fongmi/android/tv/ui/activity/PlaybackActivity.java"; + + @Test + public void ownershipReadsThePinnedSessionKeyNotTheLiveIntent() throws Exception { + String source = read(PLAYBACK); + + int owner = source.indexOf("protected boolean isOwner()"); + int ownerEnd = source.indexOf('}', source.indexOf("return key == null", owner)); + String body = source.substring(owner, ownerEnd); + + assertTrue("isOwner must exist", owner > 0); + assertTrue("ownership must read the pinned session key", body.contains("activePlaybackKey()")); + assertFalse("ownership must not recompute the key from the live intent", + body.contains("getPlaybackKey()")); + } + + @Test + public void theSessionKeyIsPinnedWhenPlaybackActuallyStarts() throws Exception { + String source = read(PLAYBACK); + + assertTrue("the pinned key must fall back to the intent before the first start", + source.contains("return pinnedPlaybackKey != null ? pinnedPlaybackKey : getPlaybackKey();")); + // 两条起播分支(需解析 / 直连)都要钉住,漏一条那条链路照旧丢归属; + // 重建恢复也写同一字段,但不是 startPlayer 内的赋值,所以要限定方法体统计 + int startPlayer = source.indexOf("protected void startPlayer(String key, Result result, boolean useParse, long timeout,"); + int startPlayerEnd = source.indexOf("private String lifecycleState()", startPlayer); + assertTrue("startPlayer must exist", startPlayer > 0 && startPlayerEnd > startPlayer); + assertEquals("both start branches must pin the session key from startPlayer", + 2, countOccurrences(source.substring(startPlayer, startPlayerEnd), "pinnedPlaybackKey = key;")); + + int route = source.indexOf("NovelRouter.isReaderUrl(result)"); + int firstPin = source.indexOf("pinnedPlaybackKey = key;", route); + int parse = source.indexOf("player().parse(", route); + int start = source.indexOf("player().start(", route); + + assertTrue("the reader route must return before anything is pinned", firstPin > route); + assertTrue("pinning must happen before the player is handed the spec", + firstPin < parse && firstPin < start); + } + + @Test + public void routingAndReadyReplayFollowTheSameSessionKey() throws Exception { + String source = read(PLAYBACK); + + // 导航 key 与归属 key 必须同源:PlaybackService#isNavigationOwner 拿它跟 + // player.getKey() 比,用现算值会让切集在 id 漂移后静默失效 + assertFalse("navigation must not be registered with a recomputed key", + source.contains("setNavigationCallback(getNavigationCallback(), getPlaybackKey())")); + assertEquals("every navigation registration must use the session key", + 3, countOccurrences(source, "setNavigationCallback(getNavigationCallback(), activePlaybackKey())")); + assertTrue("the READY replay reconciliation must compare the session key", + source.contains("PlaybackStateReconciliation.shouldReplayReady(activePlaybackKey()")); + } + + @Test + public void switchingEntryPointsKeepTheSessionKeyInsteadOfTheHistoryKey() throws Exception { + // 切内核/切解码会重建 PlaySpec;传 getHistoryKey() 会把播放器的 key 换成 + // 当前 intent 算出来的新值,等于在会话中途把归属令牌搬走 + for (String path : new String[] { + "app/src/mobile/java/com/fongmi/android/tv/ui/activity/VideoActivity.java", + "app/src/leanback/java/com/fongmi/android/tv/ui/activity/VideoActivity.java", + "app/src/main/java/com/fongmi/android/tv/ui/activity/TmdbDetailActivity.java" + }) { + String source = read(path); + assertFalse(path + " must not re-key the player with a freshly computed history key", + source.contains("switchPlayer(type, result, getHistoryKey()") + || source.contains("switchPlayer(playerType, result, getHistoryKey()") + || source.contains("switchDecode(result, getHistoryKey()")); + } + assertTrue("mobile decode switching must reuse the session key", + read("app/src/mobile/java/com/fongmi/android/tv/ui/activity/VideoActivity.java") + .contains("switchDecode(result, activePlaybackKey()")); + } + + @Test + public void switchingToAnotherItemReleasesThePreviousSessionKey() throws Exception { + // onNewIntent 换的是条目,旧会话已作废;不清令牌会让新条目一直拿旧 key 比对 + assertTrue("the reset hook must exist", read(PLAYBACK).contains("protected final void resetPlaybackOwnership()")); + for (String path : new String[] { + "app/src/mobile/java/com/fongmi/android/tv/ui/activity/VideoActivity.java", + "app/src/leanback/java/com/fongmi/android/tv/ui/activity/VideoActivity.java", + "app/src/main/java/com/fongmi/android/tv/ui/activity/TmdbDetailActivity.java" + }) { + String source = read(path); + int newIntent = source.indexOf("protected void onNewIntent(Intent intent)"); + int reset = source.indexOf("resetPlaybackOwnership();", newIntent); + int end = source.indexOf("protected void initView", newIntent); + assertTrue(path + " must exist", newIntent > 0); + assertTrue(path + " must release the stale session key when the item changes", + reset > newIntent && (end < 0 || reset < end)); + } + } + + @Test + public void theSessionKeySurvivesActivityRecreation() throws Exception { + String source = read(PLAYBACK); + + int save = source.indexOf("protected void onSaveInstanceState(@NonNull Bundle outState)"); + int restore = source.indexOf("private void restorePlaybackKey(Bundle savedInstanceState)"); + int initViewBody = source.indexOf("restorePlaybackKey(savedInstanceState);"); + int bindService = source.indexOf("if (!shouldBindPlaybackService()) return;", initViewBody); + + assertTrue("playback activity must implement onSaveInstanceState", save > 0); + assertTrue("playback activity must restore the pinned key on recreation", restore > 0); + assertTrue("the pinned key must be restored before binding the service", + initViewBody > 0 && initViewBody < restore && bindService > initViewBody); + assertTrue("the state key must match between save and restore", + countOccurrences(source, "STATE_PLAYBACK_KEY") >= 3); + assertTrue("the session key must not be saved after playback exits", + source.substring(save, source.indexOf("\n }", save)) + .contains("!playbackExiting && pinnedPlaybackKey != null")); + } + + /** + * 加载圈不能只由 STATE_READY 收。 + * + *

那条回调受 isOwner() 把关,归属一旦因任何原因失配,圈就永久留在屏上—— + * 画面在动、圈不走。兜底必须绕开归属,直接读播放器状态。 + */ + @Test + public void theSpinnerHasAnOwnershipIndependentFallback() throws Exception { + for (String path : new String[] { + "app/src/mobile/java/com/fongmi/android/tv/ui/activity/VideoActivity.java", + "app/src/leanback/java/com/fongmi/android/tv/ui/activity/VideoActivity.java" + }) { + String source = read(path); + int fallback = source.indexOf("private void hidePlaybackProgressIfStale()"); + assertTrue(path + " must provide a spinner fallback", fallback > 0); + + String body = source.substring(fallback, source.indexOf("\n }", fallback)); + assertFalse(path + " the fallback must not depend on ownership", body.contains("isOwner()")); + assertTrue(path + " the fallback must read the player state directly", + body.contains("player().getPlaybackState() != Player.STATE_READY")); + // 详情还没加载完时播放器是空的,那时的圈属于详情页自己,不能收 + assertTrue(path + " the fallback must not steal the detail page's own loading state", + body.contains("player().isEmpty()")); + assertTrue(path + " the fallback must only act while the spinner is actually up", + body.contains("getVisibility() != View.VISIBLE")); + + // 挂在网速自循环上:圈可见时每秒一跳,圈收了循环本就停,无额外开销 + int traffic = source.indexOf("private void setTraffic()"); + assertTrue(path + " must drive the fallback from the traffic ticker", + source.indexOf("hidePlaybackProgressIfStale();", traffic) > traffic); + } + } + + private static int countOccurrences(String text, String needle) { + int count = 0; + int index = 0; + while ((index = text.indexOf(needle, index)) >= 0) { + count++; + index += needle.length(); + } + return count; + } + + private static String read(String path) throws Exception { + Path direct = Path.of(path); + if (Files.exists(direct)) return Files.readString(direct, StandardCharsets.UTF_8); + return Files.readString(Path.of(path.substring("app/".length())), StandardCharsets.UTF_8); + } +} diff --git a/app/src/test/java/com/fongmi/android/tv/ui/activity/ReaderPlaybackRoutingSourceTest.java b/app/src/test/java/com/fongmi/android/tv/ui/activity/ReaderPlaybackRoutingSourceTest.java index 17d889ef10..596b9b3b17 100644 --- a/app/src/test/java/com/fongmi/android/tv/ui/activity/ReaderPlaybackRoutingSourceTest.java +++ b/app/src/test/java/com/fongmi/android/tv/ui/activity/ReaderPlaybackRoutingSourceTest.java @@ -1,5 +1,7 @@ package com.fongmi.android.tv.ui.activity; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; @@ -57,6 +59,371 @@ public class ReaderPlaybackRoutingSourceTest { } } + /** + * 返回键要能真正退出阅读器。 + * + * 生命周期顺序是 阅读器 onPause -> 宿主 onResume -> 阅读器 onStop -> 阅读器 onDestroy。 + * 宿主 onResume 会因 shouldReclaim() 重新派发上一次的 playerContent 结果, + * 关闭时间戳若等到 onDestroy 才写,那一刻 NovelRouter 的两道防线同时失效, + * 阅读器会被立刻重新拉起,返回键表现为完全无效。 + */ + @Test + public void readerMarksClosedBeforeHostResumes() throws Exception { + String source = read("app/src/main/java/com/fongmi/android/tv/ui/web/WebReaderActivity.java"); + + int pause = source.indexOf("protected void onPause()"); + int markInPause = source.indexOf("markClosed();", pause); + int superPause = source.indexOf("super.onPause();", pause); + int destroy = source.indexOf("protected void onDestroy()"); + + assertTrue("onPause must exist", pause >= 0); + assertTrue("onPause must mark the reader closed before super.onPause()", + markInPause > pause && markInPause < superPause); + assertTrue("markClosed must run before onDestroy is reached", markInPause < destroy); + assertTrue("markClosed must clear the reader registration", + source.contains("NovelRouter.currentReader = null;")); + assertTrue("markClosed must stamp the close time", + source.contains("NovelRouter.markReaderClosed();")); + assertTrue("onDestroy must still mark closed for non-finish teardown", + source.indexOf("markClosed();", destroy) > destroy); + } + + @Test + public void readerMarksClosedBeforeClearingHostRequests() throws Exception { + String source = read("app/src/main/java/com/fongmi/android/tv/ui/web/WebReaderActivity.java"); + + int pause = source.indexOf("protected void onPause()"); + int markInPause = source.indexOf("markClosed();", pause); + int clearRequests = source.indexOf("hostChapterRequests.getAndSet(0)", pause); + + assertTrue("onPause must mark the reader closed before clearing host requests", + markInPause > pause && clearRequests > pause && markInPause < clearRequests); + } + + @Test + public void hostResultClosesRequestBeforeWebViewGuard() throws Exception { + String source = read("app/src/main/java/com/fongmi/android/tv/ui/web/WebReaderActivity.java"); + + int method = source.indexOf("private void onEpisodeResolved(int newKind, String payload, String title, boolean fromHost)"); + int webViewGuard = source.indexOf("if (webView == null) return;", method); + int closeRequest = source.indexOf("if (fromHost) endHostChapterRequest();", method); + + assertTrue("a host result must close its request even when the WebView was already destroyed", + method >= 0 && webViewGuard > method && closeRequest > method && closeRequest < webViewGuard); + } + + @Test + public void parseFallbackKeepsRestoreAnchorUntilHostResultArrives() throws Exception { + String source = read("app/src/main/java/com/fongmi/android/tv/ui/web/WebReaderActivity.java"); + + int method = source.indexOf("private void resolveChapterSelf(String chapterUrl)"); + int dispatch = source.indexOf("if (fh && h != null)", method); + int clear = source.indexOf("restoreAnchor = 0;", dispatch); + int hostFlag = source.indexOf("boolean hostDispatched = false;", method); + int guard = source.indexOf("if (!hostDispatched)", dispatch); + + assertTrue("parse=1 已成功交给宿主时,必须保留历史恢复锚点直到结果注入", + method >= 0 && hostFlag > method && dispatch > method && clear > dispatch + && guard > dispatch && guard < clear); + } + + @Test + public void staleResultCannotBeDeliveredToAReaderWithoutPendingHostRequest() throws Exception { + String router = read("app/src/main/java/com/fongmi/android/tv/ui/novel/NovelRouter.java"); + String reader = read("app/src/main/java/com/fongmi/android/tv/ui/web/WebReaderActivity.java"); + + assertTrue("当前阅读器必须能报告自己是否有宿主切章请求在途", + reader.contains("public boolean hasPendingHostChapterRequest()")); + assertEquals("三个阅读器结果入口都必须拦截旧请求,避免串页", + 3, countOccurrences(router, + "!reader.hasPendingHostChapterRequest() && NovelRouter.consumeStaleChapterResult()")); + } + + /** + * 首帧不能把进度虚报到批次末尾。 + * + * 漫画首批只挂 5 张图,未解码时 bottom 全堆在同一 y 上,没有锚点跨过阈值, + * 循环末尾的 `idx = i` 就把序号推到最后一个锚点 —— 95 页漫画记成第 5 页、 + * 33 段小说记成第 33 段,下次进来直接跳到那里。 + * + * 注意不能用 rect.height 当「未就绪」信号:小说段落带 content-visibility:auto, + * 真机实测 height 恒为 0 而 bottom 有效,用 height 判断会让小说进度永远停在第 1 段。 + */ + @Test + public void readerAnchorIndexShortCircuitsAtTopOfChapter() throws Exception { + String source = read("app/src/main/assets/reader.html"); + + int fn = source.indexOf("function currentAnchorIndex()"); + int guard = source.indexOf("if(scrolled <= 0) return lastAnchorIndex = 0;", fn); + int loop = source.indexOf("for(", fn); + int degraded = source.indexOf("return lastAnchorIndex = idx;", loop); + + assertTrue("currentAnchorIndex must exist", fn >= 0); + assertTrue("stopping at the top must short-circuit to anchor 0 before scanning", + guard > fn && guard < loop); + assertTrue("a degraded measurement must not advance the anchor unless the document end is reached", + degraded > loop); + // #reader 的 min-height:105vh 让「图全未解码」时轻扫 32px 就到文末, + // 只判 atDocumentEnd 会把退化值当可信 —— 必须同时要求锚点已全部进 DOM + assertTrue("reaching the document end alone must not validate a degraded measurement", + source.contains("anchorsSettled() && atDocumentEnd()")); + assertFalse("rect.height is always 0 for content-visibility paragraphs; it must not gate the scan", + source.contains("if(rect.height <= 0) break;")); + assertTrue("progress bar must read the current anchor, not the loaded count", + source.contains("Math.min(total, effectiveAnchorIndex() + 1)")); + // 落库与进度条必须同一个真值,否则会出现「显示 33/33、重进回到第 30 段」的分叉 + assertTrue("the saved anchor must come from the same source as the progress bar", + source.contains("effectiveAnchorIndex(), anchorTotal());")); + // 小说正文下方还有 140px 内边距和章节导航,光靠 currentAnchorIndex 够不到最后一段, + // 历史列表就永远到不了 100% + assertTrue("a chapter read to its end must be able to record the final anchor", + source.contains("if(anchorsSettled() && atDocumentEnd()) return total - 1;")); + // 退化态统一由 anchorsSettled() 把关:漫画末页图加载失败时高度恒为 0、不占空间; + // PDF 的 canvas 先插入后绘制,未绘制时是固有 300x150(有高度但不是真实页高), + // 只判「到底」会把用户没看到的内容记成读完,下次直接跳到章末 + assertTrue("a degraded layout must be recognised before trusting the document end", + source.contains("function anchorsSettled()")); + // 漫画看末尾两页:图各自异步解码,末页不保证最后完成,只看末页仍会虚报 + assertTrue("a comic must require the last two pages to be laid out", + source.contains("for(var i = Math.max(0, total - 2); i < total; i++){")); + assertTrue("a PDF must require every page to be painted, not merely appended", + source.contains("return pdfDoc != null && pdfAppendedCount >= pdfDoc.numPages;")); + // 渲染失败也要计数,否则那一章永远达不到 numPages,永远记不成读完 + assertTrue("a failed page render must still count towards the settled total", + source.contains(".promise.then(pageSettled, pageSettled);")); + assertTrue("a failed getPage must also count", + source.contains("}, pageSettled);")); + // 换章会清零计数,上一章在途的回调若继续 ++ 会把新章撑到 numPages + assertTrue("stale render callbacks must not inflate the next chapter's count", + source.contains("var gen = pdfGen;") + && source.contains("if(gen !== pdfGen) return;")); + // #reader 是所有章节共用的容器:getDocument 的成功/失败回调也必须带代号, + // 否则上一章的慢加载会把新章内容整段替换成 pdf-error,或把旧 doc 塞进新章 + assertEquals("both getDocument handlers must be generation-guarded", + 3, countOccurrences(source, "if(gen !== pdfGen) return;")); + // 遮罩是全屏 z-index:10002,只有这里会隐藏它:放在代号判定之后, + // 跨类型换章时旧章早退,遮罩就永久盖在新章上吞掉所有点击 + assertTrue("the loading overlay must be hidden before the generation check", + source.contains("showLoading(false);") && source.contains("if(gen !== pdfGen) return;")); + // renderPdf 只在新章也是 PDF 时才调,从 PDF 切到漫画要靠 renderContent 作废代号 + assertTrue("switching away from a PDF chapter must invalidate its callbacks", + source.contains("pdfGen++;") && source.contains("pdfDoc = null; pdfAppendedCount = 0;")); + // fulfillment 里同步抛错不会被同一个 then 的 rejection 处理器捕获 + assertTrue("a throw inside the fulfillment handler must still count", + source.contains("} catch(e){") && source.contains("pageSettled();")); + assertTrue("currentAnchorIndex must use the same settled check", + source.contains("if(found || (anchorsSettled() && atDocumentEnd()))")); + // memo 有副作用:文末分支提前 return 前必须先让 currentAnchorIndex() 跑过一次 + int effFn = source.indexOf("function effectiveAnchorIndex()"); + int memoUpdate = source.indexOf("Math.min(total - 1, currentAnchorIndex());", effFn); + int endBranch = source.indexOf("if(anchorsSettled() && atDocumentEnd())", effFn); + assertTrue("the memo must be updated before the document-end shortcut returns", + memoUpdate > effFn && memoUpdate < endBranch); + } + + /** + * 迟到的切章结果不能重新拉起已关闭的阅读器。 + * + * 1500ms 静默期只挡得住紧随返回的那一拨回调;用户点了下一章又马上返回时, + * 爬虫可能几秒后才回,这条结果落在窗口外就会另起一个阅读器压在宿主上面, + * 表现仍然是返回键无效。用关闭代号比对才能识别它属于已经关掉的那个阅读器。 + */ + @Test + public void staleChapterResultDoesNotRelaunchClosedReader() throws Exception { + String router = read("app/src/main/java/com/fongmi/android/tv/ui/novel/NovelRouter.java"); + String reader = read("app/src/main/java/com/fongmi/android/tv/ui/web/WebReaderActivity.java"); + + // 只数在途请求、不认身份:结果送达那一刻拿不到「这是哪一章的」, + // 按令牌 / 按最早 / 整表清空都会删错条目,反而放行别人的迟到结果。 + assertTrue("in-flight host requests must be counted", + router.contains("inFlightChapters.incrementAndGet();") + && router.contains("public static void endChapterRequest()")); + // 关闭那一刻在途的请求,其结果逐个拦下;没有在途请求时不留额度, + // 否则会无条件吞掉关闭后的第一次合法打开 + assertTrue("closing must convert in-flight requests into suppression credits", + router.contains("int pending = inFlightChapters.getAndSet(0);") + && router.contains("if (pending > 0) {")); + assertTrue("credits must accumulate and expire so silent failures cannot swallow opens forever", + router.contains("staleChapterResults.addAndGet(pending);") + && router.contains("staleUntil = Math.max(staleUntil, readerClosedAt + PENDING_CHAPTER_TTL);") + && router.contains("if (android.os.SystemClock.elapsedRealtime() > staleUntil) {")); + assertEquals("every relaunch site must consult the suppression guard", + 3, countOccurrences(router, "if (shouldSuppressRelaunch())")); + assertTrue("the guard must combine the silence window and the stale check", + router.contains("return justClosed() || stale;")); + // 两处宿主派发都要记账,漏一处整套判定就失效 + assertEquals("both host paths must register their request", + 2, countOccurrences(reader, "NovelRouter.noteChapterRequest();")); + // 宿主找不到章节时会静默返回,必须立刻收尾而不是等 45s 过期 + assertEquals("a dispatch that never happened must close out immediately", + 2, countOccurrences(reader, "if (!h.labPlayEpisode(chapterUrl)) chapterFailedWithToast(true);")); + } + + /** + * 阅读进度落库不需要数据迁移,且读完即 100%。 + * + * 历史列表按 position/duration 画进度条,若把「读到最后一个锚点」也存成序号, + * 2 页的漫画短章读完只显示 50%;但若整体改成 1 基,升级前写入的存量记录会被 + * 统一平移一个锚点。折中:只把「读完」编码为 duration,其余沿用序号原值。 + */ + @Test + public void readingProgressKeepsLegacyRowsAndStillReachesFullBar() throws Exception { + String history = read("app/src/main/java/com/fongmi/android/tv/ui/novel/ReaderHistory.java"); + String reader = read("app/src/main/java/com/fongmi/android/tv/ui/web/WebReaderActivity.java"); + + // 非读完的锚点原样存序号 —— 存量 0 基记录读回来不偏移 + assertTrue("a mid-chapter anchor must be stored as-is so legacy rows still resolve", + history.contains("long value = Math.max(0, Math.min(duration - 1, anchor));")); + assertTrue("only the finished state is encoded as duration", + history.contains("return duration == SCALE ? duration - 1 : duration;")); + assertTrue("the finished encoding must convert back to the last anchor", + history.contains("if (position >= duration) return (int) (duration - 1);")); + assertTrue("restore must go through the converter", + reader.contains("ReaderHistory.toAnchor(h.getPosition(), restoreTotal)")); + // 旧版小说记录存的是百分比×SCALE,不能走锚点换算 + assertTrue("legacy percent records must bypass the anchor conversion", + reader.contains("restoreTotal == ReaderHistory.SCALE")); + // 百分比分支必须解锁 restoringPage,否则整个会话都不再上报,旧记录也永远迁不到新语义 + String html = read("app/src/main/assets/reader.html"); + int percentFn = html.indexOf("function restoreScrollPercent(p)"); + assertTrue("restoreScrollPercent must exist", percentFn > 0); + assertTrue("the legacy percent path must release the reporting lock", + html.indexOf("restoringPage = false;", percentFn) > percentFn + && html.indexOf("restoringPage = false;", percentFn) < html.indexOf("function restoreAnchor(index)")); + // max>0 挡不住:min-height:105vh 让它首帧就成立,上报会把 90% 的进度覆盖成章首 + // anchorsSettled() 对小说恒为真(段落一次性建完),首帧就放行等于没有护栏; + // content-visibility 让屏外段落先按 30px 估算,此刻 scrollHeight 还会长大 + // 小说的 content-visibility 估算高度在滚动前不变,「高度稳定」对它是空护栏; + // 判据必须是「滚过去之后换算回来的锚点也稳定」 + assertTrue("the percent restore must converge on the resolved anchor", + html.contains("if(!settled || lastMax === null || lastMax !== idx) stable = 0;")); + assertTrue("it must require three stable measurements like restoreAnchor", + html.contains("var ready = stable >= 3;")); + assertTrue("the percent restore must be invalidated when content is replaced", + html.contains("var gen = ++restoreGen;") && html.contains("restoringPage = true;")); + // 短章内容一屏放得下时高度一开始就稳定,滚到 min-height 撑出的 5vh 后锚点仍是 0, + // 盲目上报会把用户存的 90% 覆盖成章首 + assertTrue("migrating a percent record must not move the position backwards", + html.contains("if(effectiveAnchorIndex() >= expected) reportProgress();")); + // 漫画一批批懒加载,光等不会让剩下的页进 DOM,anchorsSettled 永远为假 —— + // 旧百分比记录既恢复不了也迁移不了,必须主动催加载 + assertTrue("the percent restore must drive lazy loading for comics and PDFs", + html.contains("if(DATA.kind === 3) renderPdfMore();") + && html.contains("else if(DATA.kind !== 1) loadMoreComic();")); + assertTrue("the percent restore budget must use the monotonic clock", + html.contains("var deadline = nowMs() + 60000;")); + } + + /** + * 换章必须清掉锚点记忆。 + * + * PDF 章在 pdfDoc 解析完成前 anchorTotal() 为 0,effectiveAnchorIndex() 会在 + * total<=0 处早退,不经过 currentAnchorIndex() 的归零短路 —— 上一章的高位值 + * 会残留,把新章第 1 页记成上一章的位置。 + */ + @Test + public void switchingChapterResetsTheAnchorMemo() throws Exception { + String html = read("app/src/main/assets/reader.html"); + + int render = html.indexOf("function renderContent()"); + int reset = html.indexOf("lastAnchorIndex = 0;", render); + int clear = html.indexOf("r.innerHTML = '';", render); + + assertTrue("renderContent must exist", render > 0); + assertTrue("the memo must be cleared when the content is replaced", + reset > render && reset < clear); + } + + /** + * 关闭静默期与在途标记的时限都必须用单调时钟。 + * + * wall clock 会被 NTP 校正或用户改时间往回跳,一旦往回跳,「现在 - 关闭时刻」 + * 变成大负数而恒小于窗口,静默期就永不结束,之后所有阅读打开都被当成残留回调拦掉。 + */ + @Test + public void relaunchGuardsUseMonotonicClock() throws Exception { + String router = read("app/src/main/java/com/fongmi/android/tv/ui/novel/NovelRouter.java"); + + assertFalse("the silence window must not depend on wall-clock time", + router.contains("readerClosedAt = System.currentTimeMillis();")); + assertFalse("the pending-tag TTL must not depend on wall-clock time", + router.contains("pendingChapterAt = System.currentTimeMillis();")); + assertTrue("every timestamp and comparison must use elapsedRealtime", + countOccurrences(router, "android.os.SystemClock.elapsedRealtime()") >= 3); + } + + /** + * 只撤销自己发出的那次在途标记。 + * + * chapterFailed() 还会被空 URL、注入异常等与宿主请求无关的路径调用, + * 无条件撤销会把另一次仍在途的请求的标记抹掉,重新打开「返回键失效」的缺口。 + */ + @Test + public void onlyTheOwnHostRequestAbandonsItsPendingTag() throws Exception { + String reader = read("app/src/main/java/com/fongmi/android/tv/ui/web/WebReaderActivity.java"); + + assertTrue("the reader must track how many of its requests are in flight", + reader.contains("hostChapterRequests = new java.util.concurrent.atomic.AtomicInteger()")); + // 只有自己确实发过请求才收尾:空 URL、注入异常与任何请求无关, + // 替别人收尾会让那一笔的迟到结果不再被拦(返回键失效) + assertTrue("closing out must be gated on owning a request", + reader.contains("if (ownHostRequest) endHostChapterRequest();")); + assertTrue("the empty-url path must not close out anyone else", + reader.contains("chapterFailed(false); return;")); + assertTrue("the reader must only decrement what it actually holds", + reader.contains("if (hostChapterRequests.getAndUpdate(n -> n > 0 ? n - 1 : 0) > 0) {")); + } + + /** + * 切章成功送达前台后必须清掉在途标记。 + * + * 「送达前台阅读器」这条路径提前 return,不经过 shouldSuppressRelaunch(), + * 所以标记不会被 isStaleChapterResult() 顺手清掉。留着它的后果是: + * 用户关掉阅读器、过一会儿主动打开另一本书时,那次合法打开会被误判成过期结果吞掉。 + */ + @Test + public void deliveredChapterResultClearsThePendingTag() throws Exception { + String router = read("app/src/main/java/com/fongmi/android/tv/ui/novel/NovelRouter.java"); + String reader = read("app/src/main/java/com/fongmi/android/tv/ui/web/WebReaderActivity.java"); + + // 送达要收尾,但 router 侧不能自作主张删条目 —— 它不知道是哪一笔 + assertFalse("the router must not guess which request was delivered", + router.contains(" clearChapterRequest();")); + assertTrue("delivery must close out exactly one in-flight request", + reader.contains("if (fromHost) endHostChapterRequest();")); + // 自解析路径没发过请求,不能替宿主收尾 + assertTrue("the self-resolve path must not close out a host request", + reader.contains("onEpisodeResolved(fk, fp, at >= 0 ? chapters.get(at).getName() : \"\", false);")); + } + + /** + * 阅读器回到前台必须重新登记。 + * + * onPause 交还前台时会清掉注册,只在 onCreate 注册的话,两个阅读器叠栈时 + * 下层那个再次回到前台就永久失去注册,之后它自己的切章会另起一个实例压在自己上面。 + */ + @Test + public void readerReRegistersOnResume() throws Exception { + String source = read("app/src/main/java/com/fongmi/android/tv/ui/web/WebReaderActivity.java"); + + int resume = source.indexOf("protected void onResume()"); + int register = source.indexOf("NovelRouter.currentReader = this;", resume); + int pause = source.indexOf("protected void onPause()"); + + assertTrue("onResume must exist", resume > 0); + assertTrue("onResume must re-register the reader", register > resume && register < pause); + } + + private static int countOccurrences(String text, String needle) { + int count = 0; + int index = 0; + while ((index = text.indexOf(needle, index)) >= 0) { + count++; + index += needle.length(); + } + return count; + } + private static String read(String path) throws Exception { Path direct = Path.of(path); if (Files.exists(direct)) return Files.readString(direct, StandardCharsets.UTF_8); diff --git a/app/src/test/java/com/fongmi/android/tv/ui/activity/TmdbDetailInlineOsdTitleTest.java b/app/src/test/java/com/fongmi/android/tv/ui/activity/TmdbDetailInlineOsdTitleTest.java new file mode 100644 index 0000000000..862449c61d --- /dev/null +++ b/app/src/test/java/com/fongmi/android/tv/ui/activity/TmdbDetailInlineOsdTitleTest.java @@ -0,0 +1,30 @@ +package com.fongmi.android.tv.ui.activity; + +import org.junit.Test; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class TmdbDetailInlineOsdTitleTest { + + @Test + public void inlineOsdUsesCurrentEpisodeTitleInsteadOfSeasonProgress() throws IOException { + String source = Files.readString(Path.of("src", "main", "java", + "com", "fongmi", "android", "tv", "ui", "activity", "TmdbDetailActivity.java"), + StandardCharsets.UTF_8); + int start = source.indexOf("private String getInlineOsdTitle()"); + int end = source.indexOf("\n private ", start + 1); + + assertTrue(start >= 0 && end > start); + String method = source.substring(start, end); + assertTrue(method.contains("historyEpisodeTitle(selectedEpisode)")); + assertTrue(method.contains("getString(R.string.detail_title, name, episodeTitle)")); + assertFalse(method.contains("selectedEpisode.getName()")); + assertFalse(method.contains("tmdbEpisodeInfo().compactText")); + } +} diff --git a/app/src/test/java/com/fongmi/android/tv/ui/custom/FocusRestorerTest.java b/app/src/test/java/com/fongmi/android/tv/ui/custom/FocusRestorerTest.java new file mode 100644 index 0000000000..e00243d8ea --- /dev/null +++ b/app/src/test/java/com/fongmi/android/tv/ui/custom/FocusRestorerTest.java @@ -0,0 +1,147 @@ +package com.fongmi.android.tv.ui.custom; + +import androidx.recyclerview.widget.RecyclerView; + +import org.junit.Test; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class FocusRestorerTest { + + @Test + public void removedItemKeepsFocusOnTheSameSlotWhenLaterItemsShiftUp() { + // 3 列,删掉第 0 行第 1 列(下标 1),后面的条目补位,焦点留在原位 + assertEquals(1, FocusRestorer.nextPosition(1, 5, 3)); + assertEquals(0, FocusRestorer.nextPosition(0, 5, 3)); + } + + @Test + public void removedLastItemOfARowFallsBackWithinTheSameRow() { + // 3 列 5 条:删掉下标 4(第 1 行第 1 列,行内末位)后剩 4 条,退到新末位 3——仍在第 1 行 + assertEquals(3, FocusRestorer.nextPosition(4, 4, 3)); + } + + @Test + public void removedOnlyItemOfTheLastRowMovesUpOneRowKeepingTheColumn() { + // 3 列 4 条:下标 3 是第 1 行唯一条目,删除后整行消失。 + // 一维 clamp 会给出 2(第 0 行第 2 列,横跨整屏),正确目标是同列上一行的 0 + assertEquals(0, FocusRestorer.nextPosition(3, 3, 3)); + // 3 列 7 条:下标 6 独占第 2 行第 0 列,删除后回到第 1 行第 0 列 + assertEquals(3, FocusRestorer.nextPosition(6, 6, 3)); + } + + @Test + public void nextPositionNeverEscapesTheNewListBounds() { + // 不只覆盖「删一条」,也覆盖聚合删除后一次少掉多条的情况 + for (int span = 1; span <= 6; span++) { + for (int position = 0; position <= 40; position++) { + for (int count = 0; count <= 40; count++) { + int next = FocusRestorer.nextPosition(position, count, span); + if (count == 0) { + assertEquals("空列表必须返回 NO_POSITION", RecyclerView.NO_POSITION, next); + continue; + } + assertTrue("span=" + span + " count=" + count + " position=" + position + + " 返回了越界下标 " + next, next >= 0 && next < count); + // 焦点只允许留在原位或往前退,绝不能往后跳到用户没去过的条目 + assertTrue("span=" + span + " count=" + count + " position=" + position + + " 让焦点前进到了 " + next, next <= position); + boolean clamped = position >= count && position - span > count - 1; + if (position >= count && !clamped && (count - 1) / span != position / span) { + assertEquals("span=" + span + " count=" + count + " position=" + position + + " 整行删空后必须保持同列", position % span, next % span); + } + } + } + } + } + + @Test + public void emptyOrUnknownPositionYieldsNoPosition() { + assertEquals(RecyclerView.NO_POSITION, FocusRestorer.nextPosition(RecyclerView.NO_POSITION, 5, 3)); + assertEquals(RecyclerView.NO_POSITION, FocusRestorer.nextPosition(0, 0, 3)); + } + + @Test + public void singleColumnListBehavesLikeALinearList() { + assertEquals(2, FocusRestorer.nextPosition(2, 5, 1)); + assertEquals(3, FocusRestorer.nextPosition(4, 4, 1)); + } + + @Test + public void restoreGuardsAgainstHiddenListsAndScrollsToUnlaidOutTargets() throws Exception { + String source = read(findMainJavaPath().resolve(Path.of( + "com", "fongmi", "android", "tv", "ui", "custom", "FocusRestorer.java"))); + assertTrue("恢复焦点前必须确认列表可见,否则 requestFocus 会被 INVISIBLE 的祖先拒绝", + source.contains("!recycler.isShown()")); + assertTrue("目标行未 layout 时必须先滚动,并再等一次 pre-draw 才能拿到 holder(post 会跑在 layout 之前)", + source.contains("recycler.scrollToPosition(position);") + && source.contains("schedule(recycler, position, scheduled, false);")); + assertFalse("不能用 post 做滚动重试:它的消息会在重新 layout 之前执行,重试必然拿不到 holder", + source.contains("recycler.post(")); + assertTrue("重试仍失败时必须把焦点兜底交回列表本身", + source.contains("recycler.requestFocus()")); + assertTrue("必须检查 requestFocus 的返回值,而不是假定成功", + source.contains("return holder != null && holder.itemView.requestFocus();")); + assertTrue("排队的恢复必须可取消,避免退出删除模式或离开页面后抢焦点", + source.contains("public void cancel()") + && source.contains("pending.removeListener();")); + assertTrue("滚动重试不受 removeListener 管辖,必须用代际号让 cancel 也能作废它", + source.contains("if (scheduled != generation) return;")); + } + + @Test + public void leanbackHistoryPageRestoresFocusByItemIdentityAndCancelsOnExit() throws Exception { + String source = read(findLeanbackJavaPath().resolve(Path.of( + "com", "fongmi", "android", "tv", "ui", "activity", "HistoryActivity.java"))); + assertTrue("删除单条后必须按网格规则恢复焦点,而不是一维 clamp", + source.contains("FocusRestorer.nextPosition(target, mAdapter.getItemCount(), Product.getColumn())")); + assertFalse("不能对网格下标做一维 clamp——列删空时会把焦点甩到上一行另一端", + source.contains("mAdapter.getItemCount() - 1)")); + assertTrue("删除位置必须来自 holder 的绑定下标,而不是重新 indexOf 扫描", + source.contains("public void onItemDelete(History item, int position)")); + assertTrue("去抖刷新会重排列表,恢复焦点必须按条目身份重新定位", + source.contains("indexOf(focused)")); + assertTrue("聚焦条目已不在新列表时必须退回原位置,而不是放弃恢复让焦点掉给删除按钮", + source.contains("reposition(focused, position)") + && source.contains("if (found >= 0) return found;")); + assertTrue("holder 绑定下标失效时必须退回当前聚焦位置", + source.contains("position >= 0 ? position : focusedPosition()")); + assertTrue("恢复焦点前必须做生命周期守卫", + source.contains("if (isFinishing() || isDestroyed()) return;")); + assertTrue("退出删除模式、返回与 onStop 都必须取消排队中的恢复", + source.contains("mFocusRestorer.cancel();") + && source.contains("protected void onStop()")); + } + + @Test + public void leanbackHistoryAdapterPassesTheBoundPositionOnDelete() throws Exception { + String source = read(findLeanbackJavaPath().resolve(Path.of( + "com", "fongmi", "android", "tv", "ui", "adapter", "HistoryAdapter.java"))); + assertTrue("删除回调必须带上 holder 的绑定下标", + source.contains("void onItemDelete(History item, int position);") + && source.contains("listener.onItemDelete(item, holder.getBindingAdapterPosition());")); + } + + private static String read(Path path) throws Exception { + return new String(Files.readAllBytes(path), StandardCharsets.UTF_8); + } + + private static Path findMainJavaPath() { + Path moduleRelative = Path.of("src", "main", "java"); + if (Files.exists(moduleRelative)) return moduleRelative; + return Path.of("app", "src", "main", "java"); + } + + private static Path findLeanbackJavaPath() { + Path moduleRelative = Path.of("src", "leanback", "java"); + if (Files.exists(moduleRelative)) return moduleRelative; + return Path.of("app", "src", "leanback", "java"); + } +} diff --git a/app/src/test/java/com/fongmi/android/tv/ui/novel/ReaderHistoryProgressTest.java b/app/src/test/java/com/fongmi/android/tv/ui/novel/ReaderHistoryProgressTest.java new file mode 100644 index 0000000000..b7e2434812 --- /dev/null +++ b/app/src/test/java/com/fongmi/android/tv/ui/novel/ReaderHistoryProgressTest.java @@ -0,0 +1,90 @@ +package com.fongmi.android.tv.ui.novel; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +/** + * 阅读进度的落库编码:历史列表按 position/duration 画进度条。 + * + * 只把「读完」编码为 duration,其余锚点原样存序号 —— 这样读完是 100%, + * 而升级前写入的存量 0 基记录读回来也不会平移。 + */ +public class ReaderHistoryProgressTest { + + @Test + public void finishedChapterFillsTheBar() { + assertEquals(33, ReaderHistory.toPosition(32, 33)); + assertEquals(2, ReaderHistory.toPosition(1, 2)); + assertEquals(1, ReaderHistory.toPosition(0, 1)); + } + + @Test + public void midChapterAnchorIsStoredAsIs() { + assertEquals(0, ReaderHistory.toPosition(0, 33)); + assertEquals(11, ReaderHistory.toPosition(11, 33)); + assertEquals(31, ReaderHistory.toPosition(31, 33)); + } + + @Test + public void anchorSurvivesTheRoundTrip() { + for (int total : new int[] {1, 2, 3, 33, 95}) { + for (int anchor = 0; anchor < total; anchor++) { + long position = ReaderHistory.toPosition(anchor, total); + assertEquals("total=" + total + " anchor=" + anchor, + anchor, ReaderHistory.toAnchor(position, total)); + } + } + } + + /** 打开后不滚动就退出会把恢复值原样回写,必须不漂移。 */ + @Test + public void repeatedOpenAndExitDoesNotDrift() { + int total = 33; + for (long start : new long[] {0, 12, 31, 33}) { + long position = start; + for (int cycle = 0; cycle < 5; cycle++) { + int anchor = ReaderHistory.toAnchor(position, total); + position = ReaderHistory.toPosition(anchor, total); + } + assertEquals("start=" + start, start, position); + } + } + + /** + * 升级前的存量记录不会被误判成「读完」。 + * 旧代码上限是 min(duration, anchor),anchor 最大 total-1,故旧 position 恒小于 duration。 + */ + @Test + public void legacyRowsAreNotMistakenForFinished() { + int total = 33; + for (int legacy = 0; legacy <= total - 1; legacy++) { + assertTrue("legacy=" + legacy, legacy < total); + assertEquals("legacy=" + legacy, legacy, ReaderHistory.toAnchor(legacy, total)); + } + } + + /** + * duration 恰好等于 SCALE 时不能把「读完」编码成 duration。 + * 那会让记录长得和旧版百分比记录一模一样,下次恢复走百分比分支, + * 把锚点当成 0~1 的比例用,位置彻底错乱。 + */ + @Test + public void scaleSizedChapterDoesNotCollideWithLegacyPercentRecords() { + long scale = ReaderHistory.SCALE; + assertEquals(scale - 1, ReaderHistory.toPosition((int) scale - 1, scale)); + // 少记一个锚点是可接受代价;换回来仍落在合法范围内 + assertEquals(scale - 1, ReaderHistory.toAnchor(scale - 1, scale)); + // 相邻规模不受影响,读完仍编码为 duration + assertEquals(scale + 1, ReaderHistory.toPosition((int) scale, scale + 1)); + assertEquals(scale - 1, ReaderHistory.toPosition((int) scale - 2, scale - 1)); + } + + @Test + public void degenerateTotalsDoNotCrash() { + assertEquals(0, ReaderHistory.toAnchor(5, 0)); + assertEquals(0, ReaderHistory.toAnchor(-1, 10)); + assertEquals(0, ReaderHistory.toPosition(-5, 10)); + } +} diff --git a/app/src/test/java/com/fongmi/android/tv/utils/FileChooserImportTest.java b/app/src/test/java/com/fongmi/android/tv/utils/FileChooserImportTest.java new file mode 100644 index 0000000000..b7374333f9 --- /dev/null +++ b/app/src/test/java/com/fongmi/android/tv/utils/FileChooserImportTest.java @@ -0,0 +1,114 @@ +package com.fongmi.android.tv.utils; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; + +/** + * 无法解析真实路径的 content URI 要复制到应用内部目录。这个目录不是 cache,系统「清理缓存」 + * 清不掉,所以复制策略必须自己保证不会无界增长——同时又不能删掉已被配置引用的文件。 + * + *

这里测的是真实行为(真建文件、真比对内容),不是源码文本。 + */ +public class FileChooserImportTest { + + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + + private static InputStream stream(String body) { + return new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)); + } + + @Test + public void importWritesContentAndReturnsPathInsideTargetDir() throws IOException { + File dir = folder.newFolder("imports"); + String path = FileChooser.persistentImport(stream("module.exports={};"), "pkg.zip", dir); + + File file = new File(path); + assertTrue("导入结果必须真的落盘", file.isFile()); + assertEquals("内容必须完整写入", "module.exports={};", new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8)); + assertEquals("必须落在指定的持久目录里", dir.getCanonicalFile(), file.getParentFile().getCanonicalFile()); + } + + /** + * 反复导入同一个包是最常见的操作(改完本地包再导一次)。若每次都留新副本, + * 内部存储会被几十 MB 的 zip 一路吃光,而用户在设置里看不到也删不掉。 + */ + @Test + public void reimportingIdenticalContentReusesOneFile() throws IOException { + File dir = folder.newFolder("imports"); + String first = FileChooser.persistentImport(stream("same-bytes"), "pkg.zip", dir); + String second = FileChooser.persistentImport(stream("same-bytes"), "pkg.zip", dir); + + assertEquals("相同内容必须复用同一份文件", first, second); + assertEquals("目录里只该有一个文件", 1, countFiles(dir)); + } + + /** 同名但内容不同的两个包必须各自独立,否则换包后仍加载旧内容。 */ + @Test + public void sameNameWithDifferentContentDoesNotOverwrite() throws IOException { + File dir = folder.newFolder("imports"); + String first = FileChooser.persistentImport(stream("bundle-a"), "pkg.zip", dir); + String second = FileChooser.persistentImport(stream("bundle-b"), "pkg.zip", dir); + + assertNotEquals("同名不同内容不能相互覆盖", first, second); + assertEquals("bundle-a", new String(Files.readAllBytes(new File(first).toPath()), StandardCharsets.UTF_8)); + assertEquals("bundle-b", new String(Files.readAllBytes(new File(second).toPath()), StandardCharsets.UTF_8)); + } + + /** 空内容说明流已失效(文档被删/权限被撤),落盘一个 0 字节文件只会让后续解析莫名失败。 */ + @Test + public void emptyStreamIsRejectedAndLeavesNothingBehind() throws IOException { + File dir = folder.newFolder("imports"); + assertThrows(IOException.class, () -> FileChooser.persistentImport(stream(""), "pkg.zip", dir)); + assertEquals("失败后不能留下任何残留文件", 0, countFiles(dir)); + } + + /** 中途失败不能留下 .import-*.tmp,否则每次失败都在内部存储里堆一份垃圾。 */ + @Test + public void failureMidStreamCleansUpTempFile() throws IOException { + File dir = folder.newFolder("imports"); + InputStream broken = new InputStream() { + private int remaining = 16; + + @Override + public int read() throws IOException { + if (remaining-- <= 0) throw new IOException("stream broke"); + return 'x'; + } + }; + + assertThrows(IOException.class, () -> FileChooser.persistentImport(broken, "pkg.zip", dir)); + assertEquals("读取中断后不能留下临时文件", 0, countFiles(dir)); + } + + /** 文件名来自 content provider,可能含路径分隔符或奇怪字符,不能直接拼进路径。 */ + @Test + public void hostileDisplayNamesStayInsideTargetDir() throws IOException { + File dir = folder.newFolder("imports"); + for (String name : new String[]{"../../evil.zip", "a/b/c.zip", null, " ", "包名.zip"}) { + String path = FileChooser.persistentImport(stream("body-" + name), name, dir); + File file = new File(path); + assertEquals("文件名 " + name + " 不能逃出目标目录", + dir.getCanonicalFile(), file.getParentFile().getCanonicalFile()); + assertTrue(file.isFile()); + } + } + + private static int countFiles(File dir) { + File[] files = dir.listFiles(); + return files == null ? 0 : files.length; + } +} diff --git a/app/src/testMobile/java/com/fongmi/android/tv/ui/activity/VideoActivityLayoutTest.java b/app/src/testMobile/java/com/fongmi/android/tv/ui/activity/VideoActivityLayoutTest.java index 02d8010a18..9a6c36bced 100644 --- a/app/src/testMobile/java/com/fongmi/android/tv/ui/activity/VideoActivityLayoutTest.java +++ b/app/src/testMobile/java/com/fongmi/android/tv/ui/activity/VideoActivityLayoutTest.java @@ -494,8 +494,8 @@ public class VideoActivityLayoutTest { assertTrue(label + " playback must update artwork before the new item starts", body.contains("applyPlaybackArtwork(episode);")); assertTrue(label + " playback must clear lyrics and karaoke state between episodes", body.contains("clearLyrics();") && body.contains("clearKaraokeState();")); - assertTrue(label + " playback must request content with the resolved per-episode flag", - body.contains("mViewModel.playerContent(getKey(), playFlag, episode.getUrl());")); + assertTrue(label + " playback must request content with the resolved per-episode flag and the show's kernel", + body.contains("mViewModel.playerContent(getKey(), playFlag, episode.getUrl(), applyHistoryPlayerKernel());")); } @Test @@ -820,13 +820,54 @@ public class VideoActivityLayoutTest { Path sourcePath = findMainJavaPath().resolve(Path.of("com", "fongmi", "android", "tv", "player", "PlayerManager.java")); String source = new String(Files.readAllBytes(sourcePath), StandardCharsets.UTF_8); int method = source.indexOf("public void switchPlayer(int type, Result result"); - int methodEnd = source.indexOf("private void switchPlayer(int type, boolean persist)", method); + int methodEnd = source.indexOf("private void switchPlayer(int type, boolean manual)", method); String methodBody = method >= 0 && methodEnd > method ? source.substring(method, methodEnd) : ""; assertTrue(sourcePath + " is missing refreshed-result player switching", method >= 0); assertTrue("a user-selected refreshed core must stop instead of auto-falling back on its first failure", methodBody.contains("manualPlayerSwitchPending = true;")); } + @Test + public void playerKernelSwitchStaysScopedToCurrentPlayback() throws Exception { + String player = new String(Files.readAllBytes(findMainJavaPath().resolve(Path.of("com", "fongmi", "android", "tv", "player", "PlayerManager.java"))), StandardCharsets.UTF_8); + String leanback = new String(Files.readAllBytes(findLeanbackJavaPath().resolve(Path.of("com", "fongmi", "android", "tv", "ui", "activity", "VideoActivity.java"))), StandardCharsets.UTF_8); + String mobile = new String(Files.readAllBytes(findMobileJavaPath().resolve(Path.of("com", "fongmi", "android", "tv", "ui", "activity", "VideoActivity.java"))), StandardCharsets.UTF_8); + String tmdb = new String(Files.readAllBytes(findMainJavaPath().resolve(Path.of("com", "fongmi", "android", "tv", "ui", "activity", "TmdbDetailActivity.java"))), StandardCharsets.UTF_8); + String history = new String(Files.readAllBytes(findMainJavaPath().resolve(Path.of("com", "fongmi", "android", "tv", "bean", "History.java"))), StandardCharsets.UTF_8); + + assertFalse("switching cores inside the player must not rewrite the global default kernel", player.contains("PlayerSetting.putPlayer(")); + assertTrue("the running kernel must be published as session state instead", player.contains("PlayerSetting.putActivePlayer(")); + assertTrue("ending playback must drop the session kernel so the global default applies again", player.contains("PlayerSetting.clearActivePlayer();")); + + assertTrue("the per-show kernel must be persisted, not a transient field", history.contains("@SerializedName(\"player\")") && !history.contains("private transient int player")); + + for (String source : new String[]{leanback, mobile}) { + assertTrue("playback must restore the show's remembered kernel before resolving the play url", + source.contains("player().preparePlayer(kernel);")); + assertTrue("the remembered kernel must fall back to the global default", source.contains("mHistory.getPlayerOrDefault()")); + assertTrue("the show's history must remember the user's selection, not an engine/session state", + source.contains("private void rememberPlayerKernel(int type)") && source.contains("mHistory.setPlayer(type);")); + // 播放页会重叠存在:上一部剧的收尾存档若也写内核,就会用别人的会话内核 + // 覆盖本剧记住的选择,历史回归点。 + assertFalse("routine history saves must not rewrite the show's kernel", + source.contains("mHistory.setPlayer(PlayerSetting.getActivePlayer());")); + // 服务可能是上一次播放留活的,它建 PlayerManager 时读到的是上一部剧的内核, + // 所以服务就绪前定下的选择必须在连上后补落到引擎。 + assertTrue("a kernel chosen before the service was ready must be applied once it connects", + source.contains("mPendingPlayerKernel = kernel;") + && source.contains("private void applyPendingPlayerKernel()") + && methodBody(source, "protected void onServiceConnected()", "\n }").contains("applyPendingPlayerKernel();")); + } + assertTrue("inline TMDB playback must resolve the play url with the show's kernel", + tmdb.contains("SiteApi.playerContent(key, flag, episodeUrl, playerKernel)")); + assertTrue("inline TMDB playback must restore the show's remembered kernel", + tmdb.contains("player().preparePlayer(inlineHistoryPlayerKernel());")); + assertTrue("inline TMDB playback must remember only the user's selection", + tmdb.contains("private void rememberInlinePlayerKernel(int type)") && tmdb.contains("history.setPlayer(type);")); + assertFalse("inline progress sync must not rewrite the show's kernel", + tmdb.contains("history.setPlayer(PlayerSetting.getActivePlayer());")); + } + @Test public void videoActivitiesDelegateSharedPlayerUiSetup() throws Exception { String leanback = new String(Files.readAllBytes(findLeanbackJavaPath().resolve(Path.of("com", "fongmi", "android", "tv", "ui", "activity", "VideoActivity.java"))), StandardCharsets.UTF_8); @@ -950,6 +991,97 @@ public class VideoActivityLayoutTest { || source.contains("isFullscreen() && isShortDramaSource()")); } + @Test + public void mobileShortDramaGesturesSwapAxesToAvoidMisfires() throws Exception { + // 用户反馈:竖屏短剧铺满屏幕,左右 1/4 竖滑调亮度/音量与中间竖滑切集互相误触。 + // 短剧形态改为「整屏上下滑切集 + 长按后上下滑调亮度/音量」,两个手势类同步。 + List gestureFiles = Arrays.asList( + findMobileJavaPath().resolve(Path.of("com", "fongmi", "android", "tv", "ui", "custom", "CustomKeyDown.java")), + findMainJavaPath().resolve(Path.of("com", "fongmi", "android", "tv", "ui", "custom", "PlayerGesture.java")) + ); + + for (Path gestureFile : gestureFiles) { + String source = new String(Files.readAllBytes(gestureFile), StandardCharsets.UTF_8); + assertTrue(gestureFile + " must expose the short drama gesture mode", source.contains("public void setShortDrama(boolean shortDrama)")); + // 上下滑切集不再受左右 1/4 亮度/音量分区限制。 + assertTrue(gestureFile + " must let short drama flings cover the side quarters", + source.contains("(!shortDrama && isSide(e1))")); + // 亮度/音量不再由滑动起点的左右 1/4 触发。 + assertTrue(gestureFile + " must stop routing short drama scrolls to brightness/volume", + source.contains("else if (!shortDrama && isSide(e2)) checkSide(e2);")); + // 长按后 GestureDetector 不再回调 onScroll,调节必须由 onTouchEvent 自己驱动。 + assertTrue(gestureFile + " must drive the long-press adjust from onTouchEvent", + source.contains("action == MotionEvent.ACTION_MOVE") && source.contains("handleAdjust(e);")); + assertTrue(gestureFile + " must hand back the speed-up before adjusting", source.contains("private void startAdjust(MotionEvent e)")); + // 起点必须在 ACTION_DOWN 时记:onDown 会在边缘/缩放/锁定时提前返回, + // 拿上一次手势的起点算位移会让长按转调节一按就跳。 + assertTrue(gestureFile + " must capture the down point from the raw stream", + source.contains("if (action == MotionEvent.ACTION_DOWN) {") && source.contains("downY = e.getY();")); + assertFalse(gestureFile + " must not rely on onDown for the down point", + methodBody(source, "public boolean onDown(@NonNull MotionEvent e)", "\n }").contains("downY = e.getY();")); + // 切集方向在短剧下固定,不跟随直播的「反转」开关。 + assertTrue(gestureFile + " must pin the short drama fling direction", + source.contains("boolean invert = !shortDrama && LiveSetting.isInvert();")); + + // onDown 在边缘/缩放/锁定时提前返回不走 reset(),所以每次抬手都要主动清标记, + // 否则上一次的 changeBright + anchorY 会让下一次手势没长按就跳亮度。 + assertTrue(gestureFile + " must clear gesture flags when the stream ends", + source.contains("private void clearGesture()") && source.contains("if (end) clearGesture();")); + assertTrue(gestureFile + " must reset the adjust anchor on cleanup", + methodBody(source, "private void clearGesture()", "\n }").contains("anchorY = Float.NaN;")); + // 没有本次手势自己建立的基准就不许调节,避免 NaN 基准算出静音/跟随系统亮度。 + assertTrue(gestureFile + " must require an anchor established by this gesture", + source.contains("if (!changeSpeed && Float.isNaN(anchorY)) return;")); + // CANCEL(被父容器拦截/来电)同样要交还倍速,否则播放卡在长按后的速率。 + assertTrue(gestureFile + " must hand back the speed boost on cancel too", source.contains("if (changeSpeed && end) listener.onSpeedEnd();")); + // ACTION_POINTER_UP 不会复位 multiTouch,用实时指数判断才不会永久挡掉单指调节。 + assertTrue(gestureFile + " must gate the adjust on the live pointer count", + source.contains("action == MotionEvent.ACTION_MOVE && e.getPointerCount() == 1")); + // 未测量的播放视图会让 deltaY/height 变成 Infinity/NaN,音量瞬间拉满或静音。 + assertTrue(gestureFile + " must floor the view height before dividing", + methodBody(source, "private void setVolume(float deltaY)", "\n }").contains("Math.max(videoView.getMeasuredHeight(), 1)")); + assertTrue(gestureFile + " must skip volume when the stream has no range", + source.contains("if (maxVolume <= 0) return;")); + } + + // 手势轴向必须由「当前是否处于短剧全屏」推导:退出全屏回到内嵌小窗后若仍是短剧那套, + // 详情页上竖滑就会误切集;换到另一部短剧时形态不变,标记也不该被清掉。 + String video = new String(Files.readAllBytes(findMobileJavaPath().resolve(Path.of("com", "fongmi", "android", "tv", "ui", "activity", "VideoActivity.java"))), StandardCharsets.UTF_8); + assertTrue("the gesture mode must be derived from the current presentation", + video.contains("mKeyDown.setShortDrama(isFullscreen() && isShortDramaSession());")); + assertFalse("no call site may pin the gesture mode to a literal", + video.contains("mKeyDown.setShortDrama(true)") || video.contains("mKeyDown.setShortDrama(false)")); + for (String host : Arrays.asList("private void enterShortDramaFullscreen()", "private void enterFullscreen()", "private void exitFullscreen()", "protected void onNewIntent(Intent intent)")) { + int start = video.indexOf(host); + assertTrue(host + " must exist in VideoActivity", start >= 0); + int end = video.indexOf("\n }", start); + assertTrue("presentation change must resync the gesture axes: " + host, + end > start && video.substring(start, end).contains("syncShortDramaGesture();")); + } + + String tmdb = new String(Files.readAllBytes(findMainJavaPath().resolve(Path.of("com", "fongmi", "android", "tv", "ui", "activity", "TmdbDetailActivity.java"))), StandardCharsets.UTF_8); + assertTrue("the inline gesture mode must be derived from the current presentation", + tmdb.contains("inlineGestureDetector.setShortDrama(inlineFullscreen && shouldUseInlineShortDramaMode());")); + assertFalse("no inline call site may pin the gesture mode to a literal", + tmdb.contains("inlineGestureDetector.setShortDrama(true)") || tmdb.contains("inlineGestureDetector.setShortDrama(false)")); + // enterInlineFullscreen 要直接重算:手动点全屏不走 applyInlineShortDramaMode。 + // exitInlineFullscreen 经 resetInlineShortDramaMode 间接重算(它先置 inlineFullscreen=false)。 + for (String host : Arrays.asList("private void applyInlineShortDramaMode()", "private void resetInlineShortDramaMode()", "private void enterInlineFullscreen()")) { + int start = tmdb.indexOf(host); + assertTrue(host + " must exist in TmdbDetailActivity", start >= 0); + int end = tmdb.indexOf("\n }", start); + assertTrue("presentation change must resync the inline gesture axes: " + host, + end > start && tmdb.substring(start, end).contains("syncInlineShortDramaGesture();")); + } + int exitInline = tmdb.indexOf("private void exitInlineFullscreen()"); + assertTrue("exitInlineFullscreen must exist", exitInline >= 0); + String exitBody = tmdb.substring(exitInline, tmdb.indexOf("\n }", exitInline)); + int cleared = exitBody.indexOf("inlineFullscreen = false;"); + int resync = exitBody.indexOf("resetInlineShortDramaMode();"); + assertTrue("leaving inline fullscreen must resync the gesture axes after clearing the flag", + cleared >= 0 && resync > cleared); + } + @Test public void mobileShortDramaQualityIconHasSingleSourceOfTruth() throws Exception { // setQualityVisible 有 6 个调用点,其中多处显式传 false(未选中集数、切线路重置), @@ -3501,4 +3633,55 @@ public class VideoActivityLayoutTest { int second = source.indexOf("android:id=\"@+id/" + secondId + "\""); return first >= 0 && second >= 0 && first < second; } + + /** + * 原生选集列表模式保持单行横向滚动。 + * + * 「按钮内文本居中」的诉求由 adapter_episode_hori.xml 的 gravity=center 加左右成对内边距 + * 满足,不是把整条列表改成换行居中的 Flexbox —— 那会让列表模式看起来像网格模式, + * 两种视图模式失去区分。 + */ + @Test + public void mobileEpisodeListModeStaysHorizontalSingleRow() throws Exception { + Path sourcePath = findMobileJavaPath().resolve(Path.of("com", "fongmi", "android", "tv", "ui", "activity", "VideoActivity.java")); + String source = new String(Files.readAllBytes(sourcePath), StandardCharsets.UTF_8); + + int method = source.indexOf("private void updateEpisodeLayout(List items, boolean useTmdbCard)"); + assertTrue(sourcePath + " is missing updateEpisodeLayout", method >= 0); + int gridBranch = source.indexOf("int span = getEpisodeSpan(items, useTmdbCard);", method); + String listBranch = source.substring(method, gridBranch); + + assertTrue("list mode must use a horizontal LinearLayoutManager", + listBranch.contains("new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)")); + assertFalse("list mode must not wrap items with a Flexbox layout manager", + listBranch.contains("FlexboxLayoutManager")); + assertFalse(sourcePath + " must not import FlexboxLayoutManager for the episode list", + source.contains("import com.google.android.flexbox.FlexboxLayoutManager;")); + } + + /** + * 原生选集按钮的文本靠左右成对内边距居中。 + * + * shape_video_item 自带 12dp 左右内边距,setPadding 只覆盖左边会把右边一起清成 0, + * 文本随之偏向一侧。徽标可见时左边额外让出 92dp 供徽标占位。 + */ + @Test + public void mobileEpisodeHoriTextKeepsSymmetricHorizontalPadding() throws Exception { + Path sourcePath = findMobileJavaPath().resolve(Path.of("com", "fongmi", "android", "tv", "ui", "holder", "EpisodeHoriHolder.java")); + String source = new String(Files.readAllBytes(sourcePath), StandardCharsets.UTF_8); + + assertTrue(sourcePath + " must resolve a shared horizontal padding", + source.contains("int horizontal = ResUtil.dp2px(12);")); + assertTrue(sourcePath + " must apply the same padding on both sides", + source.contains("binding.text.setPadding(visible ? ResUtil.dp2px(92) : horizontal, binding.text.getPaddingTop(), horizontal, binding.text.getPaddingBottom());")); + + Path layout = findMobileResPath().resolve(Path.of("layout", "adapter_episode_hori.xml")); + String xml = new String(Files.readAllBytes(layout), StandardCharsets.UTF_8); + int text = xml.indexOf("android:id=\"@+id/text\""); + int card = xml.indexOf("android:id=\"@+id/card\""); + assertTrue(layout + " is missing @+id/text", text >= 0); + assertTrue("the episode button text must be centered inside the button", + xml.indexOf("android:gravity=\"center\"", text) > text + && xml.indexOf("android:gravity=\"center\"", text) < card); + } } diff --git a/app/src/testMobile/java/com/fongmi/android/tv/ui/adapter/TmdbEpisodeAdapterTest.java b/app/src/testMobile/java/com/fongmi/android/tv/ui/adapter/TmdbEpisodeAdapterTest.java index a27e27b66e..ea23c7aa51 100644 --- a/app/src/testMobile/java/com/fongmi/android/tv/ui/adapter/TmdbEpisodeAdapterTest.java +++ b/app/src/testMobile/java/com/fongmi/android/tv/ui/adapter/TmdbEpisodeAdapterTest.java @@ -1,5 +1,7 @@ package com.fongmi.android.tv.ui.adapter; +import com.fongmi.android.tv.ui.helper.TmdbEpisodeGridPolicy; + import org.junit.Test; import java.nio.charset.StandardCharsets; @@ -11,6 +13,30 @@ import static org.junit.Assert.assertTrue; public class TmdbEpisodeAdapterTest { + @Test + public void nativeEnhancedNonCardGridUsesStandardEpisodeHeight() { + assertEquals(TmdbEpisodeGridPolicy.GRID_CARD_HEIGHT_DP, + TmdbEpisodeAdapter.nativeEnhancedGridCardHeightDp(false, false)); + assertEquals(TmdbEpisodeGridPolicy.GRID_CARD_HEIGHT_DP, + TmdbEpisodeAdapter.nativeEnhancedGridCardHeightDp(true, false)); + assertEquals(TmdbEpisodeGridPolicy.NATIVE_MOBILE_GRID_CARD_HEIGHT_DP, + TmdbEpisodeAdapter.nativeEnhancedGridCardHeightDp(true, true)); + assertEquals(TmdbEpisodeGridPolicy.NATIVE_GRID_CARD_HEIGHT_DP, + TmdbEpisodeAdapter.nativeEnhancedGridCardHeightDp(false, true)); + } + + @Test + public void nativeEnhancedGridUsesOneHeightForEveryItemOnThePage() throws Exception { + String source = tmdbEpisodeAdapterSource(); + + assertTrue("native-enhanced grid sizing must use one page-wide TMDB data decision", + source.contains("private boolean pageHasTmdbEpisodeData;") + && source.contains("pageHasTmdbEpisodeData = hasPageTmdbEpisodeData();") + && source.contains("applyCardSize(holder, compact, pageHasTmdbEpisodeData);") + && source.contains("private boolean hasPageTmdbEpisodeData()") + && !source.contains("applyCardSize(holder, compact, tmdbEpisode != null);")); + } + @Test public void nativeEnhancedPhoneGridUsesReadableCleanTitle() { assertEquals("2. 觉醒", TmdbEpisodeAdapter.nativeEnhancedIndexTitle("完美世界_02 2. 觉醒", "2. 觉醒", true, TmdbEpisodeAdapter.Mode.GRID)); @@ -55,7 +81,7 @@ public class TmdbEpisodeAdapterTest { String source = tmdbEpisodeAdapterSource(); int setMode = source.indexOf("public void setMode(Mode mode)"); int setGridSpan = source.indexOf("public void setGridSpanCount(int gridSpanCount)"); - int applyCardSize = source.indexOf("private void applyCardSize(ViewHolder holder, boolean compact)"); + int applyCardSize = source.indexOf("private void applyCardSize(ViewHolder holder, boolean compact, boolean hasTmdbEpisodeData)"); assertTrue("TMDB episode adapter must rebind visible cards when grid/list style changes", setMode >= 0 @@ -73,12 +99,12 @@ public class TmdbEpisodeAdapterTest { @Test public void gridEpisodeCardsUseSymmetricHorizontalMargins() throws Exception { String source = tmdbEpisodeAdapterSource(); - int method = source.indexOf("private void applyCardSize(ViewHolder holder, boolean compact)"); + int method = source.indexOf("private void applyCardSize(ViewHolder holder, boolean compact, boolean hasTmdbEpisodeData)"); int methodEnd = source.indexOf("private boolean nativeEnhancedMobileGrid", method); String body = method >= 0 && methodEnd > method ? source.substring(method, methodEnd) : ""; assertTrue("grid episode cards must split their spacing between start and end so outer margins stay balanced", - body.contains("int gridSpacing = dp(holder.itemView, isNativeEnhanced() ? 12 : 8);") + body.contains("int gridSpacing = dp(holder.itemView, standardGridItem ? 8 : isNativeEnhanced() ? 12 : 8);") && body.contains("int marginStart = mode == Mode.GRID ? gridSpacing / 2 : 0;") && body.contains("marginParams.setMarginStart(marginStart);") && body.contains("marginParams.getMarginStart() != marginStart")); diff --git a/app/src/testMobile/java/com/fongmi/android/tv/ui/dialog/ConfigDialogChooseDirTest.java b/app/src/testMobile/java/com/fongmi/android/tv/ui/dialog/ConfigDialogChooseDirTest.java index 20dd4a33c8..b2bd805ae2 100644 --- a/app/src/testMobile/java/com/fongmi/android/tv/ui/dialog/ConfigDialogChooseDirTest.java +++ b/app/src/testMobile/java/com/fongmi/android/tv/ui/dialog/ConfigDialogChooseDirTest.java @@ -32,10 +32,15 @@ public class ConfigDialogChooseDirTest { /** 入口只写方法不接线等于没有,所以单独钉住监听器注册。 */ @Test public void directoryChooserIsWiredToAControl() throws Exception { - assertTrue("mobile 要把选目录挂到输入框的 startIcon(endIcon 已被选文件占用)", - read(MOBILE).contains("binding.choose.setStartIconOnClickListener(this::onChooseDir);")); + String mobile = read(MOBILE); + String leanback = read(LEANBACK); + assertTrue("mobile 只有点播配置显示目录入口,避免给直播/壁纸保存无效路径", + mobile.contains("binding.choose.setStartIconVisible(type == 0);") + && mobile.contains("if (type == 0) binding.choose.setStartIconOnClickListener(this::onChooseDir);")); assertTrue("leanback 要把选目录挂到独立按钮", - read(LEANBACK).contains("binding.chooseDir.setOnClickListener(this::onChooseDir);")); + leanback.contains("binding.chooseDir.setOnClickListener(this::onChooseDir);")); + assertTrue("leanback 只有点播配置显示目录入口,避免给直播/壁纸保存无效路径", + leanback.contains("binding.chooseDir.setVisibility(type == 0 ? View.VISIBLE : View.GONE);")); } /** 选文件那条路不能被顶掉:本地包 zip 仍然靠它选。 */ @@ -55,6 +60,34 @@ public class ConfigDialogChooseDirTest { read("app/src/leanback/res/layout/dialog_config.xml").contains("android:id=\"@+id/chooseDir\"")); } + /** + * 配置导入要落到不会被系统清理的目录。 + * + *

「同一份内容只存一份」「流会关闭」这些语义由 {@code FileChooserImportTest} 做真实 + * 行为验证,这里只钉住入口和目标目录——那两条是编译期看不出来的接线。 + */ + @Test + public void configImportUsesPersistentDirectory() throws Exception { + String chooser = read("app/src/main/java/com/fongmi/android/tv/utils/FileChooser.java"); + assertTrue("配置导入必须使用持久化 URI 路径,不能落到可清理 cache", + chooser.contains("public static String getPersistentPathFromUri(Uri uri)") + && chooser.contains("Path.files(\"cat_source_imports\")")); + } + + /** 选完什么都不发生是最糟的失败方式,用户不知道该重选还是该换包。 */ + @Test + public void unreadableSelectionTellsTheUser() throws Exception { + for (String file : new String[]{MOBILE, LEANBACK}) { + assertTrue(file + " 读不到所选内容时必须给提示,不能静默 return", + read(file).contains("Notify.show(R.string.dialog_config_choose_failed);")); + } + // 漏 locale 只会在运行时炸,编译期查不出来。 + for (String values : new String[]{"values", "values-zh-rCN", "values-zh-rTW"}) { + assertTrue(values + " 缺 dialog_config_choose_failed", + read("app/src/main/res/" + values + "/strings.xml").contains("\"dialog_config_choose_failed\"")); + } + } + private static String read(String file) throws Exception { Path root = Files.exists(Path.of("app")) ? Path.of("") : Path.of(".."); return Files.readString(root.resolve(file), StandardCharsets.UTF_8).replace("\r\n", "\n"); diff --git a/app/src/testMobile/java/com/fongmi/android/tv/ui/helper/TmdbUIAdapterTest.java b/app/src/testMobile/java/com/fongmi/android/tv/ui/helper/TmdbUIAdapterTest.java index a98ca3e8bd..62b74fee3f 100644 --- a/app/src/testMobile/java/com/fongmi/android/tv/ui/helper/TmdbUIAdapterTest.java +++ b/app/src/testMobile/java/com/fongmi/android/tv/ui/helper/TmdbUIAdapterTest.java @@ -624,7 +624,7 @@ public class TmdbUIAdapterTest { int firstPrepare = source.indexOf("prepareFastTmdbPlaybackHistory(item, flag, episode);", fastMethod); int prepare = source.indexOf("prepareFastTmdbPlaybackHistory(item, flag, episode);", startPending); int firstHistoryLookup = source.indexOf("History.findPlayback", fastMethod); - int player = source.indexOf("mViewModel.playerContent(getKey(), flag.getFlag(), episode.getUrl());", prepare); + int player = source.indexOf("mViewModel.playerContent(getKey(), flag.getFlag(), episode.getUrl(), applyHistoryPlayerKernel());", prepare); int fullBind = source.indexOf("applyFastTmdbPlaybackFullDetailNextFrame(item);", player); int canApply = source.indexOf("private boolean canApplyPlayerResult()"); int fastCanApply = source.indexOf("mFastPlaybackFlag != null && mFastPlaybackEpisode != null && mHistory != null", canApply); @@ -712,7 +712,7 @@ public class TmdbUIAdapterTest { String source = new String(Files.readAllBytes(sourcePath), StandardCharsets.UTF_8); int startPending = source.indexOf("private void startPendingFastTmdbPlayback()"); int prepareItem = source.indexOf("prepareFastTmdbPlaybackItem(item);", startPending); - int player = source.indexOf("mViewModel.playerContent(getKey(), flag.getFlag(), episode.getUrl());", prepareItem); + int player = source.indexOf("mViewModel.playerContent(getKey(), flag.getFlag(), episode.getUrl(), applyHistoryPlayerKernel());", prepareItem); int postHydrate = source.indexOf("mBinding.getRoot().post(() -> hydrateFastTmdbPlaybackDetail(item));", player); int initialHydrate = source.indexOf("hydrateFastTmdbPlaybackDetail(item);", source.indexOf("private boolean tryStartFastTmdbPlayback(Vod item)")); int hydrate = source.indexOf("private void hydrateFastTmdbPlaybackDetail(Vod item)"); @@ -905,7 +905,7 @@ public class TmdbUIAdapterTest { int activePlayer = source.indexOf("&& !player().isEmpty()", activeOwner); int updateResult = source.indexOf("currentInlineResult = result;", staleGuard); int updateParse = source.indexOf("useParse = result.shouldUseParse();", updateResult); - int switchResult = source.indexOf("player().switchPlayer(playerType, result, getHistoryKey(), metadata, useParse, position, speed, repeat);", updateParse); + int switchResult = source.indexOf("player().switchPlayer(playerType, result, activePlaybackKey(), metadata, useParse, position, speed, repeat);", updateParse); int oldFallback = source.indexOf("player().switchPlayerManually(playerType);", switchMethod); assertTrue(sourcePath + " is missing refreshed inline player-kernel switching", switchMethod >= 0 && refreshCall > switchMethod && refreshMethod > refreshCall); diff --git a/docs/C0-M-mpv-ffmpeg-9.0.1.md b/docs/C0-M-mpv-ffmpeg-9.0.1.md new file mode 100644 index 0000000000..4346bdc51e --- /dev/null +++ b/docs/C0-M-mpv-ffmpeg-9.0.1.md @@ -0,0 +1,92 @@ +# C0-M:MPV FFmpeg 9.0.1 独立重建 + +## Recovery anchor + +- Objective: move the MPV native build from FongMi FFmpeg `04482c8d13ac27b2a9fe93f5d388929eef8af5f4` to the Exo-validated `177f090e0503b7e013922ca903bde14b1c375f18`, while preserving the existing MPV patches, ABI namespace, renderer, decoder, audio, subtitle, disc, and JNI contracts. +- Authority: user approved implementation on 2026-08-29; scope is limited to C0-M. +- Baseline: branch `fongmi-sync`, HEAD `5f865d0dbdcc37dfc07f06a8d9514e4523eac0d0`; recovery tag `recovery/C0-M-MPV-FFMPEG-9.0.1/baseline-20260829105431-5f865d0dbdcc`. +- Protected dirty path: `AGENTS.md`; it remains outside the task commit. +- Scope: MPV FFmpeg lock/provenance, both ARM native asset sets, required build documentation, this record, and the master assessment status. +- Excluded: MPV/libplacebo/mpv-android revisions, Exo AARs, JNI source/API, C2 DV7-to-P8.1 activation, and unrelated App behavior. +- Status: completed and closed in `9b7cf9cfbbeac00b0e5a342d4c6071c2c2d7a223`; recovery tag `recovery/C0-M-MPV-FFMPEG-9.0.1/20260829122948-9b7cf9cfbbea`. +- Next action: keep C0-M closed. Handle the pre-existing no-Surface MediaCodec reinitialization during teardown as a separate lifecycle bug with its own task, scope, verification, commit, and rollback tag. + +## 1. User-visible capability + +This is a dependency safety and compatibility update. Normal MPV playback remains on the current paths, while malformed or unusually large MPEG-PS/TS, DASH, HEVC, RTP, AV1, WebP, and audio inputs get the FFmpeg 9.0.1 boundary and initialization fixes. Some 32-bit HEVC software-decoding paths also receive upstream arithmetic and branch optimizations. The new `dovi_rpu convert=p81` code present in the source is not enabled by this task. + +## 2. Source graph and provenance + +| Input | Baseline | Candidate | Role | +| --- | --- | --- | --- | +| `FongMi/FFmpeg` | `04482c8d13ac27b2a9fe93f5d388929eef8af5f4` | `177f090e0503b7e013922ca903bde14b1c375f18` | Only source revision changed by C0-M | +| `FongMi/mpv` | `cca559b41ceb0bb7731cf6ef2e1f33276cd30c42` | unchanged | Existing MPV source and local WebHTV patches | +| `FongMi/libplacebo` | `b694a21bf2dc176c1e98b8a13c6421a0de5f3da5` | unchanged | Static renderer dependency | +| `FongMi/mpv-android` | `99a60ad2141d5ace94453590903c2c6b9a0a2443` | unchanged | Build framework and JNI reference | + +The candidate FFmpeg parent chain contains 49 audited commits. Commits 1–26 are 9.0.1 maintenance/security/version changes; 27–48 are rebase-equivalent or already covered behavior; 49 adds `dovi_rpu convert=p81` and remains disabled. C0-M rebuilds the coherent MPV graph from the candidate source, retaining `ffmpeg-webhtv-proxy-range.patch`, `ffmpeg-mediacodec-port-starvation.patch`, `libmv*`/`libmw*` renaming, and all existing MPV/Vulkan/DV/AudioTrack safeguards. + +## 3. Acceptance and rollback + +Acceptance requires both ARM ABIs to build from the candidate lock, the existing patch stack to apply without semantic drift, ELF `SONAME`/`DT_NEEDED` separation to remain intact, APK assets to match the candidate hashes, and focused playback/lifecycle checks to show no functional or material performance regression. The current `libplayer.so` remains unchanged unless an actual client-API incompatibility is proven. + +Rollback is the baseline tag above or a revert of the atomic C0-M commit, restoring `third_party/mpv-native-lock.json`, provenance records, and both ABI MPV assets together. Exo's already-published FFmpeg 9.0.1 AAR is not part of this rollback. + +## 4. Implementation record + +### 2026-08-29 10:54 CST — approved start + +- Task guard: `C0-M-MPV-FFMPEG-9.0.1`, mode `upstream`. +- Baseline tag created before edits: `recovery/C0-M-MPV-FFMPEG-9.0.1/baseline-20260829105431-5f865d0dbdcc`. +- Initial dirty state: only `AGENTS.md`, preserved and excluded. +- Result: `scripts/build_mpv_native.sh --abi all --prepare-only` passed in about 9 seconds. FFmpeg `177f090e0503b7e013922ca903bde14b1c375f18`, mpv-android, mpv, and libplacebo were pinned successfully; the existing proxy Range, MediaCodec starvation, Vulkan shader, and P2 patch checks passed. +- Next action: run one clean two-ABI native build/install. + +### 2026-08-29 12:05 CST — dual-ABI build and deterministic verification + +- The single planned `scripts/build_mpv_native.sh --abi all --install --jobs 8` run completed successfully for `arm64-v8a` and `armeabi-v7a`. FFmpeg 9.0.1, the unchanged MPV/libplacebo graph, and all existing local patches compiled and linked without errors; only existing dependency/compiler warnings were emitted. +- `libplayer.so` was preserved byte-for-byte. Its current Git object IDs match the baseline for both ABIs: arm64 `f5aa3274174503014210dd4558003e11351aca73`, armv7 `2a3435a7f89ff6dd74a3f7538baf6db275b379b3`. +- `bash scripts/verify_mpv_native_assets.sh --require-elf` passed for both ABIs, including lock provenance, stable Vulkan shader contract, P2 patch scope, ELF `SONAME`/`DT_NEEDED`, namespace, and packaging rules. +- `bash ./gradlew :app:assembleMobileArm64_v8aDebug --no-daemon` passed in 59 seconds. The APK is `app/build/outputs/apk/mobileArm64_v8a/debug/app-mobile-arm64_v8a-debug.apk`. +- The combined committed native payload grows by only 6,316 bytes before APK compression: arm64 +3,176 bytes and armv7 +3,140 bytes. `libmpv.so` is unchanged in arm64 size and 32 bytes smaller in armv7; the increase is confined to FFmpeg component libraries. +- Native asset SHA-256 values: + +| ABI | Library | SHA-256 | +| --- | --- | --- | +| arm64-v8a | `libmpv.so` | `8ffa22949f3e99c0425e6c1154e294294c65c70025bbad485d835395b91b1e80` | +| arm64-v8a | `libmvcodec.so` | `615f1f8dfb20f4deca8a1cc5506178f0b9dd2ffd24d778845db69726f0d5b734` | +| arm64-v8a | `libmvdevice.so` | `da88a7db8b5cb01dc946b4957ae9b7276f043b387e10af9c46272a41c7ecb53e` | +| arm64-v8a | `libmvfilter.so` | `58593467521973c86eed1c703e8ac85d21e1c136251e9bde17155c4bb9c6e8bc` | +| arm64-v8a | `libmvformat.so` | `8ea1973b30262bf4e89c1d68e582aaa1298111310001e15abfb7fe329e6cdd1a` | +| arm64-v8a | `libmvutil.so` | `06b12c501e678f6206cee88c46a7966f667879d876a038ccdb7cae9ac2654291` | +| arm64-v8a | `libmwresample.so` | `b363207d482ee2dbce63c10b90e335c19a20039f26e086be9476cb08c4780815` | +| arm64-v8a | `libmwscale.so` | `5bbe36d1b068d2e51520a6ccac6bbc2f09ea34e0215b717b77fdc159d0282fa8` | +| armeabi-v7a | `libmpv.so` | `b24f28f88fe1d560003d5f8db719c81d57aaece7489c5dc9a248cba41c678898` | +| armeabi-v7a | `libmvcodec.so` | `9c31756aee4365df899a233e57f48206afcfae73ad258b93bff20c551457507e` | +| armeabi-v7a | `libmvdevice.so` | `58150681bb12356108014297439c5393bb87b0cb0621a5e30b6c30fcce416d3e` | +| armeabi-v7a | `libmvfilter.so` | `b48111a074c87f947edde54c12d0e6e71a492802e539cac4894d110a84c8c36a` | +| armeabi-v7a | `libmvformat.so` | `d9e135c02a58f53ea9fb0a87bed1d665dceedd1b8546ba76f8eaf171b1c54a30` | +| armeabi-v7a | `libmvutil.so` | `e41bb8455a23593d61c97fdaf23e42672787fb3cb240dcb34cec7b968209789f` | +| armeabi-v7a | `libmwresample.so` | `4a3a84a0e716f32d039d56377ef9d34365294e590b67bc930a7db2855bd175e3` | +| armeabi-v7a | `libmwscale.so` | `563b154eea57805ad96e629ddf2d2f604ede89a718c22ba0449abaa4551fda80` | + +- Device gate: `adb devices -l` returned no device, and the prior Wi-Fi endpoint `192.168.1.9:5555` refused one reconnect attempt. No repeated connection checks were made. Runtime acceptance, commit, and recovery tag remain intentionally pending. + +### 2026-08-29 12:20 CST — focused device playback and lifecycle verification + +- Device: vivo V2453A (`10CF6H1D2L0009S`), Android arm64-v8a. The current arm64 debug APK was installed once and App preference `player=2` confirmed that the exercised path was MPV. +- Command-driven local playback covered subtitle-bearing MKV, AAC 5.1, E-AC3/Atmos DDP, TrueHD 7.1, DTS-HD MA 5.1, LPCM 7.1, and DTS 5.1 in TS. Every input entered `VideoActivity` and produced MPV `file-loaded`, audio/video reconfiguration, and `playback-restart` evidence without decode initialization failure. +- AAC, TrueHD, LPCM, and DTS TS were observed actively advancing. E-AC3 and DTS-HD MA loaded and configured successfully; their paused state came from the existing playback-history position rather than a decoder error. +- The TS case continued playing after HOME moved the Activity into picture-in-picture. A command-driven fast-forward advanced the position from `81234 ms` to `87220 ms`, including about three seconds of expected playback progress during the observation window. +- Stop/exit produced MPV `end-file` and `shutdown`. The crash buffer was empty, with no Java crash, SIGSEGV, or SIGABRT. +- Remaining risk: during picture-in-picture teardown, the BufferQueue was abandoned and FFmpeg then logged `h264_mediacodec: Both surface and native_window are NULL` twice while creating decoder components that were immediately released. Source review shows `ff_mediacodec_surface_ref()` emits this error and returns `NULL` when decoder initialization has neither a Java `Surface` nor an `ANativeWindow`; it is not a normal unref message. The focused run had no port-starvation/decode-failure precursor and proceeded to `end-file`/`shutdown` without crash. The same message exists in pre-C0-M device logs, so it is a pre-existing teardown lifecycle race rather than a regression introduced by FFmpeg 9.0.1. It remains a separate bug because the unnecessary decoder initialization should be suppressed after Surface loss. +- Existing unrelated warnings `Error parsing option http-allow-redirect` and `mpv_get_property(...demuxer-cache-state...) error` remain unchanged and are outside this dependency-only task. +- Conclusion: C0-M meets the available-device release gate. MPV now independently uses the same FFmpeg 9.0.1 source revision as Exo while retaining its separate ABI namespace, build graph, renderer/decoder/audio policies, JNI binary, and rollback boundary. + +### 2026-08-29 12:34 CST — atomic implementation closure + +- Implementation commit: `9b7cf9cfbbeac00b0e5a342d4c6071c2c2d7a223` (`build(mpv): align FFmpeg with 9.0.1`). +- Recovery tag: `recovery/C0-M-MPV-FFMPEG-9.0.1/20260829122948-9b7cf9cfbbea`; task guard created it immediately after the commit in 0 seconds. +- Commit scope: the FFmpeg source lock/provenance update, both ARM ABI MPV/FFmpeg asset sets, build and user documentation, this task record, and the master assessment index. Protected pre-existing `AGENTS.md` was not staged or committed. +- Verification recorded in the commit: prepare-only, one dual-ABI native build/install, ELF/assets validation, Mobile arm64 debug APK build and asset identity, plus V2453A MPV subtitle/audio/video playback, seek, picture-in-picture, stop/shutdown, and crash-buffer checks. +- Rollback: revert `9b7cf9cfbbeac00b0e5a342d4c6071c2c2d7a223` or reset the complete C0-M-owned paths to the baseline tag `recovery/C0-M-MPV-FFMPEG-9.0.1/baseline-20260829105431-5f865d0dbdcc`; do not partially mix the old FFmpeg component libraries with the new `libmpv.so` graph. diff --git a/docs/C2-dv7-p81-bsf.md b/docs/C2-dv7-p81-bsf.md new file mode 100644 index 0000000000..c0f1ba75cb --- /dev/null +++ b/docs/C2-dv7-p81-bsf.md @@ -0,0 +1,265 @@ +# C2-DV7-P81-BSF:MPV Profile 7 到 P8.1 的显式转换 + +## Recovery anchor + +- 目标:按设备能力自动选择 DV7 原生、P8.1 或 HDR10:原生 DV7 始终优先;设备不支持 DV7 时按用户选择尝试 P8.1 或直接 HDR10;P8.1 不支持/失败必须自动回退 HDR10。 +- 任务范围:MPV native patch/build 接线、MPV 两态用户设置与本任务文档/总索引;原生 DV7 保留仅作为内部能力结果,不作为用户选项;不修改 Exo、JNI、Vulkan、AudioTrack、网络或现有 HDR10/Surface 安全补丁。 +- 基线:`fongmi-sync` @ `5e90c2ed76830f5c45988d8597d14ffd599dba34`;恢复 tag:`upstream/mpv/c2-dv7-p81-bsf-baseline-20260829`。 +- 保护 dirty 路径:无。 +- 验收:patch 可按当前锁定 MPV 树应用;Java 编译通过;两 ABI native 产物/ELF/资产校验通过;原生 DV7、P8.1、HDR10、seek/flush/换源和失败回退有证据。 +- 当前状态:arm64 已通过删除失效 `HEVC_CONF` 修复 TCL MT9655 卡死;同一本地 DV7 FEL 转换起播仍有约 4--5.5 秒先出声音、后出画的体验问题,MPV 参数面板也因转换后轨道资料变为 Profile 8 而丢失源 DV7 身份。 +- 已完成:创建 baseline tag;完成 C2 patch、两态 UI、原生 DV7 优先、P8.1 能力门和 HDR10 自动回退;修复 P8.1 packet/CSD 不一致黑屏和失效 `HEVC_CONF`;Leanback arm64 实机已确认正常画面、DV8 识别、零丢帧且无 decoder release。 +- 已完成:章节查询门控修复已原子提交并创建恢复 tag;电视实机回归仍受 ADB 离线限制。 +- 下一动作:保留转换前源 DV profile/level,并增加 direct MediaCodec 每会话一条的首输出时间;构建 Leanback arm64 后用同一 P7 FEL 样片一次区分 decoder/VO 首帧延迟与面板遥测延迟,再只修复已证实的启动环节。 + +## 决策与来源 + +### 上游来源 + +| 仓库 | 完整 commit | 作用 | WebHTV 处置 | +| --- | --- | --- | --- | +| `FongMi/FFmpeg` | `177f090e0503b7e013922ca903bde14b1c375f18` | `dovi_rpu` BSF 的 `convert=p81`,改写 DV metadata/CSD、删除 EL NAL | 复用已锁定并已由 C0-M 验证的输入;只在 MPV 显式模式调用 | +| `FongMi/mpv` | `cca559b41ceb0bb7731cf6ef2e1f33276cd30c42` | 当前 `dovi_split`、lavf/Matroska demux 生命周期和 decoder/output 消费者 | 在本地锁定树上窄适配,不替换整树 | +| `FongMi/mpv-android` | `eabfaf9501fc08fb726953a9328da43ae4154d35` | 当前 Android native 构建框架和 ABI 打包 | 只沿用现有构建链;无 JNI/API 变化 | + +FFmpeg 的 `dovi_rpu` 必须与 MPV 的 `dovi_split` 共享同一 AVCodecParameters/packet 生命周期。C0-M 已把 MPV FFmpeg 锁定到 `177f090...`,因此 C2 不再改 lock;MPV 与 Exo 仍分别构建和回滚。 + +### 本地现状 + +- `mpv-dovi-profile7-hdr10-base-layer.patch` 已实现 `preserve|hdr10` 两态、BL-only packet 过滤、`par_out`/metadata 同步、错误传播和 `INT_MAX` 防护。 +- MPV 的 `demux/dovi_split.c` 目前只创建 `dovi_split`,不能调用 `dovi_rpu`;App 只把 MPV 旧布尔值映射成 `hdr10|preserve`。 +- Exo 已有独立 `DolbyVisionP81ExtractorsFactory`/libdovi 链路,C2 不替换该实现。 + +## 最终行为 + +MPV UI 只保留两种非原生兼容策略: + +- `升级P8.1`:默认;设备不能原生播放 DV7、但声明支持对应 P8.1 时使用 FFmpeg `dovi_rpu` 转换; +- `降级HDR10`:设备不能原生播放 DV7 时直接使用 BL-only HDR10 fallback。 + +设备能够原生播放当前 DV7 profile/level/分辨率时,无论上述 fallback 选择为何都保留原始 DV7。P8.1 静态能力不成立、转换失败或解码运行时失败时只自动重试一次 HDR10,不能保持黑屏;`preserve` 仍是内部自动结果,不再是用户选项。 + +P8.1 仅对 HEVC、Profile 7、存在有效 RPU+BL 配置记录的轨道生效。BSF 初始化、send/receive、损坏 NAL 或内存失败均不会静默改变默认路径;当前 demux 调用方会丢弃失败 AU 并记录明确错误,换源、seek、flush 继续复用现有 reset 生命周期。 + +## 方案比较 + +- 不变:风险最低,但 MPV 无法使用已锁定 FFmpeg 的 P8.1 转换能力。 +- 直接整合上游:代码量少,但会绕过 WebHTV 的双态用户策略、packet ownership 和现有 HDR10 decoder gate,容易改变默认行为。 +- 本次窄适配:只增加一个 BSF 选择和一条 packet 替换路径,默认仍 `hdr10`,并复用已有错误/flush/Surface 保护;这是本项目的推荐方案。 + +## 收益、风险与影响 + +- 收益:不支持 DV7 原生解码但支持 P8.1 的设备可显式播放动态 RPU,色彩和高光映射优于丢弃全部 RPU 的 HDR10 fallback;转换在 demux 层完成,不增加 renderer 循环开销。 +- 缺点/风险:每个 DV7 AU 需要一次 BSF 解析/重写;损坏或非标准 RPU 可能失败;厂商对 Profile 8.1 CSD 的接受度仍需实机覆盖。 +- 兼容性:原生 DV7 能力优先;旧 `true` 映射 HDR10、旧 `false` 映射 P8.1;P8.1 默认仅在能力门通过后启用,否则自动 HDR10。无 JNI/API/ABI 名称变化。 +- 性能/包体积:native 代码复用已编译的 FFmpeg `dovi_rpu`,不新增独立库;P8.1 模式增加 CPU 解析成本,其他模式无额外路径。 +- 最佳实践:遵循 FFmpeg 官方 BSF 的配置/初始化/flush/packet ownership 约定,同时保留 WebHTV 的失败回退和会话策略,优于盲目 cherry-pick。 +- 上游调整:需要。上游 BSF 本身不负责 MPV 的用户策略、demux packet 所有权和 Android decoder/output 选择,必须由本地适配补齐。 + +## 实施阶段与验证 + +1. 增加 `mpv-dovi-profile7-p81.patch`,扩展 demux option、`dovi_split` 选择和 P8.1 参数同步;在构建脚本中按现有 patch 顺序应用并增加 marker 校验。 +2. 将 MPV 设置从旧布尔值迁移为两个用户选项,`MpvPlayerEngine` 内部仅传递 `preserve|p81|hdr10`;不改变 Exo 两态行为。 +3. 运行 `git apply --check`/shell syntax/Java 编译;随后按同一 lock 做 arm64-v8a 与 armeabi-v7a native build 或在环境缺失时记录阻塞。 +4. 设备验证:DV7 原生/P8.1/HDR10 开播、seek、暂停恢复、换源和 EOF;无 RPU、无 BL、损坏 NAL、BSF 初始化失败回退;普通 HDR10/DV5/音频样片无行为变化。 + +## 回滚 + +先恢复 `upstream/mpv/c2-dv7-p81-bsf-baseline-20260829`;发布后按原子 commit 恢复 C2 patch、设置接线和 native assets,保留 C0-M/P2-2/P3/P4 已验证能力。 + +## 实施记录 + +### 2026-08-29 14:42 CST + +- 已启动 `task_guard`:`C2-DV7-P81-BSF`,范围锁定为本文件、总索引、C2 patch、MPV build/verify 脚本和四个 App 设置/engine 文件。 +- 已创建 baseline tag;尚未修改代码或 lock。 + +### 2026-08-29 15:18 CST:实现与静态验证 + +- 已完成 C2 patch:`demuxer-dovi-profile7=p81` 仅在 HEVC/Profile 7 且有效 RPU+BL 配置存在时选择 `dovi_rpu`,同步 `par_out`/Profile 8 参数,复用已有 packet ownership、flush/seek 和错误路径;`preserve`/`hdr10` 逻辑保持。 +- 已完成 App 三态:旧 MPV 布尔设置兼容映射为 `hdr10`(默认)/`preserve`,新增显式 `p81`;Exo 两态 API 不变。 +- 已通过:`bash .codex/scripts/task_guard.sh check`、`bash -n scripts/build_mpv_native.sh`、`git diff --check`、在现有 HDR10 patch 后的临时 MPV 树上 `git apply --check --recount`。 +- Gradle 尝试:`:app:compileDebugJavaWithJavac` 不存在;任务枚举在隔离缓存首次下载 Gradle 时无输出,已中止,待使用项目实际任务或仅记录环境限制。 + +### 2026-08-29 17:04 CST:首轮实机失败与方案纠正 + +- 双 ABI native ELF/marker/依赖校验已通过,`:app:assembleMobileArm64_v8aDebug` 成功,ADB 安装成功。 +- vivo V2453A(Android 15、设备无 DV 解码能力)选择首轮“升级P8.1”后黑屏;日志持续出现 `hevc_mediacodec: No start code is found`。检查确认 C2 patch 更新了 P8.1 codec parameters,却遗漏让 `mp_dovi_split_filter_base()` 在 `convert_p81` 时替换原 packet,形成 Annex-B 参数与原 NALFF packet 不一致。 +- 用户纠正产品策略:删除多余的“保留DV7”选项;设备支持 DV7 时始终原样播放;否则只提供 P8.1/HDR10 两态,P8.1 不支持或失败自动 HDR10。P8.1 作为默认 fallback,重置按钮也必须恢复该默认值。 + +### 2026-08-29 17:20 CST:C2 收敛修正 + +- Native packet 过滤必须同时覆盖 `base_only` 与 `convert_p81`;否则 P8.1 codec parameters 已切到 Annex-B,而原始 Matroska NALF packet 仍会送入 MediaCodec,复现黑屏和 `No start code is found`。 +- P8.1 请求缺少有效 Profile 7 RPU+BL 配置,或 `dovi_rpu` 不可用时,native 层改用 HDR10 base-layer 过滤,不再保留不受支持的 DV7 bitstream。 +- 待完成:应用最终 patch、策略单测、双 ABI native 重建与 `mobileArm64_v8aDebug`/`leanbackArm64_v8aDebug` 构建,然后在非 DV 设备确认默认 P8.1 自动落到 HDR10 且无 `No start code`。 + +### 2026-08-29 19:59 CST:最终构建与收尾验证 + +- `bash scripts/verify_mpv_native_assets.sh --require-elf` 通过:`arm64-v8a`、`armeabi-v7a` 的 ELF、SONAME、DT_NEEDED、C2 marker 和资产集合均匹配;使用 NDK `29.0.14206865` 的 `llvm-readelf`。 +- `bash ./gradlew :app:assembleMobileArm64_v8aDebug :app:assembleLeanbackArm64_v8aDebug --no-daemon` 通过,耗时 3 分 43 秒。产物:`app/build/outputs/apk/mobileArm64_v8a/debug/app-mobile-arm64_v8a-debug.apk`(SHA-256 `2c5b6ef8b0e73d9b79b95f9b655bc5fa619018d2cdd3384ec373037fa97271e6`)和 `app/build/outputs/apk/leanbackArm64_v8a/debug/app-leanback-arm64_v8a-debug.apk`(SHA-256 `3867a8c7fb352815c7bfe4882301aefdd88fe6cc88c648ad9b03353c6ccdd392`)。 +- `bash ./gradlew :app:testMobileArm64_v8aDebugUnitTest --tests com.fongmi.android.tv.player.engine.MpvDolbyVisionFallbackPolicyTest --no-daemon` 通过,耗时 1 分 26 秒;覆盖原生 DV7 优先、P8.1 能力门和 HDR10 回退策略。 +- 尝试 `adb devices -l` 和 `adb connect 192.168.1.9:5555`;当前无在线设备,连接返回 `Connection refused`,因此未宣称本轮实机播放通过。此前首轮黑屏根因及修正已由日志和静态 patch 检查确认,最终包仍需设备在线后验证默认 P8.1/HDR10 实际解码路径。 + +### 2026-08-29 20:00 CST:提交与恢复锚点 + +- C2 原子提交:`ae337b81e44657d85050bee3a9f92a780fb418ab`(`mpv: complete DV7 to P8.1 fallback integration`)。 +- 恢复 tag:`recovery/C2-DV7-P81-BSF/20260829200055-ae337b81e446`。 +- 状态:实现、静态验证、native 资产验证、双端 arm64 包构建和策略单测已完成;实机验证因设备离线保留为明确剩余风险。回滚锚点为 `upstream/mpv/c2-dv7-p81-bsf-baseline-20260829`。 + +### 2026-08-29 20:41 CST:电视端 P8.1 启动卡死证据与修复决策 + +- TCL Smart TV Pro(Android 14/API 34,MT9655,arm64-v8a)使用 MPV、自动模式、硬解、默认“升级 P8.1”播放 `/storage/emulated/0/Download/P7_FEL_GIJoe_The_Rise_of_Cobra.mkv` 时复现卡死。 +- 直接证据:`/private/tmp/c2-tv-card-freeze-latest.log` 中 `20:41:16.858` 起主线程 watchdog 连续报告 `native=get-string:current-tracks/sub2/id`,耗时增长到 31 秒;栈固定为 `MpvPlayer.refreshTracks -> syncOsdSurfaceRequirementFromMpv -> MPVLib.getPropertyString`。没有 Java/native 崩溃或 MediaCodec fatal error。 +- 结论:`refreshTracks()` 在主线程无条件读取字幕 current-track;本次样片启动期间 MPV core 正忙于 P8.1 demux/BSF 工作,`current-tracks/sub2/id` 的同步读取把内部等待放大成 UI 卡死。该属性不是播放必需状态,且 direct output 默认 `sid=no`、`secondary-sid=no` 时无需读取。 +- 采用窄修复:新增 `MpvOsdSurfacePolicy.needsCurrentTrackQuery()`;两个字幕选择都明确禁用时直接关闭 OSD 请求并跳过 current-track 查询;`auto`、已选字幕和未知选择仍查询真实 current-track。`secondarySubtitleTrackId()` 同步遵循该规则,避免 debug/轨道快照再次触发同一阻塞。 +- 不修改 `dovi_rpu`、FFmpeg lock、MPV native 资产、解码器/渲染器选择或字幕菜单数据流;因此不增加包体积,不改变正常播放帧路径,回滚为本阶段单个 Java/测试提交。 +- 当前验收状态:策略单测和 Mobile arm64 Java 编译均通过;Leanback arm64 Debug APK 已构建(156,646,041 bytes,SHA-256 `74f3d70d9ccb5ab8edd09ead456706d661020f752d2a267cab23c91b9b6a7d0e`)。电视 ADB(`192.168.1.5:5555`)仍返回 `Connection refused`,所以 P7 FEL 自动模式实机回归尚未宣称通过。 +- 待设备上线后的最小验收:同一 P7 FEL 样片自动模式不再出现主线程 `current-tracks/sub2/id` 长时间阻塞;普通 P5/DV5、字幕 `auto`/已选路径保持可播放;日志无 Java/native crash、ANR 或 decoder fatal error。 + +### 2026-08-29 22:04 CST:原生 P8.1 能力确认与窄修复实施范围 + +- 用户确认:同一 TCL MT9655 电视播放原生 P8.1 样片正常,排除“电视不支持 P8.1 硬解”的解释。 +- 结论:当前故障限定为 DV7 FEL 经 FFmpeg `dovi_rpu convert=p81` 后的输出,或该输出在启动期间触发的 native 等待;不能通过删除 P8.1 选项或改变普通 P8.1 解码路径解决。 +- 批准的窄修复:在配置为 `p81` 的 MPV 会话中,文件加载到首次播放重启前不执行同步 `track-list/*` 刷新;若现有播放超时仍没有首帧,调用现有一次性 HDR10 回退并重建播放。已产生首帧的 P8.1、原生 DV7 和直接 HDR10 不触发该回退。 +- 不在本阶段处理:重新设计 `dovi_rpu`、替换 FFmpeg/MPV lock、修改 Exo、改变 Vulkan/Surface 策略、异步重写全部 MPV 属性 API。 +- 验收重点:普通 HDR10/DV5 轨道菜单和音频选择仍在首帧后刷新;P8.1 失败时主线程保持可响应并自动切 HDR10;回退仅发生一次,seek/换源/退出不改变既有生命周期。 + +### 2026-08-29 22:26 CST:窄修复验证 + +- 代码结果:`MpvPlayerConfig` 增加 P8.1 启动期轨道刷新门控;`MpvPlayer` 仅对 P8.1 会话延后 `FILE_LOADED`/启动期 `track-list/*` 同步查询,收到 `PLAYBACK_RESTART` 后恢复刷新;`restoreVideoTrackSelection` 同样受门控保护。普通 MPV 会话保持原有立即刷新路径。 +- 回退结果:`PlayerManager.onPlaybackTimeout()` 在无首帧且当前为 MPV P8.1 时调用现有一次性 `prepareDv7P81Hdr10Fallback()`,重建为 HDR10;已出首帧、原生 DV7 或已回退会话不会重复触发。 +- 定向单测:`bash ./gradlew :app:testMobileArm64_v8aDebugUnitTest --tests androidx.media3.mpvplayer.MpvTrackRefreshPolicyTest --tests com.fongmi.android.tv.player.engine.MpvDolbyVisionFallbackPolicyTest --no-daemon` 通过,耗时 3 分 1 秒。 +- Java 编译:`bash ./gradlew :app:compileMobileArm64_v8aDebugJavaWithJavac --no-daemon` 通过,耗时 2 分钟。 +- 电视包:`bash ./gradlew :app:assembleLeanbackArm64_v8aDebug --no-daemon` 通过,产物 `app/build/outputs/apk/leanbackArm64_v8a/debug/app-leanback-arm64_v8a-debug.apk`,大小 156646041 bytes,SHA-256 `e801f04e9e57baa3a537eb542b1b4a5b69f7e1c59993ac89dac4c56c6ff1379e`。 +- 环境限制:`adb devices -l` 当前无在线设备,未宣称电视实机回归通过;原生 P8.1 正常是用户实测事实,转换 P8.1 的设备接受度仍需在设备上线后验证。 + +### 2026-08-30 00:24 CST:电视再次复现与章节查询门控 + +- 电视日志快照:`/private/tmp/c2-tv-live-full.txt`。TCL MT9655、MPV 自动模式、硬解、默认升级 P8.1 播放同一 P7 FEL 文件时,`FILE_LOADED` 后主线程 watchdog 从 `00:04:09.725` 开始报告 `native=get-string:chapter-list`,随后持续到 `00:04:35.333`,最长 `27113ms`。 +- 调用栈固定为 `MpvPlayer.refreshChapters -> stringProperty("chapter-list") -> MPVLib.getPropertyString`;这证明上一轮只延后 `track-list/*` 仍不足,`FILE_LOADED` 的同步章节读取才是当前卡死触发点。`chapter`/`chapter-list` 属性事件和手动刷新入口也可能在同一启动窗口触发同步读取。 +- 窄修复:P8.1 启动窗口内统一跳过 `refreshChapters()`、`handleChapterListProperty()` 及对应属性事件;首次 `PLAYBACK_RESTART` 后由既有延迟轨道刷新任务补做一次章节刷新。普通 MPV 会话、原生 DV7、直接 HDR10 和字幕/章节在首帧后的路径不变。 +- 未修改 FFmpeg/MPV native、`dovi_rpu`、Vulkan、解码器、Surface 或默认策略;无新增依赖和包体积变化。 +- 验证:`bash ./gradlew :app:testMobileArm64_v8aDebugUnitTest --tests androidx.media3.mpvplayer.MpvTrackRefreshPolicyTest --tests com.fongmi.android.tv.player.engine.MpvDolbyVisionFallbackPolicyTest :app:compileMobileArm64_v8aDebugJavaWithJavac --no-daemon` 通过(57 秒);`git diff --check` 通过。 +- 设备限制:本次读取时 `http://192.168.1.5:9978/debug/logs.txt` 暂不可连接,电视 ADB 仍离线;因此只记录日志根因和静态/编译验证,不宣称电视实机回归已通过。 +- 当前状态:代码提交 `a83fe86baa245f58c1f5143584c1a5ceaa348530`,恢复 tag `recovery/C2-DV7-P81-BSF/20260830003041-a83fe86baa24`;设备重新上线仅需复测同一 DV7 自动模式,确认不再出现 `chapter-list` 长时间 JNI 阻塞。 + +### 2026-08-30 00:31 CST:提交收尾 + +- 原子代码提交:`a83fe86baa245f58c1f5143584c1a5ceaa348530`(`fix(mpv): defer startup chapter metadata for DV7 P8.1`)。 +- 恢复 tag:`recovery/C2-DV7-P81-BSF/20260830003041-a83fe86baa24`。 +- 验证记录:C2 定向单测、Mobile arm64 Java 编译和 `git diff --check` 已在提交前通过;未重复执行构建。电视端仍无 ADB/live 日志连接,实机回归保留为唯一剩余风险。 + +### 2026-08-30 06:36 CST:native 失败链、离线码流对照与上游复核 + +- 复现 `p-de6eo9-1` 的顺序已收敛:`dovi_rpu` 转换包持续送入 MediaCodec,但没有视频输出;FFmpeg 的 packet-property 队列达到 256 条后丢弃,随后出现 `Pending dequeue input buffer request cancelled`、`Invalid to call at Released state` 和 `hevc_mediacodec: Failed to dequeue output buffer`。主线程之后才阻塞于 `demuxer-cache-state/reader-pts`,最长超过 145 秒,因此同步属性查询不是码流失败根因,但会阻止 15 秒 HDR10 回退任务执行。 +- 离线样片 `/private/tmp/c2-p7-full.mkv` 的 27--30 秒区间与转换结果 `/private/tmp/c2-p81-27s.mkv` 已逐 packet 解析:原始 72 个 packet 和转换后 62 个 packet 都恰好包含一个 type-62 RPU;转换后 type-63 EL NAL 为 0。重复 RPU 假设被否定。 +- 电视上已验证正常的原生 P8.1 样片 `P81_GlassBlowing2_3840x2160@59_94fps_15200kbps.mkv` 前 57 个 packet 与转换结果都把 RPU 放在 VCL 之后,因此 RPU NAL 顺序假设也被否定。 +- 转换结果的 codec side data 仍含 `AV_PKT_DATA_HEVC_CONF`,而其 DOVI config 已是 `profile=8, el_present=0`;FFmpeg 自带 `dovi_split` 在删除 EL 后会明确移除该 side data。该输出元数据不一致需要后续修正评估,但当前 MediaCodec 初始化代码只直接读取 `AV_PKT_DATA_DOVI_CONF`,所以尚不能把残留 `HEVC_CONF` 宣称为零输出根因。 +- `FongMi/FFmpeg` 当前 `release-9.0-fongmi` 头为 `5e6ba5e987284d8ecb6dc25d2d3fd45d309f3fdd`。其 P7->P8.1 提交 `86b827daa9401f781f8660ea511a2cae0baa2833` 与锁定 `177f090e0503b7e013922ca903bde14b1c375f18` 的 stable patch-id 均为 `c3e9cba49f8bbe3c1d0ea7ab15868198b75d18bd`,`dovi_rpu.c/.h` 最终行为无差异;新头只以 `5e6ba5e987284d8ecb6dc25d2d3fd45d309f3fdd` 公开 RPU parser API,没有修复 BSF 输出或 Android MediaCodec 零输出。 +- `FongMi/mpv` 当前 `fongmi` 头为 `f70b385f57ad930a298f8b54e0199ce17c4f4ad3`,分支已强制重落基。近期相关提交 `c318236b8882af860f16f936225430ad053a2179` 只在独立 enhancement-layer stream 被标记 absent 时解除 BL/EL pairing;`e8673660ab7ee5d4ea8f93e4bf3a6e170ab2a19a` 只保留 GPU peak-detection HDR metadata,均不触及当前 `dovi_rpu` 到 Dolby MediaCodec 的初始化和零输出链。 +- `FongMi/mpv-android` 当前 `fongmi` 头为 `e1a1f75106afefa6fb3ec9aa6c9ca081155486dd`;该唯一新提交只导出 libplacebo/shaderc renderer SDK 与来源清单,没有 JNI、MediaCodec、Surface 或播放行为变更。 +- 最小下一步不是修改 native,而是只在 C2 P8.1 会话把 mpv 的 `ffmpeg` 与 `ffmpeg/video` 日志提升到 info。锁定 FFmpeg 已存在 `Dolby Vision profile %u detected` 与 `MediaCodec started successfully: codec = %s` 两条初始化日志;一次复现即可区分“错误 MIME/profile/codec 选择”和“正确 Dolby codec 收到转换流后拒绝输出”。普通 MPV 会话继续使用 `all=warn`,无播放路径、性能或包体积变化。 +- 诊断包已通过 `:app:assembleLeanbackArm64_v8aDebug`,构建耗时 2 分 16 秒;APK 为 `app/build/outputs/apk/leanbackArm64_v8a/debug/app-leanback-arm64_v8a-debug.apk`,大小 156646041 bytes,SHA-256 `e7bf658078a0ad059373d84c1b20ea274737b16539259908b117838df7436235`。06:44 之后观测到的新播放走的是 Exo 而非 MPV,尚未产生本诊断包的 codec 初始化证据;下一动作保持为安装该包并用 MPV 复现同一 P7 FEL 一次。 + +### 2026-08-30 07:01 CST:最新 MPV 复现与日志接收门槛 + +- 完整快照为 `/private/tmp/c2-tv-latest-repro.txt`,最新有效 MPV trace 为 `p-dg4unu-1`。日志记录 `requested=opengl`,但自动模式最终为 `direct=true`、`actual=surface/mediacodec_embed`;因此本次不是 OpenGL GPU renderer 卡死,界面中的请求模式不能代替实际输出路径。 +- `06:49:04` 已收到 `FILE_LOADED`;`06:49:05.106` 起连续出现 `Dropping unmatched MediaCodec packet properties`,`06:49:05.482` 首次出现 `Invalid to call at Uninitialized state`,随后 `hevc_mediacodec: Failed to dequeue output buffer`。全程没有首帧。`reader-pts` 同步读取约 3 秒后才开始阻塞,并从约 46 ms 增长到 40 秒以上,继续证明解码器失败在先、Java 属性阻塞在后。 +- P8.1 会话的 `msg-level=all=warn,ffmpeg=info,ffmpeg/video=info` 已生效到 mpv client 请求链;未看到 `Dolby Vision profile %u detected` 的直接原因是 `MpvPlayer.shouldDebugLogMpvLine()` 没有放行该文本。`MediaCodec started successfully: codec = %s` 本应因包含 `codec` 被现有筛选放行,但本次没有出现,说明 MediaCodec 尚未成功启动,不能再按“已启动后零输出”描述本次状态。 +- 四个遗留轮询曾同时每 1--2 秒下载约 5 MB 完整日志,已停止并改为单个 8 秒轮询,避免调试服务负载干扰复现。该清理不改变 App 或电视播放配置。 +- 已把 `androidx/media3/mpvplayer/MpvPlayer.java` 纳入本诊断单元,只放行 `Dolby Vision profile` 初始化行;`bash ./gradlew :app:assembleLeanbackArm64_v8aDebug --no-daemon` 通过,用时 1 分 54 秒。APK 为 `app/build/outputs/apk/leanbackArm64_v8a/debug/app-leanback-arm64_v8a-debug.apk`,大小 156646041 bytes,SHA-256 `08a48bf18b7a27f284897952191f1a806970a568463a927dbe3f1cd0ae1d78e0`。 +- 唯一下一动作:在电视安装该诊断包并用 MPV 自动模式复现同一 P7 FEL 一次,从单个后台轮询采集最终 profile/codec 证据;在该证据前,仍不修改 BSF、CSD、硬解、Surface、OpenGL/Vulkan、默认策略或上游 lock。 + +### 2026-08-30 07:32 CST:厂商 Dolby decoder 释放顺序确认 + +- 本次完整日志已冻结为 `/private/tmp/c2-tv-user-repro-20260830.txt`,有效 MPV trace 为 `p-dhezv2-1`,播放文件为 `/storage/emulated/0/Download/P7_FEL_GIJoe_The_Rise_of_Cobra.mkv`。 +- 自动模式实际为 `direct=true`、`surface/mediacodec_embed`。`07:24:56.408` FFmpeg 识别转换结果为 Dolby Vision profile 8;`07:24:56.421` 厂商 decoder `c2.mtk.dvhe.st.decoder` 启动成功,排除错误 MIME、错误 profile、错误 decoder 和 OpenGL/Vulkan 选择。 +- 全程没有首帧。`07:24:57.716` 起连续出现 `Dropping unmatched MediaCodec packet properties`;`07:24:58.027` 出现 `Pending dequeue input buffer request cancelled`,随后 codec 已处于 `Released`,再出现 `hevc_mediacodec: Failed to dequeue output buffer`。主线程之后才阻塞于 `demuxer-cache-state/reader-pts`,最长超过 130 秒,因此 JNI 查询是卡死放大点,不是 decoder 释放的起因。 +- 诊断日志已完成使命,临时 P8.1 FFmpeg verbose 配置与 Java 文本放行不进入生产修复。当前单变量假设是:`dovi_rpu convert=p81` 删除 EL 并改写 DOVI config 后仍保留表示增强层配置的 `AV_PKT_DATA_HEVC_CONF`;FFmpeg 自带 `dovi_split` 对同类输出明确删除该 side data,并注明输出端已失效。 +- 下一动作:只在 P8.1 转换的 `par_out` 删除 `AV_PKT_DATA_HEVC_CONF`;不改变 RPU 内容、extradata、packet、codec/MIME、Surface、GPU、Java 回退和其他播放模式。验收是同一文件产生首帧且不再进入厂商 decoder `Released`;失败则立即撤销该假设。 + +### 2026-08-30 07:38 CST:失效增强层配置单变量候选 + +- 在 `third_party/patches/mpv-dovi-profile7-p81.patch` 中,`dovi_rpu` 初始化完成后、`par_out` 复制给 MPV decoder 参数前,仅对 `convert_p81` 删除 `AV_PKT_DATA_HEVC_CONF`。该 side data 的公开语义是 Dolby Vision 增强层 HEVC decoder configuration,而当前转换已删除全部 type-63 EL NAL。 +- 没有修改 `AV_PKT_DATA_DOVI_CONF`、主 HEVC extradata、RPU 重写、packet 数据、MIME/profile/codec 选择、Surface/GPU、Java 回退或其他 DV/HDR 模式。新增 verbose marker 仅用于证明构建资产包含该候选,默认 `all=warn` 不输出。 +- 静态验证通过:新 C2 patch 在锁定 MPV `cca559b41ceb0bb7731cf6ef2e1f33276cd30c42` 及既有 HDR10 patch 后通过 `git apply --check --recount`;`bash -n` 两个 native 脚本和 `git diff --check` 通过。 +- 回滚锚点:`e343efd2e544c9957a0fe5d825e2cb81b5972d5d`,恢复 tag `recovery/C2-DV7-P81-BSF/20260830073401-e343efd2e544`。未验证候选不得提交或标记为修复。 +- 下一动作:只重建并安装 Leanback arm64 候选,用同一 P7 FEL 文件验证首帧与 decoder 生命周期;通过后再补 armeabi-v7a 资产。 + +### 2026-08-30 08:03 CST:arm64 单变量候选完成,等待安装 + +- `scripts/build_mpv_native.sh --abi arm64-v8a --install --incremental --jobs 8` 已完成;新 arm64 `libmpv.so` 已确认包含 `DV7 P8.1 conversion: removed stale enhancement-layer configuration.`。包装构建同时改写的七个无关 FFmpeg 资产均已恢复到 `e343efd2e544c9957a0fe5d825e2cb81b5972d5d`,候选包只保留 C2 `libmpv.so` 单变量。 +- 全资产 `--require-elf` 校验对 arm64 已通过,随后按阶段设计在尚未重建的 armeabi-v7a marker 处停止;这不是 arm64 候选失败。task guard 在恢复无关资产后通过。 +- `bash ./gradlew :app:assembleLeanbackArm64_v8aDebug --no-daemon` 一次通过,耗时 1 分 17 秒。APK 为 `app/build/outputs/apk/leanbackArm64_v8a/debug/app-leanback-arm64_v8a-debug.apk`,SHA-256 `acc1cc698a556654e969de75b2530bad115ee21179bc522acf10d74554758870`。 +- 用户在候选构建完成前进行的播放仍使用电视旧包;最新日志中的持续播放 trace `p-did5nt-3` 是网络 H.264,最近一次 DV7 trace `p-di77tq-1` 又在启动后约一秒主动销毁,均不能验证本候选。 +- 安装阻塞:`adb connect 192.168.1.5:5555` 返回 `Connection refused`;电视 `9978` 调试服务没有 APK 安装入口,因此候选尚未安装,禁止继续用旧包重复复现并据此判断修复结果。 +- 用户新增后续要求:优化 native 构建脚本,避免 `--incremental` 仍逐个重跑 nghttp2、curl、libarchive 等未变化依赖。该优化应在 C2 播放修复收尾后使用新的稳定任务 ID、独立 guard/提交/恢复 tag 实施;设计采用输入指纹和已验证产物共同决定跳过,lock、patch、override、NDK、ABI 或构建参数变化必须使缓存失效,不能仅按文件存在跳过。 +- 唯一下一动作:电视开启无线 ADB、使 `192.168.1.5:5555` 可连接后,安装上述候选 APK,清空日志并只用 MPV 自动模式播放 `/storage/emulated/0/Download/P7_FEL_GIJoe_The_Rise_of_Cobra.mkv` 一次;验收首帧和厂商 decoder 是否保持运行。 + +### 2026-08-30 08:08 CST:电视 arm64 实机通过 + +- 用户手动安装 SHA-256 `acc1cc698a556654e969de75b2530bad115ee21179bc522acf10d74554758870` 的 Leanback arm64 候选,并使用 MPV 自动模式播放 `/storage/emulated/0/Download/P7_FEL_GIJoe_The_Rise_of_Cobra.mkv`;用户确认画面正常且显示为转换后的 DV8。 +- 冻结日志为 `/private/tmp/c2-tv-hevc-conf-candidate-20260830.txt`,有效 trace `p-diwh05-1`。`08:06:37.112` 收到首帧,首帧耗时 7604 ms;随后播放位置推进到 17081 ms,`dropped=0`、`rebufferCount=0`,最终由用户正常停止,`end-file reason=stop error=success`。 +- 本次没有 `Dropping unmatched MediaCodec packet properties`、pending dequeue 取消、decoder `Released`、output dequeue 失败、`reader-pts` JNI 阻塞或 P8.1->HDR10 自动回退。与旧包同一样片的失败链形成直接对照,支持“删除失效 `AV_PKT_DATA_HEVC_CONF` 修复 MT9655 厂商 Dolby decoder 接受度”的结论。 +- 当前恢复点只声明 Leanback arm64 实机通过;armeabi-v7a 资产尚未补入该 marker,双 ABI 完整校验和 C2 最终收尾仍待后续独立阶段完成。 +- 用户要求先固化当前已验证状态,再单独优化播放参数面板文案为 `DV7(升级P8.1)`,与 `DV7(降级HDR10)` 的显示风格一致。 + +### 2026-08-30 08:34 CST:起播音画间隔与参数面板修复决策 + +- 用户确认输入是电视本地文件;网络读取、代理和带宽不足不适用。三次转换 P8.1 复现中,`PLAYBACK_RESTART` 后约 4--6 秒才出现 App 的 `first-frame`,但该事件实际由延迟轨道刷新后的 `onTracksChanged` 推断,不是真实 Surface 帧回调,不能据此修改解码或音频时序。 +- 锁定 FFmpeg 的 `dovi_rpu` 保留首视频包的 key flag;样片首包为 `pts=0`、`K__`,转换 10 秒仅耗时 0.83 秒(host 对照),首帧仍为独立 RPU。历史 `Unknown previous RPU ID` 只出现在停止/重配后的晚期日志,因此“首 RPU 错误引用前态”被否定,不实施强制 key 或禁用全部 RPU 压缩。 +- 参数面板的目标以用户提供的 Exo 实机图为准:`格式 Dolby Vision DV.07`,`codec dvhe.07.06(升级P8.1)`。当前 Java formatter 已符合该文本,但 MPV C2 在 native 中把 `dv_profile` 改为 8 后,`track-list` 只暴露转换后的身份;必须同时保留源 profile/level,不能根据设置项猜测,否则原生 P8.1 文件会被误标为 DV7 转换。 +- 方案比较:不改会保留音画体验问题和错误面板;直接使用上游转换结果无法提供源身份,也没有真实首 Surface 输出证据;WebHTV 窄适配是在 C2 splitter 中保存源 DV profile/level、通过现有 `track-list` 增加只读属性,并在 direct MediaCodec VO 每会话只记录一次首输出提交时间。它不改变 packet、RPU、CSD、解码器、Surface 调度或音频时序,诊断开销为一次日志。 +- 推荐:先实施上述源身份和一次性首输出证据;同一 arm64 包即可同时验证面板和定位起播延迟。若首输出本身晚,修复 decoder/VO 前的已证实阻塞;若首输出及时而屏幕仍黑,只在 P8.1 转换会话设计首画同步门,禁止用固定全程 audio-delay。任何最终时序修复仍不得影响原生 DV7、原生 P8.1、HDR10、GPU 输出或 seek/flush。 +- 验收:MPV 面板与 Exo 图一致;同一本地样片记录 `PLAYBACK_RESTART`、首 direct MediaCodec output 和用户可见首画;无 decoder `Released`、packet-property 丢弃、JNI 长阻塞、HDR10 意外回退或新增掉帧。回滚到 `b1f07cea3d36b8207ac0d518b837e295cb212323` 及 `recovery/C2-DV7-P81-BSF-CSD/20260830081107-b1f07cea3d36`。 + +### 2026-08-30 09:58 CST:参数面板候选引入 GPU 软解回归及修正 + +- 用户实测首个面板候选播放严重卡顿。冻结证据 `/private/tmp/c2-tv-stutter-20260830.txt` 显示会话最初保持 `surface/mediacodec_embed` 和 MediaCodec 硬解,但源身份接线错误地把运行时 Profile 8 覆盖为 Profile 7;自动输出策略随后记录 `dvProfile=7`、`dvSupport=UNSUPPORTED`、`transition=LEAVE_SURFACE_DIRECT`,并以 `auto-dolby-vision-hw-unsupported` 重建为 `vo=gpu / hwdec=no`,掉帧增长到 89。该回归不是电视性能波动,而是本候选的数据边界错误。 +- 修正后 `VideoTrackDiagnostics` 同时保留运行时 Profile 8 和源 Profile 7/Level 6;`MpvPlayerEngine` 仅用源 Profile 判断面板的 `(升级P8.1)` 标记,所有播放能力、自动输出和硬解策略继续读取运行时 Profile 8。`DolbyVisionFormatLabel` 从源 codec 生成 `Dolby Vision DV.07`,因此面板显示不再改变渲染决策。 +- 本次修正没有修改 `PlayerManager`、自动输出策略实现、解码器选择、Surface/VO、BSF packet/CSD/RPU、音频或起播时序。现有 native 候选仅增加源 profile/level 的只读轨道属性和一次性首 MediaCodec output 诊断,用于面板与黑屏根因取证。 +- 定向验证通过:`bash ./gradlew :app:testMobileArm64_v8aDebugUnitTest --tests com.fongmi.android.tv.player.DolbyVisionFormatLabelTest :app:assembleLeanbackArm64_v8aDebug --no-daemon`,耗时 1 分 33 秒。Leanback arm64 Debug APK 为 `app/build/outputs/apk/leanbackArm64_v8a/debug/app-leanback-arm64_v8a-debug.apk`,大小 174363865 bytes,SHA-256 `4f98512b119f1da83ef64c462bea0ce652023a42e82104d4b6abdc4b3db041cb`。 +- 当前状态:尚未提交或创建恢复 tag;等待用户手动安装该包复测同一 DV7 自动/P8.1 场景。验收必须保持 `vo=mediacodec_embed`、`hwdec=mediacodec`,不得再次出现 `LEAVE_SURFACE_DIRECT` 或 `auto-dolby-vision-hw-unsupported`,且面板显示源 DV7 与 `(升级P8.1)`。 +- 唯一下一动作:用户安装上述 APK 并播放同一样片后,读取一次电视日志确认硬解直通与掉帧计数,再决定是否进入提交/tag 收尾。 + +### 2026-08-30 10:08 CST:面板修正版电视实机验收 + +- 用户手动安装 SHA-256 `4f98512b119f1da83ef64c462bea0ce652023a42e82104d4b6abdc4b3db041cb` 的 Leanback arm64 Debug APK,并以 MPV 自动/P8.1 模式播放同类本地 DV7 样片;冻结日志为 `/private/tmp/c2-tv-live-panel-fixed.txt`,有效 trace 为 `p-dn3rgx-4`。 +- 播放从始至终保持 `vo=mediacodec_embed`、`hwdec=mediacodec` 和 `mpv-surface-direct`;自动策略结论为 `dolby-vision-hw-supported`。统计 `LEAVE_SURFACE_DIRECT=0`、`auto-dolby-vision-hw-unsupported=0`、`vo=gpu=0`、`hwdec=no=0`,确认此前 GPU 软解回归已修复。 +- direct MediaCodec 首个输出在加载后约 `759283 us` 提交,启动缓冲约 `988 ms` 后进入 READY;播放期间掉帧从 0 增至 1 后保持不变,`rebufferCount=0`。位置停在 `33033 ms` 是用户手动暂停,已排除为播放停滞。 +- 当前原子单元可以提交并创建恢复 tag。后续“先有声音、后出画面”仍作为 C2 的下一个独立修正单元处理:现有证据已经证明 decoder/VO 在约 0.76 秒提交首输出,而 App 的 `first-frame=7165 ms` 来自延迟轨道刷新后的 `PLAYBACK_RESTART` 推断,不能把两者的差值直接解释为真实黑屏时长,也不能据此增加固定音频延迟。 +- 唯一下一动作:提交并标记当前面板/源身份/诊断单元;随后从本次真实 MediaCodec 输出证据与用户可见首画观察之间建立可证伪的时序,再决定最小代码修复。 + +### 2026-08-30 10:15 CST:先有声音后出画面的根因与修复设计 + +- 根因已由同一 trace `p-dn3rgx-4` 的完整时序证实:direct MediaCodec 在 `10:04:09.349` 提交首个视频输出,MPV 于 `10:04:09.370` 发出 `PLAYBACK_RESTART` 并在 `10:04:09.378` 进入 READY;但 App 的自动输出 shutter 仍因 `mpvAutoOutputEvaluated=false` 保持 Surface alpha=0/黑色遮罩,直到延迟轨道刷新完成并于 `10:04:15.607` 得出 `KEEP_SURFACE_DIRECT` 后才调用 output-ready。可见画面被 App 额外遮住约 6.26 秒,期间音频正常播放,因此形成“先有声音、后出画面”。 +- 这不是 decoder、BSF、CSD、RPU、Surface 提交或音频同步变慢。`firstFrameMs=7165` 是 `markStartupCompletion()` 等待非空 tracks 后的延迟推断;它不代表真实视频首输出。此前 P8.1 失败 trace `p-de6eo9-1` 没有 `PLAYBACK_RESTART`,随后直接进入 packet-property 丢弃和 MediaCodec dequeue 失败,因此 READY/restart 可区分本次成功输出与既有失败回退路径。 +- 方案比较:不改会固定保留约 6 秒黑遮罩;增加 `audio-delay` 会破坏全程 A/V sync、seek 和暂停恢复;恢复启动期同步轨道查询会重新引入电视主线程 JNI 卡死;等待完整自动评估仍是当前缺陷。采用窄适配:自动 MPV Surface Direct 在 `PLAYBACK_RESTART/READY`、视频尺寸有效且输出尚未评估时,把该帧作为运行时成功证据,立即打开 shutter并记录真实首帧;完整自动输出评估继续后台运行,若后续确需重建仍走现有 reset/pending 流程。 +- 保留合同:不修改解码器、`vo`/`hwdec`、native binary、BSF/CSD/RPU、音频时序、轨道刷新门控或失败回退。音频-only、GPU 输出、未 READY、无有效视频尺寸和已经评估的会话不得提前打开;失败的 P8.1 因没有 `PLAYBACK_RESTART` 继续保持 shutter 并等待现有 HDR10 fallback。 +- 验收:定向策略单测覆盖允许/拒绝条件;Leanback arm64 构建通过;电视同一样片的 shutter/output-ready 应从约 7 秒提前到 READY 约 1 秒附近,同时保持 `mediacodec_embed`/`mediacodec`、无 GPU transition、无 rebuffer,掉帧不高于当前候选的稳定水平。 +- 回滚:恢复 `3db8252c95ad23096db58d6adb75c094565a33bc` 或 `recovery/C2-DV7-P81-BSF-PANEL/20260830100826-3db8252c95ad`;本单元只修改 App Java、策略单测和本文件。 + +### 2026-08-30 10:22 CST:shutter 提前释放候选实现与构建 + +- `PlayerManager` 新增会话级 `mpvAutoOutputFrameReady`:自动 MPV Surface Direct 收到 READY(其来源为 `PLAYBACK_RESTART`)且已有有效视频尺寸时,立即调用 output-ready、打开 shutter,并将该时刻记录为 MPV 首帧。轨道列表稍后刷新时不会重复记录首帧。 +- `MpvAutoOutputPolicy.canRevealDirectFrame()` 集中约束允许条件;未 READY、GPU 输出、无视频尺寸、非自动模式或已经完成输出评估的会话均拒绝提前打开。完整 `evaluateMpvAutoOutput()` 仍继续运行,重建时既有 reset/pending 会重新关闭 shutter。 +- 定向验证通过:`bash ./gradlew :app:testMobileArm64_v8aDebugUnitTest --tests com.fongmi.android.tv.player.mpv.MpvAutoOutputPolicyTest :app:assembleLeanbackArm64_v8aDebug --no-daemon`,耗时 1 分 45 秒。没有修改或重建 native 资产。 +- Leanback arm64 Debug APK:`app/build/outputs/apk/leanbackArm64_v8a/debug/app-leanback-arm64_v8a-debug.apk`,大小 174363865 bytes,SHA-256 `8c2c6bf0394e60619d62df07a68d4be6ef3257680839292007b67e40b5da2c6f`。 +- 当前状态:候选尚未提交/tag。唯一下一动作是用户手动安装该 APK 并播放同一 DV7→P8.1 样片;日志必须先出现 `MediaCodec first output submitted`/READY,紧接 `auto shutter release reason=direct-playback-restart`,后续自动决策仍为 `KEEP_SURFACE_DIRECT`,且无 GPU transition、rebuffer 或异常掉帧。 + +### 2026-08-30 10:30 CST:电视实机验收与收尾 + +- DV7→P8.1 有效 trace 为 `p-dnwxvd-4`:direct MediaCodec 在 `10:26:50.953` 提交首个输出,App 在 `10:26:51.051` 记录首帧并于 `10:26:51.055` 打开 shutter,首帧总耗时 `1603 ms`。完整自动输出评估直到 `10:26:56.422` 才结束,但画面已提前约 5.37 秒显示;最终保持 `mpv-surface-direct`、`hwdec=mediacodec`、`vo=mediacodec_embed`,结论为 `dolby-vision-hw-supported`。 +- 该样片继续播放至 EOF,位置推进到 `57099/57140 ms`,`dropped=0`、`rebufferCount=0`、`rebufferTotalMs=0`,`end-file reason=eof error=success`。没有 GPU/软解切换、MediaCodec 释放失败、JNI 长阻塞、Java/native 崩溃或 HDR10 意外回退。 +- 随后一轮 trace `p-dnyatr-6` 同样保持硬解直出:MediaCodec 首输出后约 `56 ms` 打开 shutter,首帧总耗时 `1021 ms`;完整策略评估稍后保持 Surface Direct,播放期间 `dropped=0`、`rebufferCount=0`。这同时覆盖了非首次会话的状态重置与普通自动输出路径。 +- 验收结论:修复已消除 App 自身额外维持 5--6 秒黑遮罩的问题,不改变解码、渲染、音频同步、DV 转换或失败回退路径。回滚仍为 `3db8252c95ad23096db58d6adb75c094565a33bc` 或 `recovery/C2-DV7-P81-BSF-PANEL/20260830100826-3db8252c95ad`。 +- 收尾结果:实现、测试和实机证据已提交为 `fa6a9ab2df507f1e223225efbabd2b2978dfafcb`(`fix(mpv): reveal direct video at playback restart`),并在提交后立即创建 annotated recovery tag `recovery/C2-DV7-P81-BSF-FIRST-FRAME/20260830103126-fa6a9ab2df50`;tag 创建耗时 `0s`。 +- 下一动作:本原子单元已完成;不重复构建,不推送远端。后续 C2 工作必须另开独立 guard、提交和恢复 tag。 + +### 2026-08-31 22:26 CST:补齐 C2 P8.1 的 armeabi-v7a 已验证资产 + +- CI 运行 `Silent1566/webhtv` 的 `33392660102`(job `99489724919`,`beta@b35ff038d26b297e3a1b020c0117cd365b35425f`)在 `verify_mpv_native_assets.sh --require-elf` 的第二个 ABI 失败:`armeabi-v7a/libmpv.so` 缺少 `DV7 P8.1 conversion: removed stale enhancement-layer configuration.`。`b1f07cea3d36b8207ac0d518b837e295cb212323` 仅更新 arm64 产物却把该 marker 加入双 ABI 校验,导致旧 armv7 资产无法满足已提交的锁定 patch 合同。 +- 依用户要求优先采用上游精确产物:`fish2018/webhtv@23a3c74417fdcc107ad8efc43ca366482af89e58` 的 `app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libmpv.so`。该来源提交只改动该二进制和未采用的 `MpvPlayerEngine.java` 一行;本地与上游的 `third_party/mpv-native-lock.json`、`scripts/build_mpv_native.sh`、`scripts/verify_mpv_native_assets.sh`、`third_party/mpv-native-build.md`、`mpv-dovi-profile7-p81.patch` Git blob 完全一致,因此未引入任何新源码、锁、patch 或 Java 行为。 +- 安装产物:Git blob `64701f8a778bb3cfc2edecbcf8f2da204d4828d9`,大小 `14,522,228` bytes,SHA-256 `c2b952f9e6d3fb38399672d74bb9a3607668825c6eaacf40d02a1b8706407753`;ELF 为 `ELF32` / `ARM` / `DYN`,包含所需 P8.1 stale-enhancement-layer marker。仅替换 `armeabi-v7a/libmpv.so`;其余 armv7 资产、全部 arm64 资产及两 ABI 的 `libplayer.so` 均未改动。 +- 验证:使用 NDK `29.0.14206865` 的 `llvm-readelf` 和 `llvm-strings` 执行 `scripts/verify_mpv_native_assets.sh --require-elf`,稳定 Vulkan shader contract、P2 generic UV patch scope、`arm64-v8a`、`armeabi-v7a`、ELF `SONAME`/`DT_NEEDED`/命名空间与过期 marker 拒绝规则均通过。 +- 回滚:恢复本任务父提交 `119b3aec7345f578a93e1d59bf2a87d0dc61248a` 中的唯一 armv7 `libmpv.so`,或恢复本次 guard 收尾创建的 recovery tag;不需要回滚 C2 P8.1 patch、arm64 产物或任何 App Java 代码。 diff --git a/docs/C3-iso-multi-extent-resolver.md b/docs/C3-iso-multi-extent-resolver.md new file mode 100644 index 0000000000..3a61fca4d8 --- /dev/null +++ b/docs/C3-iso-multi-extent-resolver.md @@ -0,0 +1,7 @@ +# C3 ISO multi-extent App resolver + +C3 is implemented and rolled back together with E7-2 because the App resolver consumes Media3 `IsoFileEntry`. The authoritative joint decision, implementation history, verification, commit/tag, risks, and next action are maintained in [E7-2-exo-iso-multi-extent-api.md](E7-2-exo-iso-multi-extent-api.md). + +Scope specific to C3: update `IsoTrackMetadataResolver` to read MPLS/CLPI metadata across all logical extents while preserving the existing 8 MiB cap, short-read/EOF handling, cancellation behavior, and MPV metadata semantics. It does not modify MPV native code. + +Implementation status: complete in `5f7d834bfdd00f215609df7b41c2ea7cadc2cd4f`, anchored by `recovery/E7-2-C3/20260827193629-5f7d834bfdd0`, and App-compile verified on 2026-08-27. Recorded extents are read in logical order, unrecorded extents are zero-filled, and a short extent still raises `IOException`. Mobile and Leanback arm64 Debug Java compilation passed against the published E7-2 AARs. Tests and real split MPLS/CLPI playback were omitted by user direction and remain residual validation risk. diff --git a/docs/E-SP2-exo-remote-mkv-deferred-cues.md b/docs/E-SP2-exo-remote-mkv-deferred-cues.md index a8b97edb17..c3a0024bec 100644 --- a/docs/E-SP2-exo-remote-mkv-deferred-cues.md +++ b/docs/E-SP2-exo-remote-mkv-deferred-cues.md @@ -5,8 +5,8 @@ - 唯一文档:`docs/E-SP2-exo-remote-mkv-deferred-cues.md` - 评估日期:2026-08-22(Asia/Shanghai) - 范围:Exo 起播速度、远程百度网盘 MKV、Matroska Cues/索引,以及首次随机访问。 -- 状态:Media3 补丁、extractor AAR 和 HTTP/HTTPS App gate 已完成并提交;定向测试和双产品编译通过,真实设备起播/seek 性能验收待完成。 -- 下一动作:同一设备、资源和网络下完成基线/候选至少 3 次中位数及首次/连续 seek 回归;未取得该证据前不宣称性能验收完成。 +- 状态:链式 `SeekHead` 修正已完成;定向测试、extractor 发布、双产品 arm64 编译和 vivo 实机连续 seek 均通过。 +- 下一动作:无;本单元提交并创建 recovery tag 后关闭。 ## 结论先行 @@ -328,7 +328,7 @@ first seek/非零 prepare - 工作区:分支 `fongmi-sync`,HEAD `3aae091dbba7a2140f4c157f86aa42d901f01ff9`;活动 task id 为 `exo-sp2-defer-cues-implementation-20260822`。 - 已完成:新增显式 `FLAG_DEFER_SEEK_FOR_CUES`、64 MiB/已知长度门槛、临时可更新 SeekMap、首次非零 seek 时加载 Cues 的状态机,并等价纳入 Media3 `859f7b3b5388378698ff23a667d3e2db5ac41aed` 的 Tracks-after-Clusters 顺序修复;补丁顺序已固定。App 的 HTTP/HTTPS URI 收窄将在候选 AAR 接入单元中完成。 - 已有验证:完整补丁链上的 `git apply --check` 和仓库 `git diff --check` 已通过;尚不能据此声明运行时 seek 或性能正确。 -- 构建环境:机器原先只有 JDK 17,已于 2026-08-23 安装 Homebrew OpenJDK `21.0.12.1`;后续构建显式设置 `JAVA_HOME=/usr/local/opt/openjdk@21/libexec/openjdk.jdk/Contents/Home`。使用隔离临时 checkout,不清理或覆盖预存 `third_party/sources/media/`。 +- 构建环境:使用 JDK 21;后续构建显式设置 `JAVA_HOME=/usr/local/opt/openjdk@21/libexec/openjdk.jdk/Contents/Home`。使用隔离临时 checkout,不清理或覆盖预存 `third_party/sources/media/`。 - 保护路径:`.gitignore`、`third_party/fongmi-repositories-lock.json`、`.codex/`、`AGENTS.md`、`docs/agents-md-effective-constraints-review-2026-08-21.md`、`docs/upstream-player-dependency-merge-assessment-2026-08-20.md`、`third_party/sources/media/` 均保持在本提交之外。 - 回滚锚点:`3aae091dbba7a2140f4c157f86aa42d901f01ff9`;若 extractor、seek、DV 或产物验证失败,整体撤销 E-SP2 source/AAR/App 单元,不改变 E-SP1。 - 未决风险:首次/连续/反向 seek、Cues 缺失/损坏、未知长度、IO 重试、递归 SeekHead、Tracks-after-Clusters,以及 DV7→P8.1/HDR10、TrueHD/字幕邻接能力仍需由定向测试和代表性播放验证。 @@ -357,3 +357,73 @@ first seek/非零 prepare - 回滚:若只需关闭新行为,回滚最终 App URI gate 即可;若候选 artifact 有兼容问题,再一并回滚 `71514fdb101db56e836902405700f39c891428e5`;若要完全撤销 E-SP2,再回滚 `fb2a9ab839958a711a73ee34232d5baa082bddc7`,E-SP1 不受影响。 - 未决:当前无 ADB 设备;实机首帧、首次 seek、连续 seek、DV7→P8.1、DV7→HDR10、字幕/TrueHD 及网络失败率需在候选包阶段验收。该限制不影响源码、AAR 与 App 编译结论,但禁止宣称性能提升已在设备上验证。 - 下一步:用同一远程大 MKV 做基线/候选至少 3 次中位数及首次/连续 seek、DV fallback 回归;该实机证据完成前不宣称性能验收完成。 + +## Checkpoint 7:2026-08-28 链式 SeekHead 实机失败与修正设计 + +### 现场证据与根因 + +- 设备:vivo V2453A,Android 15;App `com.fongmi.android.tv`;Exo 播放约 4.20 GB 远程 MKV。 +- 用户连续三次拖动进度条,系统日志逐次输出 `Controller isn't allowed to call command= 5`;Media3 `COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM` 的值为 5,说明请求在 `MediaController` 层被当前不可 seek 时间线拒绝,未到达 Exo seek 状态机。 +- 通过播放链原有认证参数和用户指定代理执行最小 Range 检查,没有记录或输出 URL、Cookie、token:文件长度为 `4508956833` 字节,Segment content 起点为绝对偏移 `52`。 +- 文件头绝对偏移 `52` 的首个 `SeekHead` 不含直接 `Cues` 条目,只含 `SeekID=SeekHead`,其相对位置为 `4508956696`、绝对位置为 `4508956748`。 +- 文件尾绝对偏移 `4508956748` 的第二个 `SeekHead` 含 `SeekID=Cues`,其相对位置为 `4508747919`、绝对位置为 `4508747971`;直接读取该位置的前四字节为 `1c53bb6b`,确认目标确实是 `Cues`。 +- 当前 `media3-deferred-cues.patch` 只在 `SeekID` 为 `Cues` 或 `Tracks` 时保存位置,忽略 `SeekID=SeekHead`。因此到首个 Cluster 时 `cuesContentPosition == C.INDEX_UNSET`,`maybePrepareSeekMap()` 发布 `SeekMap.Unseekable`,MediaSession 随后移除当前媒体内 seek 命令。 +- 结论:这是 E-SP2 未覆盖链式/递归 `SeekHead` 的 correctness 缺口,不是 E-SP3 seek 恢复门槛或统计隔离引入的回归。 + +### 上游 PR #2268 完整提交处置 + +上游 PR 截至 2026-08-28 仍为 closed、未合并。维护者验证了三个 `SeekHead`、未知长度和每个读位置注入 IOException 的组合,指出早期实现会丢样本或在重试后得到不一致的 seekability。以下提交全部纳入本修正的来源账本: + +| Full commit | 内容 | E-SP2 处置 | +| --- | --- | --- | +| `ffca82f981e975d302c6480ba9cbce6e05260e74` | 初版递归 SeekHead + 样片/测试 | `partial`:采用识别 `ID_SEEK_HEAD` 和二阶段跳转思想,不采用起播阶段立即尾跳 | +| `3a79ac28707f138adb8a2f9c09c3b59125bdf261` | 初版在 PR 分支上的重落基 | `superseded`:由同 PR 后续实现覆盖 | +| `04c8b3da1b1538ab10caf926e75bae4beeeb9226` | 增加 extractor dump | `test-only`:测试意图保留,本地使用更小的定向构造输入 | +| `f5a6ed0f3f5e3ad827e886de088bd93ecbc2178e` | 三 SeekHead 实验样片 | `evidence-only`:证明单位置字段不足,需要 pending/visited 集合 | +| `a77bd285dcfe3ebd56eb5f487f55638625005e35` | 任意数量 SeekHead 的 pending/visited 状态 | `partial`:采用有界 pending/visited 设计,访问时机改为首次非零 seek | +| `73a79cb0c496b55d7a1eb14d30785cd537be7954` | PR 分支 merge | `maintenance-only`:无独立行为移植 | +| `3525b89ef2bdb549bb9744cc7c51af3a56a2cb58` | 补 HashSet import | `covered`:随本地状态集合实现自然覆盖 | +| `705b31db25dd08708cf578e39b60e3b9e14574e0` | 三 SeekHead dump 更新 | `test-only`:不复制 dump,覆盖相同行为断言 | +| `5ee7bd2fa4f2416d3cb75c437444c20585d1a468` | 补漏 dump 更新 | `test-only`:不影响生产逻辑 | +| `46f72f3e8ead70c3b6b375d1b7f41e5b15d82329` | IO 重试状态清理及向前位置限制 | `partial`:采用 `seek(0,0)` 重置和位置/边界检查,不在 Segment 回调无条件清空 | +| `6d8ce0f41e8c688ef4fff1b1ae7403e6deb0871d` | 最终 dump 同步 | `test-only`:不影响生产逻辑 | + +### 方案比较与批准设计 + +| 方案 | correctness | 起播性能 | 风险 | 决定 | +| --- | --- | --- | --- | --- | +| 不变更 | 链式 SeekHead 永久不可 seek | 保持当前首帧 | 用户核心功能失败 | 拒绝 | +| 强制 MediaSession 暴露 seek 命令 | UI 请求可下发,但底层没有有效 SeekMap | 无直接影响 | 可能回到 0、错误定位或循环读取 | 拒绝 | +| 原样采用 PR #2268 | 能查找多个 SeekHead | 首个 Cluster 前访问尾部 SeekHead/Cues,重新把尾部 RTT 放回起播路径 | PR 未合并,且重试/未知长度测试曾失败 | 拒绝原样移植 | +| WebHTV 惰性链式 SeekHead | 起播先发布临时可 seek map,首次非零 seek 才解析 SeekHead 链和 Cues | 保留 E-SP2 起播收益 | 需要有界状态、重试清理和定向测试 | 批准实施 | + +最终设计: + +1. 解析 `SeekID=SeekHead` 时记录绝对位置;只接受位于当前 Segment 内、严格向前、尚未访问的条目,并限制最多 10 个待访问 SeekHead,避免循环或恶意唯一链造成无界 I/O。 +2. deferred 模式下,只要已知直接 Cues 或至少一个待访问 SeekHead,就发布 `isSeekable=true` 的临时 SeekMap。非零 seek 的临时 byte position 优先指向 Cues,否则指向待访问 SeekHead;起播阶段不主动执行尾部跳转。 +3. 首次非零 seek 到达 SeekHead 后,若解析出 Cues 则继续跳到 Cues;否则访问下一个未访问 SeekHead。完整 Cues map 发布后,用原目标时间计算最终 Cluster 位置并继续正常 seek。 +4. `seek(0, 0)` 和新的 Segment 重启清理 pending/visited/中间跳转状态;相同位置的 unchanged-position IOException 重试保留状态。链耗尽、越界或超过上限时回退 `SeekMap.Unseekable`,不得死循环、无限分配或强制暴露错误命令。 +5. 保留直接 Cues、Tracks-after-Clusters、Format 去重、DV BlockAdditional、字幕、TrueHD/DTS 分析和其他 extractor 语义;不修改 App 工厂、LoadControl、PreCache、E-SP3、MPV/native 或网络超时。 + +### 验收、可观测性与回滚 + +- 定向测试:直接 Cues 保持原行为;单层链式 SeekHead 在 prepare 阶段不读取尾部、临时 map 可 seek;首次非零 seek 按 `SeekHead -> Cues -> Cluster` 顺序完成;循环/重复/超过上限不死循环;`seek(0,0)` 后可重新解析;IO 短读/重试不丢状态。 +- 构建:锁定 Media3 `e3e922d5c01bc0b564849940fe589daf37360d15` 应用完整补丁链,运行 Matroska 定向测试并发布 extractor AAR/sources;更新补丁、artifact 和 lock SHA-256;Mobile/Leanback arm64 Java 编译通过。 +- 实机:同一 vivo、同一 MKV 连续 seek 至少三次;不得再出现 `command=5` 拒绝;第一次 seek 必须出现尾部 SeekHead/Cues Range,播放位置到达目标且后续连续播放;起播阶段不得提前读取尾部 SeekHead。 +- 日志:不另做大范围诊断 APK;修复中只增加一条 debug 级分支日志(disabled/direct-cues/nested-seekhead/unseekable)或等价测试可观测点,不记录 URL、Cookie、token。 +- 回滚:作为独立 extractor source/artifact/lock 单元回滚到当前 HEAD `9fcab83f9084446566240a8e8f5233d87d0274cc`;App gate 和 E-SP3 不需回滚。 +- 用户批准:2026-08-28 用户明确要求忽略 C2、集中解决该 bug;C2 文档保持受保护且不进入本单元。 +- 下一动作:修改 `media3-deferred-cues.patch` 和定向测试,重建 extractor 产物后执行实机验收。 + +## Checkpoint 8:2026-08-29 链式 SeekHead 修正完成 + +- 完成:`MatroskaExtractor` 在 deferred 模式记录有界 pending/visited `SeekHead`,起播只发布临时可 seek map,首次非零 seek 才按 `SeekHead -> Cues -> Cluster` 解析;循环、重复、越界或链耗尽安全回退,`seek(0,0)` 可重置重试状态。 +- 补丁链:扩展后的 deferred patch 会改变后续零上下文补丁的行号,因此 `scripts/build_media_deps.sh` 固定为 `media3-upstream-playback-fixes-2026-08.patch -> media3-exo-hdr-parser-safety.patch -> media3-deferred-cues.patch`。从锁定源码重新应用全部 Media3 补丁后,最终 Java 源码与已测试源码 SHA-256 逐字节一致。 +- 定向测试:锁定 Media3 `e3e922d5c01bc0b564849940fe589daf37360d15` 上运行 `:lib-extractor:testDebugUnitTest --tests androidx.media3.extractor.mkv.MatroskaExtractorNonParameterizedTest`,`BUILD SUCCESSFUL`;覆盖直接 Cues、Tracks-after-Clusters、首次非零 seek、链式 SeekHead 成功和自循环回退。 +- Artifact:deferred patch SHA-256 `ebbfbe0bcd1f002780b2db300bdcf42d9c3309c0738b43212ffa224eedcba8dd`;extractor AAR SHA-256 `59a090bad8efc32552cf5a7ec1d2fb66444168bfbc97bd45e50764527f80c768`;sources JAR SHA-256 `9314a303f402e903dd075db5e9babf9be6474da539a4b76bb1ed765b95b6ef4e`。AAR、sources、module 及各自 MD5/SHA-1/SHA-256/SHA-512 sidecar 一致,module 内嵌摘要一致,POM 未变化。 +- 发布与编译:`:lib-extractor:publishReleasePublicationToMavenRepository`、`:app:compileMobileArm64_v8aDebugJavaWithJavac` 和 `:app:compileLeanbackArm64_v8aDebugJavaWithJavac` 均 `BUILD SUCCESSFUL`;Gradle transform 中实际消费的 `MatroskaExtractor` 已包含 `pendingSeekHeadPositions`。 +- APK:Mobile arm64 debug APK SHA-256 `1563a1208b4721140fd88abf9548732e752ae700c00ad3a6711f010385b2e4b1`;vivo 流式安装被 OEM 拒绝,改用 `adb install --no-streaming -r -d -g` 后成功,不属于 APK 或代码失败。 +- 实机验收:vivo V2453A、Android 15、EXO、同一 4.20 GB 远程 MKV;用户完成连续拖动后明确确认“可以了”。本次日志未出现 `Controller isn't allowed to call command=5` 或 App fatal exception。 +- 可观测性决定:不增加额外运行时调试日志。定向测试已覆盖分支状态,现有 MediaSession 拒绝日志、播放器位置和网络 Range 行为足以判定本缺陷;避免在 extractor 热路径增加长期噪声或泄露请求信息的风险。 +- 回滚:整体回滚本单元即可恢复至 `9fcab83f9084446566240a8e8f5233d87d0274cc` 的 extractor patch/artifact/lock/build-order 状态;App URI gate 和 E-SP3 无需回滚。 +- 下一动作:运行最终一致性校验,使用 task guard 原子提交并立即创建 recovery tag。 diff --git a/docs/E-SP3-exo-seek-preload-isolation.md b/docs/E-SP3-exo-seek-preload-isolation.md new file mode 100644 index 0000000000..0fd57442d5 --- /dev/null +++ b/docs/E-SP3-exo-seek-preload-isolation.md @@ -0,0 +1,356 @@ +# E-SP3:Exo seek 预载隔离与 HLS 预缓存崩溃防护 + +- 任务 ID:`E-SP3` +- 类别:Exo 性能/生命周期 +- 唯一文档:`docs/E-SP3-exo-seek-preload-isolation.md` +- 评估日期:2026-08-27(Asia/Shanghai) +- 当前状态:`E-SP3-A + E-SP3-B` 已实施并形成独立 recovery tag;Media3 产物、App 构建和 vivo 安装已完成,HLS 预缓存崩溃暂未复现,但用户确认普通 seek 后仍有约 1 秒可感知停顿,因此设备验收未通过,任务继续定位。 +- 实施边界:只修改 Exo App 预载策略、Media3 `PreCacheHelper` 补丁、锁文件和 `media3-exoplayer` 产物;未修改前台 HLS、解码器、MIME、MPV、FFmpeg、nextlib native 或共享 `.so`。 +- 现场设备:vivo V2453A,Android 15 / SDK 35,`com.fongmi.android.tv`,序列号 `10CF6H1D2L0009S`。 +- 原始证据:[`/tmp/webhtv-repro-logcat.txt`](/tmp/webhtv-repro-logcat.txt)、用户截图 `/var/folders/ty/xxvjkz4s4pb9mndtj0hys0w40000gn/T/IMAGE 2026-08-27 10:13:59.jpg`。 + +## 完成目标 + +消除用户复现的两个 Exo 预缓存问题,同时保持前台播放契约不变: + +1. seek 时不让旧预载任务继续占用网络,也不在前台缓冲尚未恢复时立即启动新的预载任务; +2. HLS 预缓存准备阶段遇到 Media3 playlist 生命周期竞态时,不再让异常冒泡导致应用崩溃,并停止该媒体的预载重试; +3. Exo 前台 HLS 播放、解码器选择、字幕、DV/HDR、TrueHD/Atmos、代理 Range 和缓存格式不被这两个修复改变。 + +## 1. 现场证据与可证伪根因 + +### 1.1 seek 停顿的日志闭环 + +两次操作均在同一 Exo preload session 中观察到“取消旧任务很晚、随后又启动新任务”的序列: + +| 日志时间 | 事件 | 证据 | 解释 | +| --- | --- | --- | --- | +| 10:14:04.419 | task 1 start | `generation=6`, `buffered=11684`, `loading=true` | seek 前/中的预载仍在运行,前台只有约 12 ms 缓冲 | +| 10:14:06.554 | task 1 cancelled | `reason=seek`, `elapsedMs=2135`, `cachedBytesRead=7291154` | `stopCurrentTask()` 返回后,后台任务仍存活约 2.1 s | +| 10:14:08.397 | task 2 start | `generation=8`, `buffered=9358`, `loading=true`, `waitTotalMs=2036` | seek 后不到 2 s 即重新提交预载;前台缓冲仍不足 | +| 10:14:08.812 | task 2 prepare-error | `HttpDataSourceException` | 失败任务进入当前重试路径 | +| 10:14:08.959 | task 3 start | `generation=8`, `buffered=17087`, `loading=true`, `waitTotalMs=2186` | prepare 失败后约 147 ms 又启动下一次预载 | +| 10:14:10.462 | task 3 cancelled | `reason=seek`, `elapsedMs=1504` | 第二次 seek 仍需等待后台任务退出 | +| 10:14:13.429 及以后 | task 4--12 start/error | 约 5 s 周期,`buffered=9182..51239` | 失败且无进展的预载继续重试,制造额外网络/优先级竞争 | + +本地调用链: + +- `app/src/main/java/com/fongmi/android/tv/player/exo/PreCache.java:296-304` 在 seek 回调中调用 `stopCurrentTask("seek")`,随后立即 `refillActive = true`、`check()`; +- `PreCache.java:503-508` 的 `stopCurrentTask()` 只能调用 `PreCacheHelper.stop()`; +- Media3 `PreCacheHelper.stop()` 将取消动作 post 到预缓存 looper,而不是同步终止下载线程; +- `PriorityTaskDataSource` 以 `C.PRIORITY_PLAYBACK_PRELOAD` 注册等待,取消期间累计等待从约 `2036 ms` 增长到 `3647 ms`; +- `PreCachePolicy.hasSafeBuffer()` 允许“非 loading 且达到 idle floor”时通过,但 seek 期间状态可能先经过 `STATE_READY`/回调竞态,当前代码没有独立的“seek 恢复闸门”阻止重新提交。 + +**根因判断(Grade A,本地可重复日志 + 源码):** 停顿的主要原因是 seek 取消与新预载提交没有隔离。旧任务异步退出,且 `onPositionDiscontinuity()` 在同一回调中允许下一次 `check()`;前台只有约 9--35 ms 缓冲时,预载仍会进入下载/重试路径。日志没有显示 vivo MediaCodec 崩溃或解码器初始化失败,不能把这次停顿归因于设备解码器。 + +### 1.2 HLS 崩溃的堆栈闭环 + +用户截图中的完整关键栈为: + +```text +java.lang.NullPointerException + at com.google.common.base.Preconditions.checkNotNull + at androidx.media3.exoplayer.hls.HlsMediaPeriod.getStreamKeys(HlsMediaPeriod.java:219) + at androidx.media3.exoplayer.offline.DownloadHelper.getDownloadRequestBuilder(DownloadHelper.java:938) + at androidx.media3.exoplayer.offline.DownloadHelper.getDownloadRequest(DownloadHelper.java:911/879) + at androidx.media3.exoplayer.source.preload.PreCacheHelper$DownloadCallback.onPrepared(PreCacheHelper.java:473) +``` + +本地 AAR 对应代码: + +- `PreCacheHelper.DownloadCallback.onPrepared()` 在 `PreCacheHelper.java:468-481` 无条件调用 `helper.getDownloadRequest(null, startPositionMs, durationMs)`; +- `HlsMediaPeriod.getStreamKeys()` 在 `HlsMediaPeriod.java:216-220` 对 `playlistTracker.getMultivariantPlaylist()` 调用 `checkNotNull()`; +- Media3 `HlsPlaylistTracker` 的公开契约明确写明:`getMultivariantPlaylist()` 在初始 playlist 尚未加载时允许返回 `null`; +- 因此“period 已触发 prepared 回调”与“multivariant playlist 已可用于离线 stream-key 计算”不是同一个生命周期条件,预缓存路径存在竞态。 + +**根因判断(Grade A,本地 AAR + 官方契约 + 截图):** 崩溃发生在预缓存下载请求建单,不是视频解码器或前台播放线程。当前 `PreCacheHelper` 把一个允许抛出状态竞态的 `getDownloadRequest()` 当成了不会失败的回调操作。 + +### 1.3 附带异常(不并入本阶段) + +日志还出现: + +```text +UnrecognizedInputFormatException +ERROR_CODE_PARSING_CONTAINER_UNSUPPORTED +TV-exo-preload: ... mime=application/x-mpegURL +``` + +这表示至少有直链响应被判为 HLS MIME、但内容不像 HLS playlist。当前 `PreCache.java:154-158` 已有“预载使用原始 MediaItem、不要由 route classifier 覆盖 MIME”的保护;本阶段只保留该风险记录和 telemetry,不把 MIME/Extractor 选择扩展成第三个修复目标。若后续仍能用同一资源复现,应另开任务按输入探测处理。 + +## 2. 当前 WebHTV 代码与边界 + +### 2.1 现有保护 + +- `PreCache` 已有 generation、`PreloadLifecycleTracker`、buffer gate、内存/存储/外部回路状态和 seek 诊断;本阶段应补一个明确的 seek-suppressed 状态,而不是重写整个预载状态机。 +- `PriorityTaskDataSource` 已给前台播放更高的 `C.PRIORITY_PLAYBACK`,但它只能在读/开阶段让预载等待,不能保证后台网络调用立即从阻塞的 `upstream.read()` 返回。 +- `PreCacheHelper.release()` 的资源销毁顺序已有专门处理,不能因本问题改成先 shutdown executor 再 release helper。 +- `third_party/patches/media3-deferred-cues.patch` 已存在并随 `third_party/media-lock.json` 使用,但它只处理 Matroska Cues 延后,和 HLS `getStreamKeys()` 竞态无关;不能借此扩大 Media3 patch 范围。 + +### 2.2 明确不改的行为 + +- 不改 `DefaultLoadControl` 的启动/重缓冲阈值;现场的停顿发生在 seek 取消和预载重试竞争,不是单纯的起播缓冲阈值问题。 +- 不改连接/读取 timeout、OkHttp 或代理 Range;本次现场已看到后台错误和优先级等待,不能证明网络建连是首因。 +- 不改解码器、Surface、DV7→P8.1/HDR10 fallback、TrueHD/Atmos、字幕和 MPV native。 +- 不在 `HlsMediaPeriod.getStreamKeys()` 中伪造空 stream keys;这样可能静默生成不完整的下载请求,掩盖前台/离线语义问题。 + +## 3. 最佳实践证据 + +| 结论 | 来源与修订 | 等级 | WebHTV 适用性与决策影响 | +| --- | --- | --- | --- | +| HLS tracker 初始 playlist 未加载时可返回 null | AndroidX Media `HlsPlaylistTracker` 官方源码:,访问 2026-08-27;`getMultivariantPlaylist()` Javadoc 与 `@Nullable` | A | 直接证明 `checkNotNull()` 不是安全的生命周期判断;修复应放在预缓存建单边界。 | +| `HlsMediaPeriod.getStreamKeys()` 当前对 playlist 使用强制非空 | AndroidX Media `HlsMediaPeriod.java` 官方源码:,release,访问 2026-08-27,约 216-220 行 | A | 不宜在 App 层假设 period prepared 等于 playlist ready;也不宜伪造 stream key。 | +| `PreCacheHelper.onPrepared()` 无条件生成 DownloadRequest | AndroidX Media `PreCacheHelper.java` 官方源码:,release,访问 2026-08-27,约 468-481 行 | A | 最窄的安全边界是把建单异常转成预缓存失败回调,并让前台继续播放。 | +| HLS 下载/stream-key 计算已有已知边界缺陷,但不是本次 NPE 的直接修复 | AndroidX Media issue #3333:,关联修复 `242c34228d3823b0dec5b40af02096f47681e58f`,访问 2026-08-27 | B/A | 上游修复针对 `IndexOutOfBoundsException` 和冗余 rendition 索引,不解决 `multivariantPlaylist == null`;不能声称 cherry-pick 该提交即可修复本崩溃。 | +| Media3 `stop()` 是 looper 异步取消 | 本地锁定 AAR `PreCacheHelper.java:331-361` 与 WebHTV `PreCache.java:229-248` 资源释放注释 | A | 解释旧任务仍存活;App 必须在异步取消期间禁止新任务,而不是只增加优先级等待。 | +| 前台优先级只能降低预载竞争,不能替代取消闸门 | WebHTV `PriorityTaskDataSource.java:44-123`;本地日志 task 1/3 的 `waitTotalMs` 与 `elapsedMs` | A | 保留 playback priority,同时增加 seek-suppressed 和失败 circuit;不改变前台读取路径。 | +| 成熟播放器把昂贵后台动作与前台路径隔离 | MPV `demux/demux_mkv.c`(HEAD `49418246f30a9c24af31ac184aa24f39755db89a`,已记录于 E-SP2)及 FFmpeg `matroskadec.c`(HEAD `eb0bfa852e7b9c524960300607ba2c4617060a9b`) | B | 这是相同的隔离原则,但它们不提供可直接移植的 HLS pre-cache API;仅作为设计佐证,不引入 MPV/FFmpeg 代码。 | + +不适用的证据类别:本问题是 Android Media3 生命周期/并发竞态,没有算法或编解码质量假设需要学术论文;没有把无关 benchmark 或论坛经验作为设计依据。设备差异由同一 vivo 设备的原始日志和后续 A/B 验收覆盖。 + +## 4. 方案比较 + +| 方案 | seek 停顿 | HLS 崩溃 | 前台/离线语义 | 风险与回滚 | 决定 | +| --- | --- | --- | --- | --- | --- | +| 不变更 | 保留 1.5--2.1 s 旧任务退出和 5 s 失败重试 | 保留 NPE | 无新增风险 | 不能满足用户问题 | 拒绝 | +| 只升级/照搬未修改的上游 Media3 | `PreCacheHelper.stop()` 仍是异步;无 seek 隔离 | 当前 release 仍允许 tracker 返回 null;`242c342...` 只针对另一类索引错误 | 表面版本变化可能带来 AAR/patch 冲突 | 高,收益不足 | 拒绝为单独方案 | +| App 仅调用 `helper.stop()`,然后延迟固定 1--2 s | 可能减少新任务,但固定 sleep 与设备/网络无关 | 不处理 NPE | 前台不变 | 体感和耗电不稳定,无法定义正确恢复条件 | 拒绝 | +| App seek-suppressed gate + Media3 建单异常保护(推荐) | 立即阻止新 task;旧 task 异步退出期间不再竞争;前台恢复后按安全 buffer 放行 | 将 request-build NPE 变成 `onPrepareError`,对当前媒体关闭预载重试 | 前台 HLS 不变,预载失败不伪造下载请求 | 两个原子单元,可分别回滚;需 AAR 重建/设备验证 | 推荐 | +| 在 HlsMediaPeriod 中把 null playlist 当空 stream keys | 不解决 seek 竞争 | 可能不崩溃,但会静默生成不完整 DownloadRequest | 破坏离线/缓存语义且难诊断 | 高,拒绝后难发现 | 拒绝 | + +## 5. 推荐实现(等待批准) + +### E-SP3-A:App 层 seek 预载隔离 + +预计修改路径(批准后重新建立 `upstream` 实施 guard): + +- `app/src/main/java/com/fongmi/android/tv/player/exo/PreCache.java` +- 如需可测试的纯状态机,再增加 `app/src/test/java/com/fongmi/android/tv/player/exo/` 下单个 policy test;不做无关重构。 + +行为设计: + +1. `onPositionDiscontinuity()` 先标记 `seekSuppressed=true`、`refillActive=false`、取消 scheduled callback、增加 generation,再调用现有 `helper.stop()`;不在同一 seek 回调中 `check()` 重新提交任务。 +2. 所有 `update()`/`check()` 在 `seekSuppressed` 时只记录等待状态,不启动 `PreCacheHelper.preCache()`。 +3. 仅在前台播放重新进入稳定状态(`isPlaying=true` 或等价的 READY 回调)后清除 suppression;清除后仍经过现有 `BufferGate.RECOVERY`/`PreCachePolicy.hasSafeBuffer()`,不以固定 sleep 代替安全条件。 +4. 旧任务完成/失败/取消回调必须校验 generation;过期回调只能结束旧 telemetry,不能打开新下载。 +5. 对连续“无进展的 prepare/download error”增加当前媒体的 preload-only circuit,避免 task 4--12 这类重复重试;不影响 foreground DataSource,也不把 transient foreground 网络错误升级为播放失败。 + +### E-SP3-B:Media3 `PreCacheHelper` HLS 建单保护 + +预计修改路径(批准后): + +- `third_party/patches/media3-precache-hls-safety.patch`(新补丁,窄改 `PreCacheHelper.DownloadCallback.onPrepared()`); +- `third_party/media-lock.json` 中该补丁的 hash/顺序; +- 重建并更新受影响的 Media3 `media3-exoplayer`/HLS AAR、sources、POM/module 校验文件。 + +行为设计: + +1. `helper.getDownloadRequest(null, startPositionMs, durationMs)` 放入窄异常边界;至少覆盖 `NullPointerException`/`IllegalStateException` 这类 request-build 生命周期异常,并保留原始 cause。 +2. 异常时先 release `DownloadHelper`,再通过已有 `Listener.onPrepareError()` 传递可诊断的 `IOException` 包装;不调用 `onPrepared()`,不生成伪造 `DownloadRequest`。 +3. App 收到该错误后结束当前预载任务并打开 E-SP3-A 的媒体级 preload circuit;前台 `ExoPlayer` 不停止、不切换 decoder、不改变 HLS playlist tracker。 +4. 真正的网络/IO 错误继续遵循现有 `onPrepareError`/`onDownloadError` 分类;只有无进展或明确 request-build 生命周期异常触发预载 circuit,避免把所有临时网络波动永久熔断。 + +### 原子性、依赖和回滚 + +- E-SP3-A 不依赖 AAR,可先独立验证并回滚;E-SP3-B 与 Media3 AAR/lock 必须成套回滚。 +- 两个单元都只属于 Exo;不修改 MPV、FFmpeg、nextlib native 或共享 `.so`。 +- 只有用户批准后才进入 `upstream` guard;批准前不创建 patch、AAR 或 APK。 + +## 6. 验收矩阵与阈值 + +### 6.1 静态/单元验证 + +- `git diff --check`、task guard scope/checkpoint 检查。 +- E-SP3-A:新增 policy/state 单测覆盖 seek suppression、generation 过期回调、恢复条件和 preload-only circuit;运行受影响的 Exo Java 编译/单测一次。 +- E-SP3-B:Media3 patch 应用、`media3-exoplayer`/HLS 源码编译、AAR/POM/module/source hash 与 `third_party/media-lock.json` 一致。 + +### 6.2 设备复现(同一 vivo V2453A) + +使用与本次相同的设置、来源和网络条件,基线与候选各至少 3 次,保存原始 logcat: + +| 场景 | 必须满足 | +| --- | --- | +| 连续两次拖动 seek | 从 seek 事件到前台恢复稳定前不得出现新的 `task-start`;旧 task 的取消回调可异步到达,但不能阻塞前台;`waitTotalMs` 不再随新预载任务增长。 | +| seek 后缓冲恢复 | 预载只在现有 recovery watermark/安全 buffer 条件满足后恢复;不能用固定延时掩盖竞态。 | +| 原始 HLS 崩溃资源 | 应用不崩溃;日志出现一次可识别的 preload request-build/prepare-error;前台播放保持可继续或按现有错误 UI 结束,不能生成不完整 DownloadRequest。 | +| HLS 正常播放 | 不因预载保护改变 playlist、track、解码器、字幕、DRM 或时间线。 | +| 非 HLS MP4/MKV/TS | 预载和 seek 行为不回归;E-SP2 deferred Cues、DV/TrueHD/字幕路径保持原有结果。 | +| stop/release/source switch | 无线程向已 shutdown executor 提交任务,无 stale callback 重新启动 preload。 | + +性能结论只在同设备/同资源/同网络的 3 次中位数和失败率均记录后给出;“编译成功”不视为 seek 或生命周期通过。 + +### 6.3 Go/No-Go + +任一条件成立即不接受候选: + +- 仍有 NPE 或其他 request-build 异常从预载 looper 冒泡到应用; +- seek suppression 期间出现新的 preload task,或前台首个可播放时刻变慢; +- HLS 前台播放被预载错误连带停止、切 decoder、改 MIME 或改变 track keys; +- AAR、patch、lock、sources/POM hash 不一致; +- 任一现有本地 Media3 patch、E-SP2 deferred Cues、缓存/Range 或双 ABI 产物被无关改动。 + +## 7. 观测、回滚和发布 + +- 继续记录 `session/generation/task/reason/waitTotalMs/buffered/loading`;新增 `seek-suppressed`、`preload-circuit-open` 和 `request-build-error` 事件,便于确认旧任务与新任务是否隔离。 +- E-SP3-A 回滚:恢复该原子 App commit,不触碰 Media3 AAR。 +- E-SP3-B 回滚:成套恢复 `third_party/patches/media3-precache-hls-safety.patch`、`third_party/media-lock.json`、受影响 AAR/POM/module/sources 和 App 适配;不回滚 MPV/native。 +- 实施阶段必须记录完整 commit、AAR/source SHA-256、验证日志和唯一 recovery tag;未通过设备验收不得标为完成或发布。 + +## 8. 用户决策 + +- 推荐批准:`E-SP3-A` + `E-SP3-B`,按上述两个原子单元实施。 +- 暂不批准:修改 HlsMediaPeriod 返回空 stream keys、调大网络 timeout、全局关闭预载、修改 decoder/renderer/MIME、MPV/FFmpeg 依赖升级。 +- 当前决定:**approved by user on 2026-08-27**。 + +## Checkpoint 1:2026-08-27 现场诊断与方案包 + +- 目标/范围:vivo V2453A 上两次 seek 停顿 + 用户截图 HLS NPE;仅 assessment,文档和索引为唯一允许修改路径。 +- 基线:分支 `fongmi-sync-bugfix`,HEAD `a20a31a7c6be2454459db68ec41b7cebf824d1a6`;工作区在本阶段开始时干净。 +- 已完成证据:保存 `/tmp/webhtv-repro-logcat.txt`;确认 task 1/3 的 2135/1504 ms 异步取消、seek 后 9--35 ms buffer、重复 HttpDataSourceException;截图确认 `HlsMediaPeriod.getStreamKeys()` null 竞态。 +- 文件变化:本任务文档和主评估索引;无代码、AAR、lock、APK、`.so` 变化。 +- 验证:待文档/索引机械校验与 `git diff --check`;实现验证待用户批准后进行。 +- 未决风险:原始 HLS URL 在脱敏日志中不可见,设备验收需重新使用用户截图对应资源或等价可复现 HLS;附带 MIME 误判另开问题。 +- 回滚锚点:当前 HEAD `a20a31a7c6be2454459db68ec41b7cebf824d1a6`;本阶段不创建生产 commit/tag。 +- 下一动作:用户确认是否按 E-SP3-A/E-SP3-B 进入实施;收到批准后重新建立 `upstream` guard 并先实现 E-SP3-A。 + +## Checkpoint 2:2026-08-27 用户批准实施 + +- 用户决定:批准在不直接或间接破坏现有功能的前提下实施 `E-SP3-A + E-SP3-B`。 +- 完成记录:Assessment packet approved by user; begin E-SP3-A App seek isolation, then E-SP3-B Media3 HLS request-build guard. +- 权限边界:批准范围只包含本文已列的两个原子单元;不授权修改 decoder/renderer、MIME、MPV/FFmpeg/native 或其他播放器行为。 +- 下一动作:Start upstream guard for E-SP3-A with declared App source/test paths. + +## Checkpoint 3:2026-08-27 E-SP3-A 已实施 + +- 实现:seek 发生时停止当前预载并进入 `seekPreloadSuppressed`;只有前台恢复到 `STATE_READY + isPlaying + !isLoading + safeBuffer` 才恢复预载。连续两次非 loopback 预载错误后,仅打开当前媒体的 preload-only circuit。 +- 保持的契约:不改前台播放、`DefaultLoadControl`、MIME、解码器、Range、代理、网络 timeout、MPV 或 native 依赖。 +- 验证:`PreCachePolicyTest` 与 `:app:compileMobileArm64_v8aDebugJavaWithJavac` 在该原子单元完成时通过。 +- 提交:`41b1276111f37bdef75b0d057e4458b70bd8ad28`。 +- Recovery tag:`recovery/E-SP3-A/20260827112014-41b1276111f3`。 +- 回滚:回滚该提交即可恢复旧 App 预载策略,不触碰 Media3 AAR。 + +## Checkpoint 4:2026-08-27 E-SP3-B 源补丁已实施 + +- 实现:`PreCacheHelper.DownloadCallback.onPrepared()` 捕获 `getDownloadRequest()` 的 `RuntimeException`,release helper,并把 cause 包装成 `IOException("Pre-cache download request unavailable", cause)` 交给已有 `onPrepareError()`。 +- 保持的契约:不伪造 stream keys,不修改 `HlsMediaPeriod`、playlist tracker 或前台 HLS 播放路径。 +- 补丁:`third_party/patches/media3-precache-hls-safety.patch`,SHA-256 `9b48e895bd3923159f880152a54160e7c937b2b0369d717da559a7ad98fd14f7`。 +- 提交:`a007af32c85cb120f469c3dc34a58c2c7cd907ef`。 +- Recovery tag:`recovery/E-SP3-B/20260827113637-a007af32c85c`。 + +## Checkpoint 5:2026-08-27 E-SP3-B Media3 产物已发布 + +- 固定源码:`e3e922d5c01bc0b564849940fe589daf37360d15`;构建脚本按显式顺序应用全部既有补丁和 E-SP3-B 补丁。 +- 构建:Media3 发布成功,`474 actionable tasks: 474 executed`。全模块发布产生的无关机械改写已恢复,只保留真正受补丁影响的 `media3-exoplayer` AAR、sources JAR 和校验侧车。 +- AAR SHA-256:`485805506d44b739f3cd4bf179241f0322a3e52de6b29625c3133832eaa187ea`。 +- Sources SHA-256:`f378864ac3817fd95132268170e6c0ca6d3dc76f9a7eb09c51d60cb06027d442`。 +- 内容验证:sources 与 AAR bytecode 均包含 `Pre-cache download request unavailable`;MD5/SHA-1/SHA-256/SHA-512 发布侧车与实际文件一致。 +- App 验证:干净构建已成功完成 `:app:compileMobileArm64_v8aDebugJavaWithJavac`,证明新 AAR 可被当前 App 编译消费。 +- 提交:`97d02d72b1b4a3eed92d42cd6857fd822c036a8d`。 +- Recovery tag:`recovery/E-SP3-B-PUBLISH/20260827123702-97d02d72b1b4`。 +- 回滚:成套回滚该提交与前一补丁提交;不回滚 E-SP3-A、MPV 或 native 依赖。 + +## Checkpoint 6:2026-08-27 设备验收阻塞 + +- 设备:vivo V2453A,Android 15 / SDK 35,序列号 `10CF6H1D2L0009S` 已连接。 +- APK 构建:`:app:assembleMobileArm64_v8aDebug` 在完成 App Java 编译、dex 和 native merge 后,失败于既有 `:app:processMobileArm64_v8aDebugResources`。 +- 阻塞证据:缺少 `attr/selectableItemBackgroundBorderless`、`attr/resize_mode`、`Theme.Material3.DynamicColors.DayNight.NoActionBar`、`TextAppearance.MaterialComponents.Tooltip` 等 Material/UI 资源。该失败不在本任务声明路径,也不是 Exo AAR 编译错误。 +- 结论:没有候选 APK,故未安装到设备;不得宣称两次 seek suppression 或原 HLS 崩溃场景已通过实机验证。 +- 当前风险:代码与依赖产物已完成并可编译,但 Go/No-Go 的设备运行项仍未关闭。 +- 下一动作:单独解决或取得已知可构建基线中的 Material 资源链接问题后,重新构建 arm64 APK,安装到同一 vivo,清空 logcat,并按 6.2 的 seek/HLS 场景完成验收。 + +## Checkpoint 7:2026-08-27 候选实机复现纠正 + +- 候选 APK 已通过隔离 Gradle 缓存构建并安装到 vivo V2453A;原 Material 资源链接失败确认是共享 Gradle transform 缓存污染,不是仓库源码缺失。 +- 用户在同一视频多次复现:普通 seek 后仍有约 1 秒明显停顿,并非此前日志推断的约 8.5 秒。 +- 设备日志显示 seek 时正在运行的自动预载任务立即以 `reason=seek` 取消;seek 前后只有 codec flush/config 更新,没有新的 `Created component`,因此“每次 seek 都重新探测并重建 decoder”不成立。 +- `UnrecognizedInputFormatException`、MIME 从自动探测切为 HLS、decoder 创建发生在媒体首次打开或重新打开阶段,不等同于普通 seek 停顿。 +- 当前最小可证伪假设:seek 到未缓存位置后进入 `BUFFERING`,现有 Exo `3000 ms` rebuffer 门槛造成约 1 秒恢复等待;需要补充 seek 起点/目标、`BUFFERING -> READY` 时长和 READY 时缓冲量日志后再决定行为修复,避免降低正常网络断流的抗抖动能力。 +- 下一动作:增加不改变播放行为的 seek 恢复定向日志,构建安装后用同一视频复现一次。 + +## Checkpoint 8:2026-08-27 seek 诊断入口纠正 + +- 第一版埋点已编译安装,但用户复现时没有输出 `TV-exo-seek`;调试日志开关已开启。 +- 根因是拖动进度条经 `MediaController` 直接发送 seek,未进入 `PlayerManager.seekTo()` 的请求埋点;Analytics discontinuity 已在正确的公共路径上。 +- 纠正方案:保留调试开关,在 `DISCONTINUITY_REASON_SEEK/SEEK_ADJUSTMENT` 到达且没有请求序号时建立诊断序号,继续量化 `BUFFERING -> READY -> first-frame/playing`;不改变播放行为。 +- 下一动作:增量构建安装纠正后的诊断 APK,清空 logcat 后复现一次并据时序实施最小修复。 + +## Checkpoint 9:2026-08-27 画面恢复后停顿的诊断边界 + +- 用户进一步明确:问题不是 seek 后等待缓冲期间黑屏或静止,而是缓冲结束、画面已经恢复并开始播放后,又额外停顿一下再正常播放。 +- 现有多次设备日志已排除每次 seek 的 MIME 重新探测、MediaSource/decoder 重建;seek 邻近只看到 codec flush/config 更新。 +- 因此不调整 seek 精度或 rebuffer 阈值;下一轮只观察恢复首帧后的连续视频帧间隔、`isPlaying`/playback state、音频推进、underrun/sink error 和预载状态。 +- 完成说明:seek 后停顿发生在画面恢复之后;现有日志排除每次 seek 的 MIME 探测和 decoder 重建,下一轮只补首帧后视频帧间隔与音频推进时序。 +- 下一动作:增加 seek 后首帧/视频帧间隔/音频推进诊断,构建安装并复现一次。 + +## Checkpoint 10:2026-08-27 最新诊断 APK 重新打包安装 + +- 目标/车道/范围:`quick-fix`;仅重新构建并安装当前 E-SP3-DIAG 诊断代码,范围仍为 `PlayerManager.java`、`PlaybackAnalyticsListener.java` 与本文档,不扩展播放行为。 +- 基线:分支 `fongmi-sync-bugfix`,HEAD `0250fd01295fad8c499c699da45e07eb3834256d`。 +- 受保护的既有改动:上述三个路径均为当前任务已有未提交改动;重新打包不得清理、覆盖或混入其他路径。 +- 已完成证据/文件变化:首帧后视频间隔、音频推进、underrun/sink error 与 isPlaying 恢复诊断代码已经存在;本检查点只追加任务状态,不新增播放行为。 +- 验证状态:此前同一变体构建成功;本轮按用户要求重新执行 `:app:assembleMobileArm64_v8aDebug`,随后覆盖安装并核对设备端包与启动状态。 +- 未决风险:必须以本轮新产物成功安装为准;上一次安装曾被 OEM 权限确认中止。 +- 回滚锚点:HEAD `0250fd01295fad8c499c699da45e07eb3834256d`;诊断改动尚未提交,不执行清理或回退。 +- 下一动作:立即重新构建 mobile arm64 debug APK,并用 OEM 安装器辅助流程覆盖安装到已连接 vivo 手机。 + +## Checkpoint 11:2026-08-27 三次 seek 停顿根因定位 + +- 现场证据:设备应用内日志保存为 `/tmp/e-sp3-3seek-app-debug.log`,系统日志保存为 `/tmp/e-sp3-3seek-current.log`。用户连续三次 seek 后都复现“目标画面先出现,再冻结一下才连续播放”。 +- 第一次:目标首帧在 seek 后 `485 ms` 出现;下一帧相隔 `1734 ms`;播放器在累计约 `9054 ms` 前向缓冲后进入 `READY`。 +- 第二次:目标位置首帧出现后,下一帧相隔 `1003 ms`;播放器在约 `8466 ms` 前向缓冲后进入 `READY`。 +- 第三次:目标位置首帧出现后,下一帧相隔 `642 ms`;播放器在约 `9088 ms` 前向缓冲后进入 `READY`。 +- 一致原因:三次都在 `BUFFERING` 阶段允许渲染一张 seek 目标帧,但 `AutoLoadControl` 随后锁定 `episode=startup startMs=8000`,原因均为 `throughput-deficit`;播放时钟必须等约 8 秒媒体缓冲后才启动,所以用户看到目标画面冻结约 0.6--1.7 秒。 +- 排除项:三次窗口内没有 decoder `Created component`/release-recreate,没有 audio underrun、audio sink error 或崩溃;因此不是 decoder 重建,也不是音频 sink 故障或预载取消。 +- 诊断日志限制:三次 seek 在 30 秒追踪窗口内复用了 `seq=2`,因此 `elapsed`/`bufferingDuration` 为该窗口累计值;每次 `discontinuity`、`playback-buffer event=start/end` 和视频帧 gap 仍能独立确定上述时序,不影响根因结论。 +- 最小修复边界:不得降低正常首次启动或普通网络断流的全局阈值;应把用户 seek 恢复识别为独立 episode,仅调整 seek 后启动门槛,并阻止主动 seek 被计入网络 rebuffer 风险历史。 +- 下一动作:补充 E-SP3 seek-specific threshold 的决策设计与验收/回滚条件,取得该播放行为阶段批准后实施、构建并在同一视频复测三次。 + +## E-SP3-C:seek 专用恢复门槛 + +- 用户决定:用户于 2026-08-27 明确要求修复,批准该窄播放行为单元。 +- 决策问题:如何消除“seek 目标帧已出现但仍冻结约 0.6--1.7 秒”,同时不降低首次启动或真正网络 buffer depletion 的保护门槛? +- 官方/上游语义(A):当前锁定 Media3 sources `e3e922d5c01bc0b564849940fe589daf37360d15` 的 `DefaultLoadControl` 明确定义 `bufferForPlaybackMs` 用于首次启动和 seek 等用户动作,默认值为 `1000 ms`;`bufferForPlaybackAfterRebufferMs` 只用于非用户动作导致的 buffer depletion,默认值为 `2000 ms`。同一 sources 中 `ExoPlayerImplInternal.seekToPeriodPosition()` 在 seek 时显式把 `isRebuffering` 重置为 false。 +- WebHTV 实机证据(A):`/tmp/e-sp3-3seek-app-debug.log` 的三次 seek 都被本地自适应层锁成 `episode=startup startMs=8000`,目标首帧先出现,随后冻结 `1734/1003/642 ms`,直到前向缓冲达到 `9054/8466/9088 ms` 才进入 READY。 +- 当前代码原因:`AutoLoadControl` 只区分 `STARTUP/REBUFFER`;Media3 正确地把 seek 报为 `rebuffering=false`,但 WebHTV 因此误选 `STARTUP`。同时 `PlaybackAnalyticsListener` 把 seek 后 BUFFERING 计入网络 rebuffer 历史,进一步抬高后续风险。 +- 方案比较:不变更无法满足用户;把全局 startup/rebuffer 降到 1 秒会破坏真实弱网保护;依赖 seek 时间猜测或固定 sleep 不可靠;推荐在现有 App 协调器增加一次性 `SEEK` episode,沿用 Media3 的 `1000 ms` 用户动作门槛,并只从网络 rebuffer 统计中排除该 seek 区间。 +- 最终设计:收到 `DISCONTINUITY_REASON_SEEK/SEEK_ADJUSTMENT` 时标记当前 Exo session 的 seek recovery;`AutoLoadControl` 在 `rebuffering=false` 且标记有效时选择 `SEEK`,阈值为 `min(当前自适应 startMs, 1000 ms)`;READY/IDLE/ENDED 或超时后清除。真实 `rebuffering=true` 始终优先选择 `REBUFFER`,首次启动仍选择 `STARTUP`。 +- 保护契约:不改用户配置值、target bytes、min/max buffer、ABR、网络保护、预载、decoder/renderer、Surface、MIME、Media3 AAR、MPV 或 native;不允许 seek 风险覆盖真实 rebuffer。 +- 验收:单测覆盖 `REBUFFER > SEEK > STARTUP` 分类和 `SEEK <= 1000 ms`;arm64 Java 编译通过;同一 vivo/视频三次 seek 日志必须为 `episode=seek`,READY 不再等待约 8--9 秒媒体缓冲,目标首帧后的额外 gap 不超过 `300 ms`,且 seek 不增加网络 rebuffer count/total。 +- 回滚:单独回滚 E-SP3-C App commit,恢复旧 `STARTUP/REBUFFER` 分类;E-SP3-A/B、诊断日志和 Media3 产物不动。 +- 不适用证据:不涉及 ABI、native、codec 算法、安全解析或新依赖,学术论文、跨播放器代码和二进制供应链研究不会改变该 App 层分类修复。 + +## Checkpoint 12:2026-08-27 E-SP3-C App 行为实现 + +- 基线:分支 `fongmi-sync-bugfix`,HEAD `0d2f80fb3a0f92717d820556f739b68b9d9a62db`;诊断单元已提交并有 recovery tag。 +- 实现:阈值协调器新增 session-bound、30 秒自动过期的 `SEEK` 标记;`AutoLoadControl` 按 `REBUFFER > SEEK > STARTUP` 分类,seek 实际门槛为 `min(startMs, 1000 ms)`;Analytics 在 seek recovery 中不增加自适应阈值使用的 rebuffer 历史。 +- 保持契约:首次启动、真实 rebuffer、target bytes、min/max buffer、ABR、网络保护、预载、decoder/renderer、Media3 AAR 和其他播放器未改变。 +- 验证:`AutoLoadControlTest` 与 `ExoPlaybackThresholdCoordinatorTest` 共 17 个测试通过,`:app:compileMobileArm64_v8aDebugJavaWithJavac` 通过;Gradle `BUILD SUCCESSFUL`。 +- 未决风险:`PlayerManager` 的公共 `PlaybackBufferingTracker` 仍可能把 seek 后 BUFFERING 记入通用网络重缓冲 telemetry;该统计排除应作为独立窄单元完成,不与 LoadControl 行为提交混合。 +- 回滚锚点:回滚 E-SP3-C App commit 即恢复旧阈值分类,不影响 E-SP3-A/B 和诊断单元。 +- 下一动作:提交并标记 E-SP3-C 行为单元;随后单独排除公共 buffering tracker 的用户 seek 事件,再打包安装实机验收。 + +## Checkpoint 13:2026-08-27 seek 公共统计隔离 + +- 实现边界:`PlayerManager.recordBufferingState()` 只在 Exo、刚进入 BUFFERING、当前没有 tracker episode 且 Analytics 确认是有效用户 seek recovery 时跳过公共 rebuffer 计数,并记录 `phase=seek outcome=user-action`。 +- 保持契约:首次启动、真实网络 rebuffer、MPV/IJK managed reload、播放阈值和 telemetry 字段格式不变;READY 无需伪造结束事件,因为 seek BUFFERING 从未打开 tracker episode。 +- 验证结果:`bash gradlew --offline --no-daemon :app:clean :app:compileMobileArm64_v8aDebugJavaWithJavac` 通过;用户已在 vivo 实机使用同一视频重复 seek,确认修复后播放表现正常。 +- 回滚:单独回滚该统计隔离 commit 即恢复旧公共计数,不影响 seek 专用播放门槛。 +- 下一动作:通过 task guard 原子提交该统计隔离单元并创建 recovery tag。 + +## Checkpoint 14:2026-08-27 实机验收与收尾 + +- 完成:用户已在 vivo 实机重复 seek,确认修复后播放正常,本轮补充的公共 buffering 统计隔离代码已通过干净 arm64 Java 编译。 +- 工作区:分支 `fongmi-sync-bugfix`;基线 `038b6c58b265a7fbd5c6a173068d7fe1f4d868d3`;受保护的其他脏文件未改。 +- 变更文件:`PlayerManager.java`、`PlaybackAnalyticsListener.java`、本任务文档。 +- 验证:`bash gradlew --offline --no-daemon :app:clean :app:compileMobileArm64_v8aDebugJavaWithJavac` 通过;用户实机验收通过。 +- 回滚锨点:`038b6c58b265a7fbd5c6a173068d7fe1f4d868d3`;本单元提交后使用 task guard recovery tag 回滚。 +- 未决:无。 +- 下一动作:执行 task guard finish 并创建唯一 annotated recovery tag。 + +## Checkpoint 15:2026-08-27 APK 资源链接恢复 + +- 现象:执行 `:app:clean` 后,普通 assemble 在 `processMobileArm64_v8aDebugResources` 缺少 AppCompat、Material3 和 Media3 UI 资源。 +- 定性:变体 runtime 依赖图仍完整包含三组依赖,最近 seek 提交未改 Gradle 或 XML;根因是 AGP/Gradle 恢复了不完整的资源构建缓存,不是源码或依赖配置缺失。 +- 恢复:`--no-build-cache --rerun-tasks :app:processMobileArm64_v8aDebugResources` 成功重建资源;随后普通 `:app:assembleMobileArm64_v8aDebug` 通过。 +- 产物:`app/build/outputs/apk/mobileArm64_v8a/debug/app-mobile-arm64_v8a-debug.apk`,SHA-256 `da1514a4e826cd8a363051c615bb89ca44d49d861088dcf9acb3f7987ff0c46d`。 +- 代码处置:无需修改或回滚 seek 代码、Gradle 配置或依赖版本。 +- 下一动作:关闭资源恢复诊断单元并交付 APK。 diff --git a/docs/E1-exo-ffmpeg-9.0.1.md b/docs/E1-exo-ffmpeg-9.0.1.md index 3757087971..211a92d9ae 100644 --- a/docs/E1-exo-ffmpeg-9.0.1.md +++ b/docs/E1-exo-ffmpeg-9.0.1.md @@ -33,9 +33,9 @@ C2 有一项明确参考价值:它会让转换后的 DV 配置与 P8.1 码流 下一动作:清理非 Git 的旧 nextlib 缓存目录并运行双 ABI nextlib 构建。 -检查点:nextlib `6ff6cf9d0820382b3c233d018c52e4163b09d345` 已重新检出,两个 nextlib 补丁均已成功应用;首次构建未进入编译,原因是指定的 Android Studio JBR 路径不存在。主机实际可用 Java 为 `/Library/Java/JavaVirtualMachines/jdk-17.jdk/Contents/Home`。 +检查点:nextlib `6ff6cf9d0820382b3c233d018c52e4163b09d345` 已重新检出,两个 nextlib 补丁均已成功应用;首次构建未进入编译,原因是当时指定的外部 JDK 路径不存在。项目构建需要 JDK 21。 -下一动作:使用该真实 JDK 仅重试一次同一 `--nextlib-only` 构建;若 Gradle 明确要求 JDK 21,则记录环境阻塞,不继续重复尝试。 +下一动作:使用 JDK 21 仅重试一次同一 `--nextlib-only` 构建;若 Java 环境仍不满足项目要求,则记录环境阻塞,不继续重复尝试。 构建结果:`bash scripts/build_media_deps.sh --nextlib-only` 成功,Gradle 报告 `BUILD SUCCESSFUL in 14m 25s`。构建输入为 nextlib `6ff6cf9d0820382b3c233d018c52e4163b09d345`、FFmpeg `177f090e0503b7e013922ca903bde14b1c375f18`、NDK `28.2.13676358`、CMake `3.22.1`;两个 ABI 的 mbedTLS、libvpx、libarcdav3a 和 FFmpeg shared libraries 均完成。 diff --git a/docs/E2-1-exo-hdr-parser-safety.md b/docs/E2-1-exo-hdr-parser-safety.md new file mode 100644 index 0000000000..bd5f0d6f63 --- /dev/null +++ b/docs/E2-1-exo-hdr-parser-safety.md @@ -0,0 +1,126 @@ +# E2-1:Exo HDR / Dolby Vision parser safety + +- 任务 ID:`E2-1` +- 所属分类:Exo +- 状态:已完成 +- 唯一任务文档:`docs/E2-1-exo-hdr-parser-safety.md` +- WebHTV 同步目标:`fish2018/webhtv@c410bf4f40a0ef7babb5b6281b97fa4bc621c24d` +- WebHTV 同步基线:共同祖先 `b2eccc357662065e02e49af4caff4c059cf508f3` +- FongMi Media 基线:`FongMi/media@e3e922d5c01bc0b564849940fe589daf37360d15` + +## Recovery anchor + +- 目标:让 Exo 遇到截断、过短或越界的 Dolby Vision/HDR 配置时安全拒绝输入,并按 CTA-861.3 规范编码 Matroska 最低 mastering luminance;正常 MP4/MKV、现有 DV RPU 和 fallback 行为保持不变。 +- 接受标准:Media3 container/extractor 定向测试通过;parser-safety patch 可在现有四个 Media3 补丁之后重放;只发布受影响的 `media3-container`/`media3-extractor` AAR 与 sources;App Mobile/Leanback Java 编译通过;初始脏文件不被覆盖或提交。 +- 允许路径:本任务文档、主评估索引、`third_party/patches/media3-exo-hdr-parser-safety.patch`、`scripts/build_media_deps.sh`、`third_party/media-lock.json`、Media3 container/extractor Maven 产物。 +- 回滚:按 container、extractor、接线/文档三个单元分别回滚;完整恢复目标为实施前 `09af6a0069490a17e1f626407b483de3a688a4bf`,不回滚 E1、E2-2、MPV 或其他本地提交。 + +## 上游提交台账与处置 + +在线核对时间:2026-08-26(Asia/Shanghai)。GitHub API 返回 `fongmi-sync` 头 `c410bf4f40a0ef7babb5b6281b97fa4bc621c24d`;相对共同祖先只有以下两个 WebHTV 提交,台账完整: + +| 仓库 | 完整 commit | 处置 | 范围 | +| --- | --- | --- | --- | +| `fish2018/webhtv` | `e19289a3c9871563f891500bdc2d42be6be23f3d` | 实施候选;窄合并 | parser-safety patch、Media3 构建顺序/lock、container/extractor 产物 | +| `fish2018/webhtv` | `c410bf4f40a0ef7babb5b6281b97fa4bc621c24d` | 文档收尾;吸收内容并保留本地后续检查点 | E2-1 文档和主评估索引 | + +关联 FongMi/media 源提交: + +| 完整 commit | 关联与处置 | +| --- | --- | +| `f70e4b6f14d9f3b38ef953be80c53184f9c50bed` | 仅取 Matroska minimum mastering luminance 语义;不整提交替换本地 fork。 | +| `0cefd3ceec27444cf8faf02486b472bab39109fe` | 仅取短 DV config、major-version 和 MP4 box-boundary hunk;拒绝连带 CSD、compatible BL、renderer/output policy。 | +| `b63139c6432caa3f058e7f0496f0d754aa0eaa93`、`249774647b026e16b56467eb5d79479816f79f11`、`08c664eb8a213a956ff2c8b3d0fcea49902a81fa` | 当前 fork 已有等价覆盖,仅登记,不重复应用。 | + +## 证据与设计决策 + +### 当前 WebHTV 路径 + +- `scripts/build_media_deps.sh:230-247` 固定按 `media3-danmaku-live`、`media3-dolby-vision-matroska`、`media3-upstream-playback-fixes-2026-08`、`media3-deferred-cues` 顺序应用 patch;新 parser patch 必须排在 deferred Cues 之后。 +- `third_party/media-lock.json:4-32` 锁定 Media3 源 commit、每个 patch 的 SHA-256 和受影响 AAR/sources;`gradle/libs.versions.toml` 与 `settings.gradle:18` 证明 App 消费本地完整 Maven publication。 +- E2-2、Matroska Dolby Vision RPU、HDR10 fallback 和 deferred Cues 是必须保留的本地契约;本阶段不修改 renderer、CSD、RPU、网络、seek 或 MPV。 + +### 外部证据 + +- Android AOSP `MediaFormat.KEY_HDR_STATIC_INFO`(在线核对 2026-08-26)明确要求 ByteBuffer 包含 CTA-861.3 Static Metadata Descriptor;这支持按 CTA-861.3 的 `0.0001 cd/m²` 单位写入最低 mastering luminance。 +- AndroidX Media `release` 的 `DolbyVisionConfig.parse()` 仍从配置数据读取版本、profile 和 level;FongMi 源提交提供了可独立测试的长度/版本拒绝与 box 边界保护。Google ExoPlayer 对应 extractor 路径作为成熟相关实现,支持在解析外部字节前校验边界。 +- GitHub API 未发现两个 FongMi 源提交关联的 Pull Request;不把 PR 标题或提交标题当作正确性证据。论文、基准和性能报告对本次常数时间 parser safety 变更不适用。 +- 上游 WebHTV `e19289a3c9871563f891500bdc2d42be6be23f3d` 声称 JDK 21 定向测试、五 patch 重放、两个 release AAR、Mobile/Leanback Java 编译和 SHA-256 一致;这些是待在当前分支复核的候选证据,不直接视为本地验证结果。 + +### 方案比较与推荐 + +1. **不变**:继续承受 malformed DV 输入导致的异常/错误元数据风险;拒绝。 +2. **原样移植上游大提交**:会连带 DV CSD、compatible BL 和 renderer/output policy,覆盖已落地的 E2-2/本地策略;拒绝。 +3. **WebHTV 窄适配(采用)**:只引入 parser safety 与 CTA-861.3 luminance hunk,保留本地 Media3 patch、DV RPU、P8.1 CSD、fallback 和输出策略;按三个单元回滚。 + +推荐方案不新增线程、网络访问、native ABI 或公共 Media3 API;合法文件路径保持兼容,极端 malformed 文件从未定义行为变为受控解析失败。每个 boundary check 是常数时间,包体变化限于受影响 Media3 publication。 + +## 实施计划、验证与用户决策 + +- 单元 A:合并 parser patch、`scripts/build_media_deps.sh`、`third_party/media-lock.json` 和本记录。 +- 单元 B:只更新 `media3-container` 的 AAR、sources、module metadata 与校验文件。 +- 单元 C:只更新 `media3-extractor` 的 AAR、sources、module metadata 与校验文件。 +- 合并收尾:纳入 `fongmi-sync` 两个提交的内容;主评估索引保留本地已完成的后续检查点,不用上游旧文档覆盖本地诊断。 +- 最小验证顺序:`git diff --check` 与 lock/产物 SHA-256;五 patch `git apply --check` 重放;JDK 21 下 Media3 定向测试/Java 编译;随后 Mobile 与 Leanback arm64-v8a Debug Java 编译。 +- 未解决风险:真实厂商 DV codec、设备级 HDR 输出和非标准文件兼容性仍需设备/样片验收;不把 Java 编译结果表述为设备正确性证明。 +- 用户决策:用户明确要求合并上游最新代码,本记录将其解释为批准 `fongmi-sync@c410bf4f40a0ef7babb5b6281b97fa4bc621c24d` 的 E2-1 窄适配,不批准 E3-1a 或其他未审阅阶段。 + +## 当前状态 + +- 评估结论:E2-1 已完成,范围未超出批准的 parser-safety 窄适配。 +- 当前进度:parser patch、固定应用顺序、container/extractor publication、lock override、当前树定向验证和上游双亲合并均已完成。 +- 实施提交:`c9ddcf2bbdf902b771694cabbf85930d467bd8ba`、`f2db5952ebec66e94e8cddce6230cff035202274`、`1e96933f5fdc35e2eec49c474f5e5552cba4dd7a`。 +- 恢复标签:`recovery/E2-1-sync-parser/20260826104622-c9ddcf2bbdf9`、`recovery/E2-1-sync-container/20260826105926-f2db5952ebec`、`recovery/E2-1-sync-extractor/20260826110557-1e96933f5fdc`。 +- 最终双亲合并提交:`af28547d965fb862a4b8d005abe0eac07fe5196a`;父提交为 `1e96933f5fdc35e2eec49c474f5e5552cba4dd7a` 与 `c410bf4f40a0ef7babb5b6281b97fa4bc621c24d`。 +- 最终恢复标签:`recovery/E2-1-sync-closeout/20260826131620-af28547d965f`。 +- 当前未解决风险:真实厂商 DV codec、设备级 HDR 输出和非标准文件兼容性仍需设备/样片验收;Java 编译不代表设备正确性。 +- 下一动作:E2-1 已完成;进入队列中的下一项 Exo 任务 `E3-1a` 前先评估并等待用户批准。 + +## 评估检查点 + +### 2026-08-26:fongmi-sync 最新头评估完成 + +- 当前分支:`dev2@09af6a0069490a17e1f626407b483de3a688a4bf`;远端目标:`fish2018/fongmi-sync@c410bf4f40a0ef7babb5b6281b97fa4bc621c24d`。 +- 共同祖先:`b2eccc357662065e02e49af4caff4c059cf508f3`;目标领先 2 个提交,完整提交台账已记录。 +- 无副作用合并预演显示只有主评估索引存在内容冲突;代码、脚本、锁、补丁和 Media3 产物没有三方冲突。 +- 已核对本地 Media3 消费路径、FongMi/media 源提交、Android AOSP `KEY_HDR_STATIC_INFO` 契约和上游提交关联状态;建议采用 E2-1 窄适配,不引入 E3-1a 或其他阶段。 +- checkpoint: E2-1 fongmi-sync head assessment complete +- next: commit assessment record, then start implementation guard + +### 2026-08-26:单元 A 哈希验证修正 + +- 发现:Windows `core.autocrlf=true` 下,`git hash-object` 默认输出 Git blob SHA-1,不能直接与 lock 的文件 SHA-256 比较;这不是补丁内容变化。 +- 修正:用 `git hash-object --path` 与上游 blob ID 验证规范化内容,再用上游 LF blob 的 `sha256sum` 验证 lock 值。 +- 当前进度:单元 A 的 parser patch、固定应用顺序和 lock patch 条目已写入,尚未提交。 +- checkpoint: unit A hash verification command corrected +- next: run normalized blob and LF SHA-256 checks, then commit unit A + +### 2026-08-26:实施单元完成,进入合并收尾 + +- parser 单元提交 `c9ddcf2bbdf902b771694cabbf85930d467bd8ba`,container publication 单元提交 `f2db5952ebec66e94e8cddce6230cff035202274`,extractor publication 单元提交 `1e96933f5fdc35e2eec49c474f5e5552cba4dd7a`;三个提交均已创建 annotated recovery tag。 +- container/extractor 的 AAR、sources、module、POM 及四类 sidecar 已按上游规范化 blob 校验;lock 中 patch、AAR 和 sources SHA-256 已对应更新。 +- 当前合并冲突只涉及本任务文档和主评估索引;脚本、锁、补丁与产物没有新增冲突。上游 `e19289a3c9871563f891500bdc2d42be6be23f3d`、`c410bf4f40a0ef7babb5b6281b97fa4bc621c24d` 的内容已吸收,未采用其覆盖本地诊断的文档版本。 +- checkpoint: E2-1 implementation units complete; merge closeout pending +- next: stage the resolved documents and run current-tree verification + +### 2026-08-26:文档合并稿完成,进入当前树验证 + +- 合并稿保留主评估索引的本地检查点、`E-SP3` 状态和 E2-2/C2/MPV 边界,同时吸收上游 E2-1 完成记录;未修改脚本、锁、补丁或 Media3 产物。 +- 当前合并仅待将两份文档标记为已解决,并运行既定的 Media3 定向测试与 Mobile/Leanback Java 编译。 +- checkpoint: E2-1 documentation merge draft complete +- next: stage the two resolved documents and run current-tree verification + +### 2026-08-26:当前树定向验证通过 + +- JDK 21 下运行 `:app:compileMobileArm64_v8aDebugJavaWithJavac` 与 `:app:compileLeanbackArm64_v8aDebugJavaWithJavac --no-daemon`,Gradle daemon 日志记录 `BUILD SUCCESSFUL in 6m 22s`。 +- 五个 Media3 patch 按 LF 规范化内容与 lock SHA-256 全部匹配;`media3-container` 与 `media3-extractor` 的 AAR、sources SHA-256 全部匹配 lock override。 +- 当前工作树无未解决冲突,验证范围未触及受保护的 `third_party/sources/media` 外部 checkout;Media3 单元测试仍以既有上游 JDK 21 验证记录为依据。 +- checkpoint: E2-1 current-tree verification passed +- next: create the two-parent merge commit and recovery tag + +### 2026-08-26:双亲合并与恢复点完成 + +- 双亲合并提交 `af28547d965fb862a4b8d005abe0eac07fe5196a` 已创建,父提交为本地 E2-1 实施头 `1e96933f5fdc35e2eec49c474f5e5552cba4dd7a` 与上游收尾头 `c410bf4f40a0ef7babb5b6281b97fa4bc621c24d`。 +- annotated recovery tag:`recovery/E2-1-sync-closeout/20260826131620-af28547d965f`。 +- checkpoint: E2-1 merge and recovery point complete +- next: wait for approval before assessing E3-1a diff --git a/docs/E3-1a-exo-pixel-eac3-joc-guard.md b/docs/E3-1a-exo-pixel-eac3-joc-guard.md new file mode 100644 index 0000000000..a650ae41b5 --- /dev/null +++ b/docs/E3-1a-exo-pixel-eac3-joc-guard.md @@ -0,0 +1,182 @@ +# E3-1a:Exo Pixel E-AC3 JOC capability guard + +- 任务 ID:`E3-1a` +- 所属分类:Exo +- 状态:已实施,待实机验收 +- 唯一任务文档:docs/E3-1a-exo-pixel-eac3-joc-guard.md +- FongMi Media 基线:`FongMi/media@e3e922d5c01bc0b564849940fe589daf37360d15` +- WebHTV 基线分支:`dev2@6312c485f06346bb6205092c1909efa59bae7ac2` + +## Recovery anchor + +- 目标:在 Google/Pixel 设备上,当平台 E-AC3 decoder 无法解码 E-AC3 JOC 流时,阻止 Exo 将 `audio/eac3-joc` 降级为 `audio/eac3` 交给已知会失败的 MediaCodec;让 `CompatFfmpegAudioRenderer` 用 FFmpeg `eac3` 软解为 PCM 接管。非 Google 设备保持现有 2D 降级行为不变。 +- 接受标准:`MediaCodecUtilTest` 的 Google/非 Google JOC 两个 case 通过;App 在 Google 设备上 JOC 流不选平台 E-AC3 fallback 而走 FFmpeg PCM;非 Google 设备 JOC 仍可 2D 降级;`media3-exoplayer` AAR/sources 独立更新且可单独回滚。 +- 允许路径:本任务文档、主评估索引、`third_party/patches/media3-exo-eac3-joc-pixel-guard.patch`、`scripts/build_media_deps.sh`、`third_party/media-lock.json`、Media3 `media3-exoplayer` Maven 产物。 +- 回滚:删除 patch、还原 build 脚本 patch 数组和 lock override,重新发布 `media3-exoplayer` AAR/sources。完整恢复目标为实施前 HEAD;不回滚 E1、E2-1、E2-2、E-SP 系列或其他本地提交。 + +## 上游提交台账与处置 + +| 完整 commit ID | 主题 | 处置 | 阶段 | +| --- | --- | --- | --- | +| `1066f642a64434e7c3c0be687d3e94a4ca2815d7` | Support multiple alternative MediaCodec MIME types | **窄取**:只取 E-AC3 JOC 的 Google/Pixel guard 和对应测试 | E3-1a | + +### 上游 commit 详细记录 + +- 仓库:`https://github.com/FongMi/media.git` +- commit:`1066f642a64434e7c3c0be687d3e94a4ca2815d7` +- parent:`2bc207851df311340767e913931ca7b28cab1794` +- 日期:2026-05-23 +- 消息:`Support multiple alternative MediaCodec MIME types` — DTS-HD MA with core maps to both DTS-HD and DTS. Add wiring to support more than one alternative MIME type. +- 在线核对时间:2026-08-26(Asia/Shanghai) +- 访问方式:GitHub API `gh api repos/FongMi/media/commits/`,已读取完整 7 文件 diff + +该提交共修改 7 个文件: + +| 文件 | 改动 | E3-1a 是否纳入 | +| --- | --- | --- | +| `libraries/exoplayer/.../MediaCodecUtil.java` | `getAlternativeCodecMimeType()->String` 改为 `getAlternativeCodecMimeTypes()->List`;新增 `supportsEac3JocFallbackDecoding()` | **窄取**:只取 `supportsEac3JocFallbackDecoding()` 和 JOC 分支的 guard 逻辑 | +| `libraries/exoplayer/.../MediaCodecUtilTest.java` | 两个 JOC case 改名并适配 List 返回 | **窄取**:两个 JOC case | +| `libraries/exoplayer/.../MediaCodecInfo.java` | `isSampleMimeTypeSupported` 适配 List | 不纳入(fork 已有等价实现) | +| `libraries/exoplayer/.../DefaultTrackSelector.java` | `VideoTrackInfo` 适配 List | 不纳入(fork 已有等价实现) | +| `libraries/inspector/.../MediaExtractorCompatInternal.java` | 适配 List | 不纳入(fork 已有等价实现) | +| `libraries/transformer/.../SampleExporter.java` | 适配 List | 不纳入(fork 已有等价实现) | +| `libraries/transformer/.../TransformerUtil.java` | 适配 List | 不纳入(fork 已有等价实现) | + +### 当前 fork 覆盖关系 + +主评估检查点 9.1 已确认:当前 fork `e3e922d5...` 的祖先 `0592f21c...` 和 `07cc217a...` 已实现多 alternative MIME API 主体和 DTS-HD MA/DTS fallback 消费。当前 fork 的 `MediaCodecUtil.getAlternativeCodecMimeTypes()` 已存在且已处理 DTS-HD/DTS-UHD/DV/MV-HEVC 等分支,唯独 E-AC3 JOC 分支缺少 Google 设备 guard: + +```java +// 当前 fork(无 guard) +if (MimeTypes.AUDIO_E_AC3_JOC.equals(format.sampleMimeType)) { + return Collections.singletonList(MimeTypes.AUDIO_E_AC3); +} + +// 上游 1066f642(有 guard) +if (MimeTypes.AUDIO_E_AC3_JOC.equals(format.sampleMimeType)) { + return supportsEac3JocFallbackDecoding() + ? Collections.singletonList(MimeTypes.AUDIO_E_AC3) + : Collections.emptyList(); +} +// ... +private static boolean supportsEac3JocFallbackDecoding() { + return !Objects.equals(Build.MANUFACTURER, "Google"); +} +``` + +## 证据与设计决策 + +### 当前 WebHTV 路径 + +- `CompatFfmpegAudioRenderer.supportsFormatInternal`(app/src/main/java/.../CompatFfmpegAudioRenderer.java:48)先用 `FfmpegLibrary.supportsFormat` 判断 FFmpeg 是否支持该 MIME。 +- `FfmpegLibrary.getCodecName`(nextlib AAR sources)将 `MimeTypes.AUDIO_E_AC3_JOC` 映射到 `"eac3"`,FFmpeg 支持软解。 +- `ExoUtil.buildAudioRenderers`(ExoUtil.java:1013-1017)在 `super.buildAudioRenderers` 之后按 `getExtensionRendererIndex` 插入 `CompatFfmpegAudioRenderer`。`PREFER` 模式下 FFmpeg renderer 排在 MediaCodec renderer 之前,`ON` 模式排在之后。 +- `MediaCodecAudioRenderer.supportsFormat` 调用 `MediaCodecUtil.getDecoderInfos(format.sampleMimeType, ...)` 查询平台 decoder 是否支持原始 JOC MIME。若平台无 JOC decoder,再由 `getAlternativeDecoderInfos` 用 alternative MIME 查询。当前 fork 无条件返回 `audio/eac3` 作为 alternative,导致 Pixel 的平台 E-AC3 decoder 被选中,但该 decoder 无法解码 JOC 流,播放失败。 +- AndroidX Media Issue #3257(closed)标题 "EAC3-JOC MIME type should not be taken as EAC3 on Pixel Device" 记录了此问题:Pixel 集成了 E-AC3 decoder 但不支持 E-AC3 JOC 流;不带 guard 时 manifest 中 JOC 轨被选中后播放失败,带 guard 后回退到 AAC 轨可正常播放。访问方式 `gh api repos/androidx/media/issues/3257`,2026-08-26。 + +### 外部证据 + +- 上游 commit `1066f642...` 的 `supportsEac3JocFallbackDecoding()` 注释引用 `https://github.com/androidx/media/pull/3257`,明确"Some devices (e.g. Pixel) have an E-AC3 decoder that cannot handle E-AC3 JOC streams at all, even in degraded 2-D"。 +- AndroidX Media Issue #3257 body:"Pixel devices integrate an EAC3 decoder, but it does not support EAC3-JOC stream decoding."——这是产品决策而非技术限制。 +- WebHTV fork 的 `FfmpegLibrary.getCodecName` 已将 `AUDIO_E_AC3_JOC` 映射到 `"eac3"`,因此 FFmpeg 软解可接管 JOC 流,guard 不会导致 JOC 无可用 renderer。 + +### 方案比较与推荐 + +1. **不改变**:Pixel 继续将 JOC 降级给已知失败的平台 E-AC3 decoder,播放失败。**拒绝**。 +2. **整体重放 `1066f642...`**:fork 已有多 MIME API 主体和 DTS-HD fallback,整体重放会与 `0592f21c...`/`07cc217a...` 产生冲突,且引入 fork 不需要的 transformer/inspector 适配 hunk,扩大回滚面。**拒绝**。 +3. **WebHTV 窄取适配(采用)**:只移植 `supportsEac3JocFallbackDecoding()` 的 Google/非 Google 判断、E-AC3 JOC 分支的 guard 逻辑和 `MediaCodecUtilTest` 两个 JOC case;新增 `import java.util.Objects`。不改 DTS、DV、MV-HEVC 分支,不动 transformer/inspector/DefaultTrackSelector,不改 App renderer 代码。风险是 Google 设备没有原生 JOC decoder 时平台 renderer 更早拒绝,必须验证 `CompatFfmpegAudioRenderer` PCM 软解能接管。 + +推荐方案不新增线程、网络访问、native ABI 或公共 Media3 API(`getAlternativeCodecMimeTypes` 签名不变);合法文件路径保持兼容;极端情况从"选错 decoder 导致播放失败"变为"正确 fallback 到 FFmpeg 软解"。 + +### 产物边界 + +- 只更新 `media3-exoplayer` 的 AAR、sources、module metadata 和校验文件。不更新 `media3-container`、`media3-extractor`、`media3-common` 或其他 Media3 模块。 +- 不更新 nextlib/MPV FFmpeg,不触及 `third_party/fongmi-repositories-lock.json`。 +- patch 排在 `media3-exo-hdr-parser-safety.patch` 之后(build 脚本数组末尾),不改变现有 5 个 patch 的顺序和内容。 + +## 实施计划、验证与用户决策 + +- 单元 A:创建 `third_party/patches/media3-exo-eac3-joc-pixel-guard.patch`,在 `scripts/build_media_deps.sh` patch 数组末尾追加该 patch 名,更新 `third_party/media-lock.json` 的 patch 条目和 `media3-exoplayer` 产物 override。 +- 单元 B:重新构建并发布 `media3-exoplayer` 的 AAR、sources、module metadata 和四类 sidecar,更新 lock SHA-256。 +- 验证:patch `git apply --check` 重放;LF 规范化 SHA-256 与 lock 匹配;JDK 21 下 Media3 `:media3-exoplayer` 定向测试或 Java 编译;随后 App Mobile/Leanback arm64-v8a Debug Java 编译。 +- 未解决风险:真实 Pixel 设备的 JOC 流播放、非 Google 设备的 2D 降级和 FFmpeg PCM fallback 仍需设备/样片验收;Java 编译不代表设备正确性。 +- 用户决策:用户明确批准后实施。本记录将解释为 E3-1a 窄取适配,不批准 E3-1b 或其他未审阅阶段。 + +## 评估检查点 + +### 2026-08-26:E3-1a 本地评估基线建立 + +- 当前分支:`dev2@6312c485f06346bb6205092c1909efa59bae7ac2`;工作树干净。 +- 上游 commit `1066f642...` 的完整 7 文件 diff 已通过 GitHub API 读取并核对。 +- 当前 fork `MediaCodecUtil.java`(从 `media3-exoplayer` sources jar 提取)已确认:多 MIME API 主体存在,E-AC3 JOC 分支缺少 Google guard,无 `import java.util.Objects`。 +- `FfmpegLibrary.getCodecName`(从 nextlib AAR sources 提取)已确认 `AUDIO_E_AC3_JOC` 映射到 `"eac3"`,FFmpeg 软解可接管。 +- `CompatFfmpegAudioRenderer.supportsFormatInternal` 和 `ExoUtil.buildAudioRenderers` 的 renderer 链路已核对。 +- AndroidX Media Issue #3257 已读取,确认 Pixel E-AC3 decoder 不支持 JOC 的产品决策。 +- 决策包已就绪,等待用户批准。 +- checkpoint: E3-1a local assessment baseline complete +- next: wait for user approval before implementation +## 实施检查点 + +### 2026-08-26:E3-1a 实施单元 A 完成(patch、build 脚本、lock) + +- 用户已批准 E3-1a 实施。 +- 创建 `third_party/patches/media3-exo-eac3-joc-pixel-guard.patch`,包含三个 hunk 修改 `MediaCodecUtil.java`(import Objects、JOC guard 分支、`supportsEac3JocFallbackDecoding()` 方法)和两个 hunk 修改 `MediaCodecUtilTest.java`(ShadowBuild import、两个 JOC test case)。 +- patch 在从 sources jar 提取的原始 fork 源码上通过 `git apply --check`;应用后源码验证确认所有修改正确。 +- `scripts/build_media_deps.sh` patch 数组末尾追加 `media3-exo-eac3-joc-pixel-guard.patch`。 +- `third_party/media-lock.json` 添加 patch 条目(SHA-256 `f36790e77d65cd2638c14eb38f23dbdd3125a2aec09acb031fe6baaa06ab7c41`)。`media3-exoplayer` artifact override 待构建后填入。 +- checkpoint: E3-1a unit A patch/script/lock complete +- next: build media3-exoplayer AAR and update lock override SHA-256 + +### 2026-08-27:E3-1a 实施单元 B 完成(AAR 构建与 lock 更新) + +- Media3 源码 clone 成功(`e3e922d5...`),6 个 patch 全部应用成功(含 E3-1a 新 patch)。 +- 构建脚本新增 `apply_media_patch_lf` 函数解决 Windows CRLF patch 兼容问题:`git apply` 在 Windows 无法解析 CRLF 格式 patch 的空行,fallback 到 GNU `patch` 命令自动 strip CR。 +- 使用 `--use-aliyun-mirrors` 和 JDK 21 构建,`BUILD SUCCESSFUL in 7m 3s`,474 个 task 全部执行,16 个 Media3 模块发布到 `third_party/maven`。 +- `media3-exoplayer` AAR SHA-256 `8cebe1b193a9bfe11bab60decf3b71cd593b9fd050a3073c5455e48f722c62d3`,sources SHA-256 `f630c00e913ae7f6720069eb38c3bcf25a7ee3b0dd2312aa7efa0eeddb62c4da`。 +- `third_party/media-lock.json` 添加 `media3-exoplayer` artifact override(reason: E3-1a adds Pixel E-AC3 JOC fallback guard)。 +- 其他 15 个 Media3 模块(common/container/extractor 等)也重新发布了,但 lock 只 override `media3-exoplayer`;其余模块内容与 E2-1 构建的产物一致(未改变其 patch)。 +- checkpoint: E3-1a unit B build and lock override complete +- next: verify patch SHA-256 in lock matches final patch, then commit and tag + +### 2026-08-27:E3-1a 收敛为两个发布原子单元 + +- 构建产生的其他 16 个 Media3 坐标共 385 个旁支文件已确认与本任务无关,并恢复到 `HEAD`;未触碰其他预先存在的脏文件。 +- `media3-exoplayer` 坐标的完整发布内容包含 AAR、sources、Gradle module、POM 校验旁车和 Maven metadata。由于 `upstream` task guard 单元上限为 16 个文件,将其拆为两个连续且可回滚的发布单元:第一单元提交运行时 AAR、sources 及校验文件并连同任务源码/lock;第二单元提交 module、POM 校验旁车和 Maven metadata。 +- 当前 guard 的安全门已恢复,第一单元将包含 14 个文件,第二单元将包含 14 个文件;两单元均保留同一 `media3-exoplayer` 坐标和 SHA-256 一致性。 +- checkpoint: E3-1a side-module outputs excluded and target artifact split bounded +- next: commit first artifact unit with hash and patch validation, then restore and commit metadata unit + +### 2026-08-27:E3-1a 第一发布原子单元验证完成 + +- 第一单元范围为任务文档、构建脚本、lock、E3-1a patch,以及 `media3-exoplayer` 的 AAR、sources 和对应校验旁车,共 14 个文件。 +- `bash -n scripts/build_media_deps.sh` 通过;`git diff --check` 通过。 +- `media-lock.json` 可解析;E3-1a patch SHA-256 为 `f36790e77d65cd2638c14eb38f23dbdd3125a2aec09acb031fe6baaa06ab7c41`,与 lock 一致。 +- AAR 的 SHA-256 为 `8cebe1b193a9bfe11bab60decf3b71cd593b9fd050a3073c5455e48f722c62d3`,sources 的 SHA-256 为 `f630c00e913ae7f6720069eb38c3bcf25a7ee3b0dd2312aa7efa0eeddb62c4da`;MD5/SHA-1/SHA-256/SHA-512 旁车全部匹配,且两项 SHA-256 与 lock override 一致。 +- sources JAR 包含 `androidx/media3/exoplayer/mediacodec/MediaCodecUtil.java`;未运行设备级 Pixel 播放验证,保留为后续设备验收风险。 +- checkpoint: E3-1a first artifact unit validation complete +- next: finish first atomic commit and recovery tag, then restore the metadata unit + +### 2026-08-27:E3-1a 第二发布原子单元换行修正 + +- 恢复第二单元后发现 Windows `core.autocrlf=true` 将 `.module` 工作树内容转换为 CRLF,而其 sidecar 摘要针对发布时的 LF 字节;POM 和 Maven metadata sidecar 与当前字节一致。 +- 已仅将 `media3-exoplayer-1.11.0-alpha01-fongmi.module` 规范为 LF,未修改 AAR、sources、POM、metadata 或任何摘要值。 +- checkpoint: E3-1a metadata newline normalization applied +- next: rerun metadata sidecar and embedded-artifact validation, then commit second atomic unit + +### 2026-08-27:E3-1a 第二发布原子单元验证完成 + +- `media3-exoplayer` module、POM、Maven metadata 的 MD5/SHA-1/SHA-256/SHA-512 旁车全部匹配当前发布文件。 +- module 中 AAR/sources 的文件大小和 SHA-256 与实际产物一致,metadata 包含 `1.11.0-alpha01-fongmi` 版本;`git diff --check` 和 task guard scope 检查通过。 +- checkpoint: E3-1a second artifact unit validation complete +- next: finish second atomic commit and recovery tag, then close E3-1a implementation record + +## 检查点 2026-08-27:E3-1a 实施收尾 + +- 已完成批准的 E3-1a 窄取适配:Google/Pixel 设备不再将 E-AC3 JOC 降级为平台 E-AC3 decoder;非 Google 设备保留既有 2D 降级路径。 +- 第一原子提交:`137fee9817be550391c1ec2054fc24840ad6a4b7`,恢复标签 `recovery/E3-1a-impl/20260826174024-137fee9817be`;包含 patch、build 脚本、lock、AAR/sources 及其校验旁车。 +- 第二原子提交:`4d5127b609558db20d81a9e2f7efa9f38bca2874`,恢复标签 `recovery/E3-1a-impl-metadata/20260826174413-4d5127b60955`;包含 module、POM 校验旁车和 Maven metadata。 +- 构建证据:Media3 1.11.0-alpha01-fongmi 在 JDK 21 下 `BUILD SUCCESSFUL in 7m 3s`,474 个 task 完成;目标 AAR SHA-256 为 `8cebe1b193a9bfe11bab60decf3b71cd593b9fd050a3073c5455e48f722c62d3`,sources SHA-256 为 `f630c00e913ae7f6720069eb38c3bcf25a7ee3b0dd2312aa7efa0eeddb62c4da`。 +- 结构化校验已通过:patch/lock SHA-256、AAR/sources/module/POM/metadata 的 MD5/SHA-1/SHA-256/SHA-512 旁车、module 内嵌产物大小与 SHA-256、sources JAR 中 `MediaCodecUtil.java`、脚本语法和 `git diff --check`。 +- 回滚锚点:实施前 `582fa66e090510b92cbf6630c8745f9afe5de236`;按两个恢复标签逆序回滚可移除 E3-1a 产物和 metadata,不影响 E1、E2-1、E2-2 或 E-SP 系列。 +- 未解决风险:尚未在真实 Pixel/Google 设备上播放 E-AC3 JOC 样片,也尚未完成非 Google 设备 2D 降级与 FFmpeg PCM 接管的实机验收;Java/产物校验不能替代设备行为验证。 +- 下一步:准备 Google/Pixel 与非 Google 设备的 E-AC3 JOC 样片验收,记录 decoder 选择、FFmpeg PCM 接管、播放结果和日志;在验收前不升级为完全发布完成。 diff --git a/docs/E3-1b-exo-dts-14bit.md b/docs/E3-1b-exo-dts-14bit.md new file mode 100644 index 0000000000..35ff161859 --- /dev/null +++ b/docs/E3-1b-exo-dts-14bit.md @@ -0,0 +1,86 @@ +# E3-1b:Exo DTS 14-bit frame-size correction + +- 任务 ID:`E3-1b` +- 所属分类:Exo +- 状态:已实施并完成验证 +- 唯一任务文档:`docs/E3-1b-exo-dts-14bit.md` +- 用户授权:2026-08-26 明确要求开始下一个任务并优先快速完成 +- 实施基线:`recovery/E3-1b-baseline/20260826-9c347cc688c2` +- 上游来源:`FongMi/media@d500eb27ea994ffaa8ea2b48863a0c7aaef0e4b4` + +## Recovery anchor + +- 目标:修正 14-bit DTS core 帧大小的整数换算,避免 DTS-CD WAV、raw DTS 和 TS 中帧边界多算 1 字节,导致后续 sync word 错位和音频损坏。 +- 范围:只移植 `DtsUtil.getDtsFrameSize` 的 14-bit 公式和最小边界测试;不移植上游无关的 `findDtsCoreSync`、WAV 探测或 reader 主体。 +- 接受标准:补丁按现有六个 Media3 patch 后可重放;14-bit BE/LE 与 `FSIZE+1=3585` 测试通过;`lib-extractor` 定向测试和 Java 编译通过;只更新 `media3-extractor` AAR/sources 及 lock;初始 dirty 文件不被覆盖或提交。 +- 当前状态:窄补丁、DtsUtilTest、`lib-extractor` Java 编译、AAR 最小更新和 App 接线编译已完成;实现提交 `27b85eeeed5ceb55e56a67ae3b5cf8ff64b8da40`,恢复标签 `recovery/E3-1b/20260826201735-27b85eeeed5c` 已创建。 +- 下一动作:完成本次修正提交后,开始 E4-1 评估。 + +## 实际能力 + +播放使用 14-bit DTS 编码的音乐 CD WAV、raw DTS 或 TS 时,播放器会正确计算每帧真实占用的物理字节数,连续帧不再因向下取整顺序错误而错位。普通 16-bit DTS 和其他音频格式行为不变。 + +## 证据与设计决策 + +- 评估索引 `docs/upstream-player-dependency-merge-assessment-2026-08-20.md` 第 9.3 节已确认当前 fork 的 WAV 探测、第二音轨和 `DtsReader` 接入已存在,缺口仅为 14-bit frame-size 整数换算。 +- 上游 `d500eb27ea994ffaa8ea2b48863a0c7aaef0e4b4` 将公式从 `fsize * 16 / 14` 改为 `(fsize * 8 / 14) * 2`,先取得完整 14-bit word 数再换算容器字节;`FSIZE+1=3585` 时结果从 4097 修正为 4096。 +- 当前 `DtsUtil.java` 仍使用旧公式;`DtsUtilTest` 只有 DTS:X marker 测试,没有 14-bit frame-size 覆盖。 +- 采用窄适配,不移植上游 `findDtsCoreSync`,因为当前 fork 尚未需要该 API,扩大范围会增加容器和输入探测风险。 + +## 收益、风险与回滚 + +- 收益:修复 14-bit DTS 连续帧边界,避免后续音频静音、噪声或解析失败。 +- 风险:错误的测试样例或公式适配可能影响 14-bit raw DTS/WAV/TS;软件/硬件 decoder 不受影响。变更只增加整数运算,性能和包体积影响可忽略。 +- 兼容性:16-bit DTS、DTS-HD、DTS:X、E-AC3、TrueHD 和现有 extractor 接线不变。 +- 回滚:恢复 E3-1b 实现提交和 `media3-extractor` AAR;必要时回到 `recovery/E3-1b-baseline/20260826-9c347cc688c2`。 + +## 实施记录 + +- 补丁:`third_party/patches/media3-exo-dts-14bit-frame-size.patch`,SHA-256 `328fe823b824fd36e359ea16eea4c77334ea707676e9a2803258f29b661e3d77`。 +- 定向验证:独立 Temurin JDK `21.0.12.1+1`、Gradle 9.1.0、工作区 Gradle 缓存和代理;`:lib-extractor:testDebugUnitTest --tests androidx.media3.extractor.DtsUtilTest :lib-extractor:compileDebugJavaWithJavac`,`BUILD SUCCESSFUL in 7m 45s`。 +- App 接线验证:独立 Temurin JDK `21.0.12.1+1`、`bash gradlew --no-daemon --console=plain :app:compileMobileArm64_v8aDebugJavaWithJavac :app:compileLeanbackArm64_v8aDebugJavaWithJavac`,`BUILD SUCCESSFUL in 4m 56s`。 +- AAR:仅替换既有已验证 `media3-extractor` AAR 内的 `DtsUtil.class`,保留 E-SP2/E2-1 其他 classes;SHA-256 `33109a547e7f27c1110e785ae77e8ab1e9584a24a9f904573ce770129aa4475a`。 +- sources:仅替换 `DtsUtil.java`,SHA-256 `b4d65656b5d56ea8a66580d03178b98dbecac3840791a30820ae184f3d1ca416`。 +- 发布限制:完整 `:lib-extractor:publishReleasePublicationToMavenRepository` 在现有 dirty Media3 checkout 被既有 `MatroskaExtractor.samplesHaveSupplementalData` 静态上下文错误阻塞;未修改受保护 checkout,采用已验证 AAR 的最小 class/source 替换并通过 ZIP、源码和校验文件验证。 + +## 本次直接合并记录 + +- 上游来源:`fish2018/fongmi-sync@27b85eeeed5ceb55e56a67ae3b5cf8ff64b8da40` 与后续记录提交 `d95bfd4df4dc8824ff8ce36e78b2355241654797`。 +- 已接入上游 E3-1b 的 DTS 14-bit 公式、三条边界测试、补丁和 `media3-extractor` AAR/sources;AAR SHA-256 为 `33109a547e7f27c1110e785ae77e8ab1e9584a24a9f904573ce770129aa4475a`,sources SHA-256 为 `b4d65656b5d56ea8a66580d03178b98dbecac3840791a30820ae184f3d1ca416`。 +- 已补齐 extractor Gradle module 中 AAR/sources 的大小、MD5、SHA-1、SHA-256、SHA-512 元数据,并确认每个发布文件的 sidecar 与 module entry 一致。 +- `scripts/build_media_deps.sh` 保留 WebHTV 已验证的 `apply_media_patch_lf()` Windows CRLF fallback,仅为 Media3 patch 调用增加 `--unidiff-zero`,兼容上游零上下文 DTS patch;nextlib 和镜像 patch 的应用路径不变。 +- `third_party/media-lock.json` 已登记 E3-1b patch、extractor 产物和已采用的上游 E3-1a exoplayer 产物 SHA-256。 +- 当前 checkpoint:E3-1b source/config/artifact unit ready; next: commit this verified unit, then create the fongmi-sync two-parent merge commit。 + +## 本次直接合并记录 + +- 上游来源:`fish2018/fongmi-sync@27b85eeeed5ceb55e56a67ae3b5cf8ff64b8da40` 与后续记录提交 `d95bfd4df4dc8824ff8ce36e78b2355241654797`。 +- 采用上游 E3-1b 的 `DtsUtil` 公式、三条边界测试、补丁和 extractor 产物;不引入同分支中无关的 E3-1a 文档覆盖。 +- 构建脚本保留 WebHTV 已验证的 `apply_media_patch_lf()` Windows CRLF fallback,仅让 Media3 patch 调用额外使用 `--unidiff-zero`,以兼容上游零上下文 DTS patch。 +- `third_party/media-lock.json` 已登记 E3-1b patch SHA-256;extractor AAR/sources 与 module 内嵌摘要将在下一单元按实际文件重新核对并更新。 +- 当前 checkpoint:E3-1b source/config unit ready; next: validate and commit source/config unit, then finalize extractor publication metadata。 + +## Checkpoint 2026-08-28: E3-1b publication validation + +- E3-1b publication metadata and artifact validation recorded:补丁与 `third_party/media-lock.json`、extractor AAR/sources、`.module` 内嵌摘要和全部 MD5/SHA-1/SHA-256/SHA-512 sidecar 已按实际文件核对一致;构建脚本语法检查通过。 +- 验证记录:`media3-extractor` AAR SHA-256 为 `33109a547e7f27c1110e785ae77e8ab1e9584a24a9f904573ce770129aa4475a`,sources SHA-256 为 `b4d65656b5d56ea8a66580d03178b98dbecac3840791a30820ae184f3d1ca416`,patch SHA-256 为 `328fe823b824fd36e359ea16eea4c77334ea707676e9a2803258f29b661e3d77`。 +- Workspace:`dev2@c10670e2df54553229b8303f35e01ac2b9d247a6`;范围外无预先脏路径,E3-1b 任务文件均待本次原子提交。 +- Rollback anchor:`recovery/E3-1b-baseline/20260826-9c347cc688c2`;回滚时恢复 E3-1b 实现提交及 `media3-extractor` AAR/来源产物。 +- Next action:commit the verified E3-1b unit。 + +## Checkpoint 2026-08-28: E3-1b implementation closeout + +- E3-1b 原子提交:`b75ba0a5ca6e3ecf2e494f308c0296496c5a2332`;恢复标签:`recovery/fongmi-sync-e3-1b-dts/20260828010623-b75ba0a5ca6e`。 +- 本地提交包含补丁、构建脚本、lock、`media3-extractor` AAR/sources、module 元数据及 sidecar;module 内嵌摘要按实际 artifact 重新生成并通过定向校验。 +- `fish2018/fongmi-sync` 当前完整头为 `cafd4f69e613a5db49df5e38e762b6bf4fe58819`。三方预演的 `-X theirs` 目标树会删除本任务文档并回退已验证的 module 摘要和 Windows patch fallback,因此不采用该目标树。 +- 合并边界:保留当前 WebHTV 验证树,以 `fish2018/fongmi-sync` 作为真实双亲提交的第二父;不以合并动作重新覆盖已验证产物,也不引入上游未批准的其他功能树。 +- 双亲合并提交:`130eac99f735f47284106621bad4795281724786`;父提交为本地 `1cf029bc77f791f8b6b992a004704f1d93e8fa82` 与上游 `cafd4f69e613a5db49df5e38e762b6bf4fe58819`。 +- 合并恢复标签:`recovery/fongmi-sync-merge-closeout/20260828013239-130eac99f735`。 +- Next action:E3-1b closeout complete; proceed to E4-1 assessment。 + +- Merge closeout preparation:将以 `fish2018/fongmi-sync@cafd4f69e613a5db49df5e38e762b6bf4fe58819` 为第二父创建 `ours` 双亲提交;当前验证树保持不变。 + +## Checkpoint 2026-08-28: E3-1b merge completed + +- 双亲提交 `130eac99f735f47284106621bad4795281724786` 已创建并打恢复标签;相对第一父仅增加本合并准备记录,关键功能、lock 和 artifact 树保持已验证状态。 +- Next action:E3-1b closeout complete; proceed to E4-1 assessment。 diff --git a/docs/E4-1-exo-subtitle-byte-safety.md b/docs/E4-1-exo-subtitle-byte-safety.md new file mode 100644 index 0000000000..73b391a795 --- /dev/null +++ b/docs/E4-1-exo-subtitle-byte-safety.md @@ -0,0 +1,66 @@ +# E4-1 Exo 字幕字节与边界安全 + +## Recovery anchor + +- 目标:在不改变 WebHTV 当前 raw bitmap 字幕和默认关闭 extraction 策略的前提下,修复文本字幕有效长度、字符集白名单和 TTML XML 声明处理。 +- 状态:A4-1a/A4-1b 已通过定向测试、干净重放、两个模块发布校验和 App 接线编译;实现已提交并创建 recovery tag,文档闭环待提交。 +- 基线:`cafd4f69e613a5db49df5e38e762b6bf4fe58819`;恢复 tag `recovery/E4-1/baseline-20260826210500-cafd4f69e6`。 +- 上游来源:`FongMi/media@d82fb7b9c93fa2ca0331d3ad455f5805aef47d37`;当前 fork 部分实现 `63531ddcd508b646e0cf515df3bb6caf4835120e`。 +- 保护:`AGENTS.md`、`.codex/scripts/task_guard.sh`、`docs/agents-md-effective-constraints-review-2026-08-21.md` 及所有其他初始脏路径不修改、不提交。 +- 实现提交:`9018f2b5c2b132644cde3841f33fe306209d2499`(`Exo: harden subtitle byte and charset handling`)。 +- 实现恢复 tag:`recovery/E4-1/20260827074736-9018f2b5c2b1`。 +- 下一步:完成本文件与总评估索引的文档闭环提交;不重复发布 AAR/sources,不修改受保护脏路径。 + +## 决策与范围 + +用户已批准只实施 A4-1a 和 A4-1b: + +- A4-1a:`DelegatingSubtitleDecoder` 只对白名单文本 MIME 探测,严格使用有效 `length`,非 UTF-8 TTML 转码后同步 XML encoding 声明。 +- A4-1b:`SubtitleExtractor` 使用有效 `bytesRead`,接收源 MIME 判断是否探测,并同步 TTML 声明;`DefaultMediaSourceFactory` 传递源 MIME。 +- 不实施 A4-1c/A4-1d:不新增 extraction-safe factory,不改变当前 `parseSubtitlesDuringExtraction=false`、`textTrackTranscodingEnabled=false` 默认策略,不启用全量字幕 extraction。 + +## 保留的项目契约 + +- PGS/VobSub/DVB/TX3G/MP4VTT 等非纯文本字幕不进入通用字符集探测,原始字节保持不变。 +- `TextRenderer.legacyDecodingEnabled=true` 保留,外挂和容器 raw subtitle 继续在 renderer 阶段解析。 +- 不修改 FFmpeg、MPV、libplacebo、JNI、字幕 UI 或 App 公共 API。 +- Media3 变更通过补丁和锁定 AAR/sources 交付,隔离 checkout 本身不作为仓库文件提交。 + +## 实施记录 + +### A4-1a/A4-1b:已实现并验证 + +- 补丁:`third_party/patches/media3-exo-subtitle-byte-safety.patch` +- 隔离 checkout:`/private/tmp/e41-media-clean`,基于 `e3e922d5c01bc0b564849940fe589daf37360d15` 顺序重放现有 7 个补丁后实施;未修改主仓库中预存脏的 `third_party/sources/media`。 +- 生产改动:`DelegatingSubtitleDecoder` 和 `SubtitleExtractor` 严格按有效字节长度探测/转码;`SubtitleDecoderFactory` 仅允许 SSA/WebVTT/SubRip/TTML;`DefaultMediaSourceFactory` 向 whole-file extractor 传递源 MIME;TTML 转码后同步 XML encoding;未知或不支持字符集保留原始字节而不抛异常。 +- 测试改动:新增 render-time 有效长度、GB18030、TTML declaration、二进制直通覆盖;扩展 extractor 未知长度/partial read、非 UTF-8 和 TX3G 直通覆盖。 +- 受影响模块:`media3-exoplayer`、`media3-extractor`。 +- 验收:非 UTF-8 SSA/SRT/VTT/TTML、缓冲区容量大于有效长度、未知长度非 1024 整数倍、二进制字幕不探测、TTML declaration 更新、UTF-8/BOM/UTF-16 回归。 + +### 验证检查点:2026-08-27 + +- `git diff --check`:隔离 checkout 通过。 +- JDK:`21.0.12.1`,Gradle `9.1.0`。 +- `:lib-exoplayer:compileDebugJavaWithJavac`:通过。 +- `:lib-extractor:compileDebugJavaWithJavac`:通过。 +- `:lib-exoplayer:testDebugUnitTest --tests androidx.media3.exoplayer.text.DelegatingSubtitleDecoderCharsetTest`:在沙箱外通过。 +- `:lib-extractor:testDebugUnitTest --tests androidx.media3.extractor.text.SubtitleExtractorTest`:在沙箱外通过。 +- 补强 A4-1b 的非 UTF-8 TTML whole-file declaration 用例后,单独重跑同一 `SubtitleExtractorTest`,`BUILD SUCCESSFUL in 51s`。 +- 首次受限沙箱测试未进入断言即因 Robolectric 无法创建 `/Users/macbookpro/.robolectric-download-lock` 失败;未发现代码或测试失败,重跑时使用同一命令、JDK 21 和 `-Pkotlin.compiler.execution.strategy=in-process`,仅申请了用户批准的沙箱外权限。 +- 正式补丁:`third_party/patches/media3-exo-subtitle-byte-safety.patch`,SHA-256 `8ed566a26b70609262d6c49ada2e8912997f36d75a166825e368182b5b7f35bf`;仅含 4 个生产文件和 2 个测试文件。 +- 干净重放:新 worktree `/private/tmp/e41-media-replay` 从 `e3e922d5c01bc0b564849940fe589daf37360d15` 顺序应用 8 个锁定补丁,全部 `git apply --check` 和 `git diff --check` 通过;6 个 E4-1 文件与已测试树逐字节一致。 +- 定向发布:仅执行 `:lib-exoplayer:publishReleasePublicationToMavenRepository` 和 `:lib-extractor:publishReleasePublicationToMavenRepository`,`BUILD SUCCESSFUL in 1m 58s`;未发布其他 Media3 模块,未安装根级 Maven metadata。 +- `media3-exoplayer` AAR SHA-256:`8f34ea1a6c2951c4ed4f033144e38e9e0616443a7a05fa488e5525ca47084c3f`;sources SHA-256:`71f9bee851acf22e7a63b91347b03a4966c1b9cc23958672b3da091cab3f32c6`。 +- `media3-extractor` AAR SHA-256:`14811712a342517841cf2087d8316f4458f15df2ab1688fb795570a33351f47d`;sources SHA-256:`818c7917af9cb3b4e090f14d085e91482d2b8cfef9a1d592a781d106c9e0af64`。 +- 产物内容对比:两个 AAR 的非 class 内容不变;Exo 仅 3 个修改源码对应的外部/内部 class 变化,Extractor 仅 `SubtitleExtractor` 及其内部 `Sample` class 变化;sources 仅 3 个 Exo 和 1 个 Extractor 生产文件变化;POM 内容不变,module 仅同步新 artifact 大小和哈希。 +- App 接线:JDK 21、Gradle 9.5.1,`bash ./gradlew --no-daemon --console=plain -Pkotlin.compiler.execution.strategy=in-process :app:compileMobileArm64_v8aDebugJavaWithJavac :app:compileLeanbackArm64_v8aDebugJavaWithJavac`,`BUILD SUCCESSFUL in 4m 4s`。 +- 契约审计:`parseSubtitlesDuringExtraction=false`、`textTrackTranscodingEnabled=false` 和 `TextRenderer.legacyDecodingEnabled=true` 保持;补丁不包含 extraction-safe factory、HLS/DASH/SS/chunk 默认接线或字幕 UI 改动。 +- 扩展回归审计:5 组既有 decoder 测试共 63 条;2 条 SSA `Cue.lineType` 旧期望在仅前 7 个补丁的精确基线中同样失败,确认为预存测试漂移;TX3G UTF-16LE 失败也在该基线中复现。未知 MIME 的两参数构造保持默认不探测,运行时 factory 仍按 MIME 白名单显式开启文本探测,避免把 TX3G/MP4VTT 等二进制 payload 交给 detector。 + +## 回滚 + +优先回滚本任务提交,恢复到基线 tag `recovery/E4-1/baseline-20260826210500-cafd4f69e6`;若仅 AAR 校验或运行测试失败,删除本任务补丁和对应 artifact override,保留 E1/E2/E3 及既有 Media3 补丁链。 + +## 验证与剩余风险 + +已完成补丁、单元测试、模块编译、干净重放、定向发布、产物内容对比和 App 接线编译。字符集探测本身仍是统计判断,极短或高度含糊的文本可能无法识别,此时保留原始字节;二进制字幕已由 MIME 白名单隔离。默认 extraction 开关、外挂 bitmap 路由和 HLS/DASH segmented extraction 不在本次实施范围,A4-1c/A4-1d 仍需独立批准;本阶段不以实机字幕 UI 截图替代后续 A4-J 联合验收。 diff --git a/docs/E4-J1-exo-cue-data-contract.md b/docs/E4-J1-exo-cue-data-contract.md new file mode 100644 index 0000000000..614c1cad01 --- /dev/null +++ b/docs/E4-J1-exo-cue-data-contract.md @@ -0,0 +1,114 @@ +# E4-J1 Exo Cue 数据契约 + +## Recovery anchor + +- 目标:为 Exo 字幕增加 `collisionAvoidance`、`textRegionHeight` 和 `LetterSpacingSpan` 的完整数据契约,但不启用新的碰撞、viewport 或字号行为。 +- 状态:已实施并完成验证;实现提交 `af78e3b7656d6a0f210d7344b3852f301690c417`;恢复 tag `recovery/E4-J1/20260827133106-af78e3b7656d`。 +- 分支/HEAD:`fongmi-sync` / `a20a31a7c6be2454459db68ec41b7cebf824d1a6`。 +- 上游来源:`FongMi/media@6794d75b7a39db42dcfcab18c915f0da165515b5`(ASS collision 数据契约);`FongMi/media@3c2cbe8ac742c2fe15eff52f03eeb3b1b648848d`(TTML region/spacing 数据契约)。 +- 当前 fork:`e3e922d5c01bc0b564849940fe589daf37360d15`;已有基础 `4db2ca63351a4abaf0daf3c1a65913b846215ab9`、`55fe0481b9429d3a12f6b42ed1945cd12cc88c9c`、`56fd27d919504bfebd78172acb99cf7e3bc8f490`、`9d7ea02aae18e03db0407e2146b50908acece81c`。 +- 保护:`AGENTS.md`、`.codex/scripts/task_guard.sh`、`docs/agents-md-effective-constraints-review-2026-08-21.md` 和所有其他初始脏路径不修改、不提交;尤其不触碰主仓库 `third_party/sources/media`。 +- 接受标准:新字段默认值与旧 Bundle 兼容;Builder、`buildUpon()`、`equals/hashCode`、Serializable/Binder Bundle 和 custom span 往返完整;现有 z-index、bitmapHeight、字幕位置、parser-side stacking、字号策略和 extraction 开关不变。 + +## 决策与范围 + +用户已批准实施 E4-J1。采用 WebHTV 窄化方案: + +- 移植 `Cue.collisionAvoidance`、`Cue.textRegionHeight`、`LetterSpacingSpan` 及其完整序列化/复制/比较支持。 +- 保留现有 `Cue.zIndex`、`Cue.bitmapHeight`、App 字号/位置控制和 fork SSA `applyStacking()`。 +- 不移植 ASS `Collisions: Reverse` parser 行为、TTML parser layout、Canvas collision、`PlayerView` viewport、bitmap scaling、WebView parity 或任何 extraction 开关。 +- `collisionAvoidance` 默认 `NONE`,`textRegionHeight` 默认 `Cue.DIMEN_UNSET`;本阶段不由现有 parser 产生 `UP/DOWN`。 + +### 研究与证据 + +| 证据 | 来源/修订 | 结论与决策影响 | +| --- | --- | --- | +| 上游实现与测试 | `FongMi/media@6794d75b7a39db42dcfcab18c915f0da165515b5`;评估索引检查点 11、16 | `collisionAvoidance` 必须进入 Cue 构造、`buildUpon()`、equals/hashCode 和 Bundle;不能整体 cherry-pick,因 fork 已有 parser-side stacking。 | +| 上游实现与测试 | `FongMi/media@3c2cbe8ac742c2fe15eff52f03eeb3b1b648848d`;评估索引检查点 13、16 | `textRegionHeight` 和 `LetterSpacingSpan` 是 TTML layout 的跨模块数据;本阶段只保留字段和 span 往返,不伪造 Format 画布尺寸或启用缩放。 | +| 当前 fork 源码 | `third_party/sources/media` 已发布基线 `e3e922d5c01bc0b564849940fe589daf37360d15`;`Cue.java`、`CustomSpanBundler.java`、SSA parser | 已有 `zIndex`/`bitmapHeight`,缺少三个新契约;SSA 已有 `applyStacking()`,因此不能同时打开 Canvas collision。 | +| 当前 App 消费 | `app/src/main/java/com/fongmi/android/tv/player/exo/ExoUtil.java`、`SubtitleDialog.java`、`PlayerManager.java` | App 明确关闭 embedded font sizes 并提供字号/位置设置;本阶段不改变这些调用和 UI 行为。 | +| 平台/项目规范 | AndroidX Media Bundleable/Cue serialization、Media3 player gates;见 `.codex/skills/upstream-integration-governor/references/` | 新字段必须向后兼容旧 Bundle,并在 AAR、sources、锁和应用编译链中保持一致。 | + +### 方案比较 + +1. 不改:没有新的 Cue 字段,后续 ASS/TTML 阶段无法安全传递策略和区域信息。 +2. 直接采用上游:会把 parser、Canvas、viewport 和字号行为一起带入,覆盖或叠加 WebHTV 既有 stacking,风险超出本阶段。 +3. WebHTV 窄化方案(采用):只引入可独立验证的数据契约和 span 序列化,默认不改变用户可见行为;后续行为阶段再单独审批。 + +## 计划实施文件 + +- `third_party/patches/media3-exo-cue-data-contract.patch` +- `scripts/build_media_deps.sh` +- `third_party/media-lock.json` +- `third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/` +- 本文档与 `docs/upstream-player-dependency-merge-assessment-2026-08-20.md` + +补丁只允许包含 Media3 common 的 Cue/custom-span 生产文件及对应测试文件;不包含 extractor/ui/App 源码。 + +## 验证、回滚与状态 + +- 首先运行 common 的 Cue/Bundle/custom-span 定向测试和 common 编译,再编译 extractor、ui 及 Mobile/Leanback arm64 App Java 接线。 +- 核对 AAR、sources、module、sidecar、锁文件和补丁 SHA-256;确认非 class 内容及既有 `zIndex`/`bitmapHeight` 行为不变。 +- 回滚锚点:`recovery/E4-J1/baseline-20260827102011-a20a31a7c6`;失败时只移除本任务补丁与 common artifact override,不触碰 E4-1 及其它阶段。 +- 当前下一步:开始下一项 Exo 候选的只读评估;不得把 E4-J2/E4-2/E4-4 行为并入本任务。 + +## Checkpoint 1:2026-08-27 补丁链恢复 + +- 完成:在 `/private/tmp/e4j1-media-clean` 从 `e3e922d5c01bc0b564849940fe589daf37360d15` 按 `scripts/build_media_deps.sh` 顺序重放 `media3-danmaku-live`、`media3-dolby-vision-matroska`、`media3-upstream-playback-fixes-2026-08`、`media3-deferred-cues`、`media3-exo-hdr-parser-safety`、`media3-exo-pixel-eac3-joc-guard`、`media3-exo-dts-14bit-frame-size`、`media3-exo-subtitle-byte-safety`,全部 `--check` 和应用成功。 +- 诊断结论:此前第 5 个补丁的失败来自对未按顺序应用的树做独立检查;在正确前序补丁上下文中 E2-1 补丁可重放,不需要修改既有补丁或使用三方合并。 +- 主仓库:`fongmi-sync` / `a20a31a7c6be2454459db68ec41b7cebf824d1a6`;预存脏路径保持不变,未触碰 `third_party/sources/media`。 +- 验证:8 个补丁应用成功;clean checkout 当前仅包含预期 Media3 补丁改动。 +- 未解决:E4-J1 common 数据模型尚未移植,AAR/lock 尚未更新。 +- 回滚锚点:`recovery/E4-J1/baseline-20260827102011-a20a31a7c6`。 +- 下一动作:读取 clean checkout 中 `Cue`/`CustomSpanBundler` 及上游 E4-J1 来源,实施字段和序列化测试。 + +## Checkpoint 2:2026-08-27 Cue 契约移植与验证环境 + +- 完成:clean checkout 已恢复 8 个既有 Media3 补丁;已移植 `Cue.collisionAvoidance`、`Cue.textRegionHeight`、`LetterSpacingSpan` 及 `CustomSpanBundler` 支持,并新增默认值、Builder、Bundle/Binder round-trip 与 custom span 测试。 +- 源码范围:仅 common 的 `Cue.java`、`CustomSpanBundler.java`、新增 `LetterSpacingSpan.java` 及对应两组测试;未修改 parser、renderer、UI、App 或 MPV。 +- 工作区:主仓库 `fongmi-sync` / `a20a31a7c6be2454459db68ec41b7cebf824d1a6`,预存脏路径未变;实现仍只在 `/private/tmp/e4j1-media-clean`。 +- 验证:`git diff --check` 通过;首次 `JAVA_HOME=/usr/local/opt/openjdk@21/libexec/openjdk.jdk/Contents/Home ./gradlew :lib-common:testDebugUnitTest ...` 未进入编译,因沙箱禁止访问 `/Users/macbookpro/.gradle/wrapper/dists/.../gradle-9.1.0-all.zip.lck`(环境权限问题)。放权后复用原缓存的构建又被残留 Gradle 输出目录阻断;改用隔离缓存后已越过权限点,但首次缓存生成在 build-logic 阶段因磁盘只余约 `1.8 GiB`、新缓存占 `661 MiB` 而 `No space left on device`,尚未进入 E4-J1 源码编译。 +- 未解决:common 定向测试/编译、补丁生成、AAR/lock 更新尚未完成。 +- 回滚锚点:`recovery/E4-J1/baseline-20260827102011-a20a31a7c6`。 +- 下一动作:删除仅属于本任务的失败隔离缓存/生成目录,复用已有 Gradle 依赖缓存重跑同一 JDK 21 定向 common 测试与编译。 + +## Checkpoint 3:2026-08-27 common 定向验证通过 + +- 环境固定:按用户提供的 `https_proxy=http://127.0.0.1:7896`、`http_proxy=http://127.0.0.1:7896` 完成 Gradle 9.1.0 下载;发行包固定在 `/Users/macbookpro/.gradle/wrapper/dists/gradle-9.1.0-all/7wzd0jkjit61aq2p43wpjgij9/`,后续 Media3 构建复用该持久缓存,不再使用会被清理的临时 Gradle home。 +- 验证命令:JDK 21、`JAVA_TOOL_OPTIONS=-Djava.io.tmpdir=/private/tmp/e4j1-robo` 下运行 `./gradlew :lib-common:testDebugUnitTest --tests androidx.media3.common.text.CueTest --tests androidx.media3.common.text.CustomCueBundlerTest :lib-common:compileDebugJavaWithJavac --no-daemon`。 +- 结果:`BUILD SUCCESSFUL in 7m 1s`,205 个任务中 27 executed、178 up-to-date;`CueTest` 和 `CustomCueBundlerTest` 全部通过,common 主源码与测试源码编译通过。 +- 兼容结论:`collisionAvoidance` 默认 `NONE`、`textRegionHeight` 默认 `DIMEN_UNSET`;旧 Bundle 缺字段仍使用默认值;Binder/Serializable/deprecated Bundle 和 pixel/em `LetterSpacingSpan` 往返均有测试覆盖。 +- 未解决:增量 patch、common AAR/sources/sidecars、lock、App 接线编译尚未完成。 +- 回滚锚点:`recovery/E4-J1/baseline-20260827102011-a20a31a7c6`。 +- 下一动作:生成 E4-J1 独立 patch,并从同一 clean checkout 发布 `media3-common` AAR/sources。 + +## Checkpoint 4:2026-08-27 独立补丁与重放 + +- 补丁:`third_party/patches/media3-exo-cue-data-contract.patch`,SHA-256 `a6389e0c34a9a3e895072f84c9ffd13d0c883c5909d8887873717c337066eb61`;包含 common 的 `Cue`、`CustomSpanBundler`、新增 `LetterSpacingSpan` 和三组测试文件。 +- 顺序:已在 `scripts/build_media_deps.sh` 的 Media3 补丁列表末尾加入 E4-J1,位于 E4-1 字幕 byte/charset safety 之后。 +- 独立重放:在 `/private/tmp/e4j1-replay` 从 `e3e922d5c01bc0b564849940fe589daf37360d15` 依序应用 8 个既有补丁和 E4-J1,共 9 个补丁;每项 `git apply --check --unidiff-zero` 与应用均成功,最终 `git diff --check` 通过。 +- 范围确认:E4-J1 补丁只触及 common 的 3 个生产文件和 3 个测试文件;没有 parser、renderer、UI、App、MPV 或 native 变更。 +- 未解决:`media3-common` 发布物、lock、App 接线编译、最终提交/tag 尚未完成。 +- 回滚锚点:`recovery/E4-J1/baseline-20260827102011-a20a31a7c6`。 +- 下一动作:用 JDK 21、固定 Gradle 9.1.0 缓存和 7896 代理,仅发布 `lib-common` 到临时 Maven 目录。 + +## Checkpoint 5:2026-08-27 common 产物发布 + +- 发布:clean checkout 的 `:lib-common:publishReleasePublicationToMavenRepository` 成功,`BUILD SUCCESSFUL in 44s`;发布目录仅包含 `androidx/media3/media3-common/1.11.0-alpha01-fongmi`。 +- 产物:AAR SHA-256 `5a4815ab415c0650bc8adaa60e518f32df548ddcfafb43e02381281a96dac6e5`;sources SHA-256 `31c38835a729f422ba25835733aa94ac23d8fe6445df2d725a71e46a11d86bfc`;module SHA-256 `e1bc887749ab6b69b1f8d5b56a129f5e2d6618f31ebe3db2a841b352b9f24c87`;POM SHA-256 `c5aff59e17d032f665ff55d26540fee65b8b0e843b834cea4d371c3cc7163f44`。 +- 内容检查:AAR classes.jar 与 sources.jar 均包含 `Cue`、`CustomSpanBundler`、`LetterSpacingSpan`;module/POM 仅有预期产物大小/哈希变化。 +- 锁定:`third_party/media-lock.json` 已登记 E4-J1 patch SHA-256 `a6389e0c34a9a3e895072f84c9ffd13d0c883c5909d8887873717c337066eb61` 及 common AAR/sources 哈希。 +- 未解决:App Mobile/Leanback arm64 Java 接线编译、最终文档状态、原子提交/tag 尚未完成。 +- 回滚锚点:`recovery/E4-J1/baseline-20260827102011-a20a31a7c6`。 +- 下一动作:运行 Mobile/Leanback arm64-v8a Debug Java 编译,确认 App 对 common AAR 的间接兼容。 + +## Checkpoint 6:2026-08-27 接线验证与实施完成 + +- App 接线:JDK 21 下运行 `:app:compileMobileArm64_v8aDebugJavaWithJavac` 与 `:app:compileLeanbackArm64_v8aDebugJavaWithJavac`,`BUILD SUCCESSFUL in 1m 25s`。 +- Media3 直接消费者:在完整九补丁重放树中运行 `:lib-extractor:compileDebugJavaWithJavac` 与 `:lib-ui:compileDebugJavaWithJavac`,`BUILD SUCCESSFUL in 56s`;90 个任务中 23 executed、67 up-to-date。 +- Common 验证:`CueTest`、`CustomCueBundlerTest`、`LetterSpacingSpanTest`、`:lib-common:compileDebugJavaWithJavac` 通过;`media3-common` 单模块发布 `BUILD SUCCESSFUL in 44s`。 +- 最终产物:补丁 SHA-256 `a6389e0c34a9a3e895072f84c9ffd13d0c883c5909d8887873717c337066eb61`;AAR `5a4815ab415c0650bc8adaa60e518f32df548ddcfafb43e02381281a96dac6e5`;sources `31c38835a729f422ba25835733aa94ac23d8fe6445df2d725a71e46a11d86bfc`;module `e1bc887749ab6b69b1f8d5b56a129f5e2d6618f31ebe3db2a841b352b9f24c87`;POM `c5aff59e17d032f665ff55d26540fee65b8b0e843b834cea4d371c3cc7163f44`。 +- 实施结论:E4-J1 数据契约已实现并验证;新字段保持默认无行为,因此现有字幕位置、字号、SSA stacking、Canvas/WebView 渲染和 extraction 开关不变。ASS/TTML 可见行为仍属于后续独立任务。 +- 剩余风险:本阶段没有启用新 parser 或 renderer 行为,未做字幕截图/实机视觉验收;该验证应在后续 E4-J2/E4-2/E4-4 行为阶段按样片执行,不阻塞本数据契约阶段。 +- 实现提交:`af78e3b7656d6a0f210d7344b3852f301690c417`;恢复 tag:`recovery/E4-J1/20260827133106-af78e3b7656d`。 +- 下一动作:开始下一项 Exo 候选的只读评估;E4-J2/E4-2/E4-4 仍需单独决策和批准。 diff --git a/docs/E6-1-exo-smb-proxy-cache-correctness.md b/docs/E6-1-exo-smb-proxy-cache-correctness.md new file mode 100644 index 0000000000..a8f32d3fd0 --- /dev/null +++ b/docs/E6-1-exo-smb-proxy-cache-correctness.md @@ -0,0 +1,68 @@ +# E6-1 Exo 有界缓存写入修复 + +## Recovery anchor + +- 目标:让 Exo 预缓存严格遵守 `DataSpec.length`,避免 Range 被服务器/代理忽略时继续下载整个文件。 +- 状态:已实施、验证并提交;实现 commit `0a8ed3b910679a08a7e41c735338c3804a2eb938`,恢复 tag `recovery/E6-1/20260827145043-0a8ed3b91067`。 +- 分支/HEAD:`fongmi-sync` / `c67b1498a2d5fcbb3152d7199e2af19a9f3544a0`。 +- 来源:`FongMi/media@dd00f94b58b7324ab29febb0b50f3a190d544a3b`;父提交 `FongMi/media@32c20a091ba6e5fd09e13e67df3149326232eda5` 的 SMB/proxy 主体已由当前 fork 覆盖,不重复移植。 +- 保护:`AGENTS.md`、`.codex/scripts/task_guard.sh`、`docs/agents-md-effective-constraints-review-2026-08-21.md`、`third_party/sources/media` 既有脏改动不修改、不提交。 + +## 决策与范围 + +用户已批准实施。采用窄适配:只移植上游 `CacheWriter` 的 `long` 计数、bounded `read` 和 end-position 修复,并补齐当前项目缺少的边界测试;不引入同一上游提交中的 progressive 并行下载、`DiskPreloadManager`、priority manager setter 或 E6-2 factory/cancel 行为。 + +### 实际能力 + +当播放网盘直链或本地代理只请求视频的一小段进行预缓存,而服务端错误返回整段/整个文件时,缓存写入会在请求长度处停止,不会制造无界下载、重叠缓存或额外磁盘占用。未知长度请求仍会正常读到 EOF。 + +### 当前项目已有实现与缺口 + +- `app/src/main/java/com/fongmi/android/tv/player/exo/PreCache.java` 通过 `PreCacheHelper` → `ProgressiveDownloader` → `CacheWriter` 写入共享 `SimpleCache`,因此该修复实际可达。 +- `PreCache` 已有播放优先级、缓存水位、代理 circuit breaker、内存/网络/电量/温度策略;本任务不改变这些策略。 +- 当前发布的 `media3-datasource` `CacheWriter` 仍以 `int totalBytesRead` 统计,并在 bounded 请求时持续读到 EOF;确认没有被近期 WebHTV 提交等价覆盖。 +- WebHTV 提交 `2a2af0c218bc7dee871b9a7d4f25f808420214d2` 只限制预加载范围生成,不能修复底层数据源忽略长度的问题。 + +### 方案比较 + +1. 不变:保留服务器/代理忽略 Range 时的无界读取风险。 +2. 原样合并 `dd00f94...`:会额外引入并行下载和新 manager,与当前 `PreCache` 策略重叠,范围过大。 +3. WebHTV 窄适配(采用):只修 `CacheWriter` 并补测,保持单线程、现有 priority 所有权和所有播放器策略不变。 + +## 收益、风险与兼容性 + +- 收益:减少无效网络流量、磁盘写入和缓存区间重叠;大文件计数不溢出。 +- 风险:边界 off-by-one、未知长度误截断、提前 EOF/取消/重试状态处理错误。 +- 兼容性:普通前台播放、SMB、`proxy://`、MPV、字幕、解码器、native ABI 和公共 API 不变;仅影响 Media3 cache writer 的读取终止条件。 +- 性能/包体积:减少错误 Range 场景的读取和写入;正常场景增加一次长度计算,AAR 增量可忽略。 +- 最佳实践:是,缓存层必须尊重调用者声明的长度,并使用 `long` 表示累计字节。 +- 回滚:恢复本任务提交/tag,或只回滚 `media3-datasource` AAR、补丁和 lock;不触碰 E4/J1、MPV/native 和受保护脏路径。 + +## 验收标准 + +- 九个既有 Media3 补丁后追加 E6-1 补丁可重复 `git apply --check/apply`。 +- `CacheWriterTest` 覆盖 bounded 请求、Range 被忽略返回 200、未知/已知长度、提前 EOF、部分缓存、取消/重试及 long 计数边界。 +- `:lib-datasource:testDebugUnitTest`、`:lib-datasource:compileDebugJavaWithJavac`、单模块发布、`:lib-exoplayer:compileDebugJavaWithJavac` 和 Mobile/Leanback arm64 Java 编译通过。 +- AAR、sources、patch 和 lock SHA-256 一致;不更新 nextlib/FFmpeg/MPV/native。 + +## 实施记录 + +### 2026-08-27:实施启动 + +- 已创建基线 tag `recovery/E6-1/baseline-202608271355-c67b1498a2d5`。 +- 已启动 task guard `E6-1`,范围限定为本文件、评估索引、构建脚本、Media3 datasource 补丁/产物和 lock。 +- 在隔离 checkout `/private/tmp/e61-media-202608271402` 从 Media3 基线 `e3e922d5c01bc0b564849940fe589daf37360d15` 依序重放 9 个既有补丁和 E6-1;全部 `git apply --check/apply` 及 `git diff --check` 通过。 +- 使用 JDK 21、代理 `127.0.0.1:7896` 和持久 Gradle 缓存,在同一 Gradle 进程执行 `:lib-datasource:testDebugUnitTest --tests androidx.media3.datasource.cache.CacheWriterTest`、`:lib-datasource:compileDebugJavaWithJavac`、`:lib-datasource:publishReleasePublicationToMavenRepository`、`:lib-exoplayer:compileDebugJavaWithJavac`,结果 `BUILD SUCCESSFUL in 3m 45s`,249 个任务执行成功。 +- 已将 datasource publication 安装到 `third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/`: + - AAR SHA-256:`ce5c9919bcfe611ecc9de5c4d40c0baa94f2e5858bebc54431c400a90fc37b18` + - sources JAR SHA-256:`4ac57076178a78996a4ab9ffe4466d28db71d804f735d179b9d8cbdf3d2325e7` + - Gradle module SHA-256:`b2492a158f300145c2cbafef2f76becdca3740a9645b7bbd37338774c9620d64` + - POM SHA-256:`b51078a1e63db36711db979356929957a716a01441c182cd772e2b02620a1d52` +- 补丁 SHA-256:`1b591c618fdbba91b0880284126ac8bd5c55f6fe6532187d891b4225a87cc200`;已写入构建顺序和 `third_party/media-lock.json`。 +- App 消费路径:使用 JDK 21、固定用户级 Gradle 缓存和 `127.0.0.1:7896` 代理,执行 `bash ./gradlew --no-daemon --console=plain -Pkotlin.compiler.execution.strategy=in-process :app:compileMobileArm64_v8aDebugJavaWithJavac :app:compileLeanbackArm64_v8aDebugJavaWithJavac`,结果 `BUILD SUCCESSFUL in 38s`;两个产品路径均实际重新执行 Java 编译。直接 `./gradlew` 因仓库 launcher 未设置可执行位而未进入 Gradle,改用等价的 `bash ./gradlew` 后成功,不属于代码或依赖失败。 +- 验收结论:补丁重放、精确失败模式单测、datasource 编译/发布、Exoplayer 编译、产物/lock 哈希以及 Mobile/Leanback arm64 App 编译全部通过;未改变 MPV、FFmpeg、nextlib、native、公共 API 或现有预缓存策略。 +- 剩余风险:未做实机网络流量抓包;定向测试已经精确模拟 Range 长度被忽略、数据源返回完整资源的故障,并确认缓存严格停止在请求的 20 字节处,因此不把实机抓包作为本窄修复的提交门槛。 +- 回滚:回退本任务原子提交,或恢复基线 tag `recovery/E6-1/baseline-202608271355-c67b1498a2d5`;datasource publication、patch、lock、构建顺序和文档必须作为一个兼容集合回退。 +- 原子提交:`0a8ed3b910679a08a7e41c735338c3804a2eb938`(`Exo: bound cache writer requests`)。 +- 恢复 tag:`recovery/E6-1/20260827145043-0a8ed3b91067`;tag 创建耗时 0 秒。 +- 当前结论:E6-1 完成。下一动作:按主评估索引评估下一项尚未实施的 Exo 任务,不自动扩大到 E6-2 或并行预加载。 diff --git a/docs/E7-1-exo-iso-reader-safety.md b/docs/E7-1-exo-iso-reader-safety.md new file mode 100644 index 0000000000..dbc0c1ef5d --- /dev/null +++ b/docs/E7-1-exo-iso-reader-safety.md @@ -0,0 +1,41 @@ +# E7-1 Exo ISO reader safety + +## Recovery anchor + +- 目标:只修复 `IsoDataReader` 的零长度、非法/超大预取以及 open/close/EOF 边界,不改变正常 ISO 读取、sector cache、预取批次或播放器策略。 +- 状态:已实施、验证并提交;实现 commit `491a7def30484b0936426bbc57b09f5b6435ae80`,恢复 tag `recovery/E7-1/20260827160011-491a7def3048`。 +- 来源:`FongMi/media@990abc2368fd74779f525ee345734470659f3d53`,父提交 `c85d124102c5b25a1bcd270d78f78603e87a6214`;当前 fork 初版 `39585f19e01324308213e2bdc9aa84dcfa4d5ebc`,Media3 基线 `e3e922d5c01bc0b564849940fe589daf37360d15`。 +- 范围:本文件、主评估索引、Media3 构建顺序、E7-1 patch、datasource publication 和 media lock;排除 E7-2 multi-extent、App resolver、MPV、FFmpeg、nextlib/native。 +- 时间约束:15:22 起算,计划 25 分钟、最晚 15:57;不重复成功检查,不扩展研究或验证范围。 +- 下一动作:在隔离 Media3 checkout 应用源码与定向测试,执行一次 datasource 测试/发布。 + +## 决策与最佳实践 + +- 当前项目已有连续 ISO/UDF 基础读取,但 `read(length=0)` 会发生尾位置下溢,`prefetchRange()` 可按损坏范围分配超大数组,`directRead()` 在 `open()` 抛错时不会进入原有 `finally`。 +- 上游完整提交同时包含 multi-extent API;原样合并会扩大到 E7-2 并改变所有光盘 helper。本任务采用 WebHTV 窄适配,只提取 `IsoDataReader` 安全不变量并补定向测试。 +- 依据:上游源码及实际 diff、Media3 `DataSource` open/read/close 契约、当前 WebHTV 调用链 `IsoParsedMedia → IsoDataReader` 和评估文档检查点 26/41.10。PR/issue、相关项目实现和论文/基准不会改变这一简单边界修复,故不继续扩展研究。 +- 性能:正常 `read()` 只增加一次 `length == 0` 判断;正常小范围 prefetch 只复用已计算的 sector count;cache 上限 8192 sectors、64-sector 按需预取和读取循环均不变。超大异常预取被拒绝,因此只会减少资源消耗。 +- 风险:EOF/短读或 open 失败的 close 语义、sector 边界和零长度返回值。以定向单测、datasource 编译/发布及两条 App 编译路径作为门槛。 +- 回滚:本任务 patch、datasource publication、lock、构建顺序和文档作为一个集合恢复到基线 tag;不触碰预存 dirty Media3 工作树。 + +## 验收标准 + +- 零长度读取不创建或打开 DataSource。 +- 负数、空、反向和超过 8192 sectors 的预取不分配、不读取。 +- 正常跨 sector 读取结果不变。 +- `open()` 抛错和 EOF 均关闭 DataSource。 +- 定向测试、datasource 编译/发布、Mobile/Leanback arm64 Java 编译和产物哈希通过。 + +## 实施记录 + +- 2026-08-27:用户批准实施;task guard `E7-1` 已启动,预存 dirty 文件全部受保护。 +- 在复用 E6-1 已验证补丁栈和固定 Gradle 缓存的隔离 checkout 中,使用 JDK 21 执行 `:lib-datasource:testDebugUnitTest --tests androidx.media3.datasource.IsoDataReaderTest`、debug/release 编译和 `:lib-datasource:publishReleasePublicationToMavenRepository`;结果 `BUILD SUCCESSFUL in 1m 37s`,249 个任务中 13 个执行、236 个复用缓存。 +- 定向测试覆盖零长度不 open、负/空/反向/超 8192-sector 预取不 open、正常跨 sector 字节一致、open 失败 close 和 EOF close。 +- 产物:patch `d042b6c177910604f7f251571909d018d0227abc4af7846b15a0b5d499be5893`;AAR `1f0927aa4ab78e17163efb83b03119f385eb2cc803ad46dbead0399c0d8897eb`;sources `fde247c59fca0325b8a346495f91af32eb6c544b08a1dac4119d66ed8b245daa`;module `da1217b2c644cd1de2dc2d94b9429ac33b18ef079b400167a1a3ef562987e518`;POM `b51078a1e63db36711db979356929957a716a01441c182cd772e2b02620a1d52`。 +- App 消费验证:JDK 21、固定 Gradle 缓存下运行 Mobile/Leanback arm64 Debug Java 编译,两个目标均实际执行,结果 `BUILD SUCCESSFUL in 39s`,50 个任务中 4 个执行、46 个复用缓存。 +- 验收结论:正常跨 sector 读取字节保持一致;异常范围不分配/读取;open/EOF 生命周期受测;datasource publication 和两条产品编译路径通过。未改变 cache 容量、64-sector 预取、正常读取循环、E7-2 API、App resolver、MPV/native 或公共 API。 +- 剩余风险:未做损坏 ISO 实机播放,但定向测试覆盖本任务全部新增分支;实机多 extent/光盘矩阵属于 E7-2,不作为 E7-1 门槛。 +- 回滚:整体回退本任务提交或恢复 `recovery/E7-1/baseline-202608271500-fa9e8da83154`。 +- 原子提交:`491a7def30484b0936426bbc57b09f5b6435ae80`(`Exo: harden ISO reader boundaries`)。 +- 恢复 tag:`recovery/E7-1/20260827160011-491a7def3048`,创建耗时 0 秒。 +- 当前结论:E7-1 完成。下一动作:单独评估 E7-2 multi-extent + C3,不自动实施。 diff --git a/docs/E7-2-exo-iso-multi-extent-api.md b/docs/E7-2-exo-iso-multi-extent-api.md new file mode 100644 index 0000000000..27e73fb3d9 --- /dev/null +++ b/docs/E7-2-exo-iso-multi-extent-api.md @@ -0,0 +1,52 @@ +# E7-2 + C3 ISO multi-extent integration + +## Recovery anchor + +- Objective: make Media3 and the App read an ISO/UDF file stored in multiple allocation extents as one continuous logical file, while preserving the existing single-extent fast path and E7-1 reader safety. +- Authority: approved by the user on 2026-08-27; implementation started at 2026-08-27 17:39:10 CST. +- Lane/scope: `upstream`; Media3 ISO/UDF entry/parser/datasource and required BDMV/DVD callers, App `IsoTrackMetadataResolver`, affected Media3 artifacts/patch/lock, and this task record. Excludes MPV native, FFmpeg, nextlib, unrelated disc correctness, and unrelated cleanup. +- Branch/base: `fongmi-sync` at `9ab038c91adb1b49b34d59a8cbdc292c2df04074`. +- Rollback anchor: `recovery/E7-2-C3/baseline-202608271739-9ab038c91adb`. +- Protected pre-existing dirty paths: `.codex/scripts/task_guard.sh`, `AGENTS.md`, `docs/agents-md-effective-constraints-review-2026-08-21.md`, plus unrelated dirty files in the Media3 working copy. +- Source: `FongMi/media@990abc2368fd74779f525ee345734470659f3d53`, parent `c85d124102c5b25a1bcd270d78f78603e87a6214`; local ISO/UDF origin `39585f19e01324308213e2bdc9aa84dcfa4d5ebc`; Media3 base `e3e922d5c01bc0b564849940fe589daf37360d15`. +- Acceptance: single-extent behavior remains one direct upstream range; multiple recorded extents and unrecorded zero-filled extents are represented in logical order; allocation continuation is bounded; App metadata reads all extents; affected Media3 and product compilation pass. Tests are explicitly omitted by user direction. +- Known evidence limit: no real split ISO/MPLS/CLPI image is available. No test fixture was added or run by user direction, so this task does not claim real-disc behavioral coverage. +- Current status: implemented and committed as `5f7d834bfdd00f215609df7b41c2ea7cadc2cd4f`; recovery tag `recovery/E7-2-C3/20260827193629-5f7d834bfdd0`. The reproducible patch, three affected AAR publications, and Mobile/Leanback arm64 App Java compilation are complete. No tests or real split-disc playback were run by user direction. +- Next action: optional real split ISO/MPLS/CLPI device validation when representative media is available; no implementation work remains in E7-2 + C3. + +## Decision and best-practice review + +The no-change option leaves a demonstrated single-offset truncation in `UdfFileSystem`, `IsoDataSource`, `BdmvSourceHelper`, and the App resolver. Applying the complete upstream commit unchanged is inappropriate because the current fork already contains the ISO stack plus later WebHTV changes and E7-1 safety fixes. The selected design is a narrow adaptation of the upstream extent contract: retain legacy constructors as the single-extent fast path, add immutable extent arrays, parse standard recorded/unrecorded allocation descriptors with explicit bounds, and migrate only consumers that address an `IsoFileEntry`. + +Evidence used: + +- Grade A: exact upstream source and diff at `FongMi/media@990abc2368fd74779f525ee345734470659f3d53` define `extentOffsets`, `extentLengths`, zero-filled unrecorded extents, allocation continuation, and a virtual multi-extent datasource. +- Grade A: current WebHTV source shows `IsoTrackMetadataResolver.readEntry()` and BDMV metadata reads using only `entry.byteOffset`, proving the remaining gap. +- Grade A: UDF allocation descriptors distinguish recorded extents, unrecorded extents, and continuation descriptors; the logical file must not be represented by only its first physical offset. +- Grade B: mature UDF readers use an extent map and explicit handling for holes/continuations rather than assuming file contiguity. +- Upstream discussion/PR and field sample evidence were unavailable; this limits real-media confidence but does not change the data-model requirement. Academic papers are inapplicable because this is a filesystem mapping contract, not an algorithmic or performance technique. + +Performance decision: keep the existing scalar constructor and one-element arrays, avoid extra upstream reopen operations for the normal single extent, and only traverse/reopen when the file actually has multiple extents. Package-size impact should be source-level only with no new library. + +Security/correctness decision: reject invalid lengths/offsets and overflow, bound allocation continuation depth and bytes, detect repeated continuation locations, preserve zero-progress read protection, and cap metadata using the existing 8 MiB resolver limit. + +## Implementation history + +- Added immutable `extentOffsets`/`extentLengths` while preserving scalar constructors and single-extent behavior. +- Ported bounded UDF allocation descriptor parsing, recorded/unrecorded extents, zero filling, AED continuation loop/depth/size checks, and overflow/no-progress guards. +- Ported the logical multi-extent `IsoDataSource`; single extent still opens one upstream range and reads directly. +- Adapted BDMV M2TS, MPLS/CLPI reads and prefetch; adapted DVD VOB cell/IFO reads without importing later DVD grouping or time-axis redesign. +- Adapted App `IsoTrackMetadataResolver` with the existing 8 MiB cap and strict short-read behavior. +- No tests or synthetic fixtures were added or run by user direction. Real split-disc playback remains an explicit residual validation gap. +- Replayed the full existing Media3 patch order plus `media3-exo-iso-multi-extent.patch` in an isolated clean checkout. Datasource/extractor/exoplayer debug Java compilation passed in 1m48s after cache warm-up; no tests were run per the user's instruction. +- Published only datasource/extractor/exoplayer release artifacts from the isolated checkout; release compilation and publication passed in 2m03s. +- Artifact hashes: + - datasource AAR `1b6b51e921577cb955db2ce05106a44001ad126b8f4cc67f997d1f3404ec3598`, sources `26306314752ff1b4297aea2f25e6ff0213497404564f23af95ec4bb5c25ada62`, module `7f50a6b1817a68d7ca57899765029fda3fe37d926ee69689a6116fa518d0903d`, POM `b51078a1e63db36711db979356929957a716a01441c182cd772e2b02620a1d52`. + - extractor AAR `12e03f413c9251109515011249c7151e1f33b55715d7bfad3b8687adcf876c58`, sources `c80e000e7960fca4f256ead3ed830aa1661bdb23d06b1c6ecfae6ac7e3ba73b0`, module `4b7a4df9b09f1e62c5d61f57cbe70ab4c3e14f5d50837e588edf5ee62a931128`, POM `32fb358a5f4ecee7bb58ac8f97b975e8af89cdd19533e35b520533bf76c5979b`. + - exoplayer AAR `11d572f59f0404878353d9c85e022e153e114ecbb4d43cf61c910cd9e8c2536d`, sources `c2a74d177abff6e91de2b26d0680920a966672796a080572d6477a2e3c9aa6db`, module `f20106bb4c89f0b167dec34a2909daf427149800e14f11db130431e95523e95d`, POM `ca5be4f0911931b82df270917cb91d2f1d221a97bcecd11f0d78eeaa620308a5`. +- Patch hash: `b4954d32f5c98dc5caf2a3cbc8cd72f72d24f4fdeec9425e5061a252d1ccaf68`. +- Implementation commit and recovery tag: `5f7d834bfdd00f215609df7b41c2ea7cadc2cd4f` / `recovery/E7-2-C3/20260827193629-5f7d834bfdd0`. +- App consumption: `:app:compileMobileArm64_v8aDebugJavaWithJavac` and `:app:compileLeanbackArm64_v8aDebugJavaWithJavac` both executed and passed in one Gradle invocation (`BUILD SUCCESSFUL in 1m26s`, 4 executed / 46 up-to-date tasks). +- Performance preservation: legacy scalar constructors remain; a single recorded extent opens one upstream range and does not reopen while reading. Extra range opens and extent traversal occur only for genuinely split files. No benchmark was run, so this is a structural preservation claim rather than a measured performance result. +- Verification deliberately omitted: unit tests, real split ISO/MPLS/CLPI playback, HTTP/SMB/content-URI extent boundary playback, seek/device testing, and SACD cross-extent stripping. These remain residual risks rather than hidden completion claims. +- Rollback: revert `5f7d834bfdd00f215609df7b41c2ea7cadc2cd4f` or restore `recovery/E7-2-C3/baseline-202608271739-9ab038c91adb`; the completed implementation is anchored by `recovery/E7-2-C3/20260827193629-5f7d834bfdd0`. Source patch, lock, three AAR publication directories, App adapter, and documentation must move together. diff --git a/docs/E9-3-exo-dv5-vulkan-renderer.md b/docs/E9-3-exo-dv5-vulkan-renderer.md new file mode 100644 index 0000000000..734240433d --- /dev/null +++ b/docs/E9-3-exo-dv5-vulkan-renderer.md @@ -0,0 +1,708 @@ +# E9-3: Exo DV5 Vulkan renderer + +状态:实施已获用户授权,先实现默认关闭的硬解 GPU 映射原型;真机验收前不替换现有生产路径。 + +## 1. 目标与边界 + +- 目标:在没有原生 Dolby Vision Profile 5 显示能力、但普通 HEVC MediaCodec 能输出可采样 10-bit `AHardwareBuffer` 的设备上,让 Exo 使用硬解并通过 Vulkan/libplacebo 恢复正确色彩。 +- 保留:Exo 的解封装、网络、音频、字幕、轨道、时钟、帧释放、掉帧统计和 PlayerView 协议。 +- 不做:P5->P8.1 码流伪转换、把 P5 冒充 HDR10 后 Surface 直出、复用 `libmpv.so` 私有状态、DV7 FEL 双层合成、DRM 安全视频输出。 +- 首个实施单元:独立 `VideoSink`/native renderer 原型,默认关闭,仅 Profile 5、非 DRM、Vulkan 能力通过时可被显式启用。 + +## 2. 基线 + +- App:`742de1b08b01e6022517f6200a7502d1326301c9`,分支 `exo-dv5`,开始时工作树干净。 +- Media3:WebHTV `e3e922d5c01bc0b564849940fe589daf37360d15`,版本 `1.11.0-alpha01-fongmi`。 +- MPV 实证链:MPV `cca559b41ceb0bb7731cf6ef2e1f33276cd30c42`、FFmpeg `04482c8d13ac27b2a9fe93f5d388929eef8af5f4`、libplacebo `b694a21bf2dc176c1e98b8a13c6421a0de5f3da5`。 +- 设备证据:用户确认当前 WebHTV MPV 的 `MediaCodec + Vulkan + gpu-next` 在目标设备播放 DV5 时颜色正常,至少不再紫绿。 +- 当前 Exo 缺口:`ExoUtil.DolbyVisionHdr10FallbackRenderer` 把 Profile 5 改报普通 HEVC/HDR10 并直接输出 Surface,没有进行 Dolby IPT/RPU 映射。 + +## 3. 决策证据 + +访问日期均为 2026-08-27。 + +| 证据 | 等级 | 支持的结论 | 局限/影响 | +| --- | --- | --- | --- | +| Android `MediaFormat.KEY_COLOR_TRANSFER_REQUEST` 官方 API 文档 | A | API 31+ codec 可接受 transfer/tone-map 请求;请求必须在配置后验证 | 只适用于设备已有可工作的 DV decoder,不解决普通 HEVC decoder 的 raw DV5 GPU 映射 | +| Android NDK `AImageReader` / `AHardwareBuffer` 与 Vulkan Android external-memory API | A | codec 可输出到 `AIMAGE_FORMAT_PRIVATE` reader,buffer 可用 GPU sampled usage 导入 Vulkan | 具体 external format、10-bit 精度、fence 和驱动行为依设备而异 | +| Media3 `VideoSink` / `MediaCodecVideoRenderer.Builder.setVideoSink`,WebHTV 锁定线 `e3e922d...` | A | 可保留 Media3 renderer 的 codec/时钟/掉帧逻辑,仅替换 codec 输入 Surface 和最终渲染 | `VideoSink` 是 Unstable API,升级 Media3 时必须有编译契约测试 | +| FongMi/media `0cefd3ceec27444cf8faf02486b472bab39109fe` | A | Profile 5 不能作为标准 HDR10 BL;有 DV codec 时优先请求并验证 codec tone-map | GPU fallback 必须位于 codec tone-map 之后,不能替代原生能力 | +| FongMi/FFmpeg `eb107bbafe37442065e42b4f2d410f371b758143` 与 `15b73698835285d68f9615691dd4dfc04422f28e` | A | MediaCodec 硬解链需保留逐帧 RPU/解析元数据,才能在 GPU 阶段应用 DV5 映射 | Exo 原生 MediaCodec 不会自动提供 FFmpeg `AVFrame` side data,需在输入 AU 上自行提取 | +| FongMi/mpv `c7fef70644b3d506340e113689a5923f324c861d` 及当前锁定树 | A | `gpu-next` 能对 raw MediaCodec DV5 帧应用 GPU mapping | mpv 的 VO/queue/decoder 状态机不能直接嵌进 Exo | +| 当前 `hwdec_aimagereader.c` 与 Vulkan direct/stable 实现 | A | 使用 PTS 匹配 AImage;DV5 采样必须保持 full range、RGB identity 和原始 Y/Cb/Cr 分量语义 | 需要保留 AImage 到 GPU fence 完成,不能在回调中提前释放 | +| libplacebo `b694a21bf2dc176c1e98b8a13c6421a0de5f3da5` | A | 支持 `PL_COLOR_SYSTEM_DOLBYVISION`、RPU matrix/reshape、tone mapping 和 Vulkan 输出 | 必须独立构建/链接,不能依赖 `libmpv.so` 内部生命周期 | +| FongMi/media `7d0d1e3c572aee885ffbbfd6d8317f1f3a581910` | B | GLES/libplacebo renderer 提供了 Media3 Surface/lifecycle 参考和 Dolby metadata 映射参考 | 该提交是 FFmpeg 软件解码,不满足本任务硬解目标,只取 renderer 生命周期设计 | +| mpv-player/mpv issue #10287 与 mpv-android issue #1081 | B | 普通 MediaCodec-copy/错误 Surface 转换会紫绿;Android 硬解 GPU DV 路径具有设备依赖 | issue 不是规范,不能替代本项目真机验收 | + +论文类证据不适用:本任务的决定因素是 Android codec/BufferQueue/Vulkan ABI 和实际开源实现,不是新的色彩科学算法;Dolby 专有规范也不提供可用于 Android 公共实现的完整生产契约。 + +## 4. 方案比较 + +### A. 不改 + +- 优点:无新增 native 风险。 +- 缺点:无 DV5 decoder 的设备继续紫绿,当前 HEVC/HDR10 伪装语义错误。 +- 结论:不能满足目标。 + +### B. P5->P8.1/RPU-only 转换 + +- 优点:Extractor 层改动小。 +- 缺点:只改 RPU,不能把 P5 的 Dolby IPT 基础层转换成 HDR10 基础层。 +- 结论:拒绝。 + +### C. 原样移植 MPV 播放器或调用 `libmpv.so` 内部 libplacebo + +- 优点:目标设备已有成功实证。 +- 缺点:会引入第二套 demux/clock/track/lifecycle;`libmpv.so` 的 libplacebo 符号和上下文不构成稳定 Exo API;二进制与回滚耦合。 +- 结论:拒绝原样集成,只移植已经验证的 AImageReader/Vulkan/DV 表示规则。 + +### D. WebHTV 适配的 Media3 `VideoSink` + 独立 native Vulkan/libplacebo + +- 优点:保留 Exo 主体;codec 输出 Surface、帧时序和显示 Surface 有清晰所有权;可以按能力和内容窄启用;MPV/Exo 二进制独立回滚。 +- 缺点:需要新的 native 资产、RPU 提取、PTS 配对、Vulkan/AImageReader 生命周期和真机矩阵。 +- 结论:推荐并实施。 + +## 5. 推荐架构 + +```text +Media3 Extractor / SampleStream + | + | HEVC access unit + input PTS + v +MediaCodecVideoRenderer (ordinary HEVC decoder view for P5) + | + | codec output Surface + v +ExoDoviVideoSink.getInputSurface() + | + v +AImageReader PRIVATE + GPU_SAMPLED_IMAGE + | + | AImage timestamp -> input PTS metadata map + v +AHardwareBuffer -> Vulkan external image + | + | RGB_IDENTITY, full range, raw Cr/Y/Cb mapping + v +libplacebo Dolby Vision reshape + tone map + | + v +PlayerView output Surface +``` + +### 5.1 Media3 ownership + +- 用 `MediaCodecVideoRenderer.Builder.setVideoSink()` 接入,不复制 `MediaCodecRenderer` 状态机。 +- `VideoSink.handleInputFrame()` 保存 renderer 提供的释放 handler;到计划释放时调用 handler,将 codec buffer 送进 AImageReader Surface。 +- AImage timestamp 必须与 codec buffer PTS 精确匹配;seek/flush/stream change 清空帧、RPU 和 handler 队列。 +- tunneling 在该路径禁用;自定义 GPU 渲染与 tunneling 不兼容。 + +### 5.2 RPU 所有权 + +- 在 MediaCodec 输入 AU 入队前扫描 HEVC NAL type 62,保留原样 AU 给 decoder,同时把 RPU 副本按 input PTS 送入 native metadata queue。 +- MP4 length-prefixed 与 Annex-B 都要支持;解析失败为单帧失败,连续失败触发整次播放受控回退。 +- RPU 解析和 `pl_dovi_metadata` 生成在 native 层完成;Java 不复制 Dolby 结构体。 +- 不把 ExoplayerHdrUtils 0.4.0 当作 metadata API:其公开 JNI 只提供 frame transform/profile 信息,没有输出可供 libplacebo 使用的 RPU 映射结构。 + +### 5.3 Native 资产 + +- 新库独立命名为 `libexo_dovi_renderer.so`,两 ABI 成套构建。 +- 只包含本路径需要的 AImageReader、Vulkan、libplacebo、RPU 解析和同步代码;不链接 mpv demux/player/VO 状态机。 +- 首选 Vulkan direct AHardwareBuffer sampling;失败可回退 stable GPU conversion;均失败则声明能力不可用并回到下一 Exo renderer/MPV。 +- 禁止运行时链接 `libmpv.so` 的内部 libplacebo 状态。 + +### 5.4 策略顺序 + +1. 显示和 decoder 均支持原生 DV5:原生 DV。 +2. API 31+ DV decoder 接受 `KEY_COLOR_TRANSFER_REQUEST`:codec tone-map。 +3. 非 DRM、普通 HEVC decoder、Vulkan/AHB probe 通过且用户/实验允许:本 E9-3 GPU mapping。 +4. 否则:MPV `gpu-next` 或服务端转码;不得再把 Profile 5 无条件冒充 HDR10。 + +## 6. 安全与兼容约束 + +- DRM:`cryptoType != NONE` 一律不声明支持;安全 decoder/secure Surface 不进入自定义 GPU。 +- API:最低运行 API 26,Vulkan external-memory/AHardwareBuffer 能力逐项探测;仅检查 Vulkan 版本号不够。 +- 精度:源 buffer 必须证明为可用的 10-bit/external format;不允许静默降为 8-bit 后仍标记成功。 +- 生命周期:Surface replacement、后台/前台、seek、flush、换集和 release 必须停止接收回调并等待/取消有限 fence。 +- 队列:输入 RPU、codec handler、AImage 三者均有上限;按 PTS 丢弃 stale 项,不允许无界积累。 +- 故障:初始化失败在 codec 启动前返回不支持;运行时连续映射失败报告可分类错误,由 App 只重建一次并回退。 +- 输出:SDR 屏默认输出 BT.709 SDR;HDR10 屏可后续增加 BT.2020 PQ,首个单元不同时扩展两种输出策略。 + +## 7. 实施阶段 + +### E9-3a:契约与能力门控 + +- 新增纯 Java 的 Profile 5/DRM/API/Vulkan 路由策略、失败原因和单测。 +- 新增 `VideoSink` 壳和 native capability bridge;native 不可用时不得抢占 track。 +- 将现有 Profile 5 HEVC/HDR10 fallback 收窄为最后的显式兼容选项,不在本单元直接删除。 + +### E9-3b:硬解 Surface 与帧同步 + +- 独立 native 库创建 AImageReader Surface。 +- 实现 MediaCodec handler -> AImage timestamp 的有界配对、flush/release。 +- 先以不做 DV mapping 的诊断图/帧计数验证 10-bit AHB 导入和稳定出帧。 + +### E9-3c:RPU 与 libplacebo 映射 + +- 输入 AU 提取 RPU并按 PTS入队。 +- libplacebo raw DV representation、reshape、BT.709 SDR 输出。 +- 目标 DV5 样片与 MPV 同帧截图/色彩对照。 + +### E9-3d:受控接线 + +- 默认关闭的实验开关、设备失败记忆和一次性回退。 +- 通过设备矩阵后才允许自动策略选择;未通过时生产默认仍走原生 DV/codec tone-map/MPV。 + +## 8. 验收标准 + +- 自动化:Profile 5/7/8、DRM、API、Vulkan probe、renderer 优先级、flush/PTS queue 的单测。 +- 编译:Media3/App Java 编译;两个 ABI native clean build;ELF `SONAME`/`DT_NEEDED`/版本标记校验。 +- 设备:目标设备同一 DV5 文件确认 `MediaCodec` 硬解、Vulkan renderer、生效 RPU 数、无紫绿;与 MPV gpu-next 截图对照。 +- 生命周期:起播、seek、暂停恢复、前后台、换集、Surface 重建、连续 20 次退出进入,无黑屏/死锁/use-after-free。 +- 性能:4K 代表片连续 10 分钟,无持续队列增长;掉帧、GPU 帧时和功耗不显著劣于同设备 MPV 路径。 +- 负向:DRM、8-bit AHB、缺少 Vulkan external format、RPU 缺失/损坏均不错误宣称成功。 + +## 9. 回滚 + +- 每个子阶段独立 commit/recovery tag。 +- E9-3a 回滚只移除策略/壳,不改变 Media3 AAR 或 MPV。 +- E9-3b/c 回滚删除独立 native AAR/`.so` 和 renderer 注册;现有 Exo、nextlib、MPV assets 保持原版本。 +- E9-3d 运行时可通过关闭实验开关立即停止选择该路径,无需删除媒体数据库或配置。 + +## 10. 当前检查点 + +- 已完成:方案、证据、替代比较、验收和回滚边界;用户已明确要求按最佳实践继续实现。E9-3a 已新增纯 Java 路由/能力策略,覆盖原生 DV、API 31+ codec tone-map、实验性 GPU mapping、显式旧 HDR10 兼容和不支持结果;现有 P5 兼容 renderer 已接入该策略但保持原默认行为。 +- 未完成风险:尚未用目标设备验证 Exo 自建 AImageReader Surface 是否得到与 MPV 相同的 10-bit external format;这是 E9-3b 的硬门槛。 +- 下一动作:完成 E9-3a 的定向 JVM 验证并提交恢复点,然后为 E9-3b 声明 native/Java/build 的独立范围。 + +## 11. E9-3a 实施记录 + +- 代码:新增 `ExoDv5GpuMappingPolicy`。GPU 路由要求 Profile 5、非 DRM、API 26+、非 tunneling、普通 HEVC 硬解器、独立 renderer native 库、Vulkan/AHardwareBuffer probe 和实验开关全部通过;原生 DV 和 API 31+ 已接受的 codec tone-map 优先。DRM 即使允许旧兼容也不会进入 GPU 或旧 HDR10 fallback。 +- 接线:`ExoUtil.shouldUseDolbyVisionHdr10Fallback` 的 Profile 5 分支改由策略返回值决定。E9-3a 没有注册不存在的 `VideoSink`,现有非 DRM Profile 5 默认仍进入旧兼容 renderer,等待 E9-3b/c 真机成立后再调整生产优先级。 +- 测试:独立 JUnit 4.13.2 执行 `ExoDv5GpuMappingPolicyTest`,9 个用例通过;`:app:compileMobileArm64_v8aDebugJavaWithJavac` 成功,证明 App/Media3 接线可编译。 +- 已知验证阻断:`:app:testMobileArm64_v8aDebugUnitTest` 在执行测试前的 `processMobileArm64_v8aDebugResources` 失败,缺少既有 Material/Media3 style/attr/color 资源。本单元未修改资源或依赖,故没有扩大范围处理该基线问题,也不把新增 JUnit 结果表述为 Android Gradle 测试任务通过。 +- 回滚:回退 E9-3a commit/tag 即恢复原 Profile 5 fallback 判断;没有 native 资产、Media3 AAR、设置或数据库变更。 +- 下一动作:启动 E9-3b 独立实现单元,先完成 AImageReader/`AHardwareBuffer` capability bridge、`VideoSink` Surface 生命周期和有界 PTS 配对;DV 映射仍保持关闭。 + +## 12. E9-3b 实施记录 + +- 代码:新增独立 `libexo_dovi_renderer.so` CMake target(使用锁定 NDK r29,arm64-v8a 与 armeabi-v7a),并通过 `ExoDv5Native` 暴露能力探测、AImageReader Surface、有限 expected-frame 队列、AHardwareBuffer 使用/高位深统计和释放接口。 +- Media3:新增 `ExoDv5VideoSink` 与 `ExoDv5GpuRenderer`,使用锁定 Media3 `VideoSink`/`MediaCodecVideoRenderer.Builder.setVideoSink()` 契约;视频帧 handler 的释放时间仍由 Media3 控制,AImage 时间戳按 presentation PTS(微秒转纳秒)配对,避免把渲染 deadline 错当 codec PTS。Renderer factory 仅支持显式诊断创建,当前未注册到生产 renderer 列表。 +- 能力门控:native probe 要求同一 Vulkan 物理设备同时具备 Vulkan 1.1、`VK_ANDROID_external_memory_android_hardware_buffer`、`VK_EXT_queue_family_foreign`、sampler YCbCr conversion,并成功创建逻辑设备取得 AHB 导入函数;AImageReader 必须是 `AIMAGE_FORMAT_PRIVATE + AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE`。不满足时不会声明可用。 +- 测试/构建:`:app:compileMobileArm64_v8aDebugJavaWithJavac` 成功;`:app:externalNativeBuildMobileArm64_v8aDebug` 与 `:app:externalNativeBuildMobileArmeabi_v7aDebug` 成功,产物分别确认 ELF 64-bit AArch64 与 ELF 32-bit ARM。新增纯逻辑测试覆盖显式 opt-in、完整 probe、队列时序和 PTS 纳秒换算;Android Gradle 单测仍受既有资源链接错误阻断。 +- 当前限制:此单元只验证 codec→AImageReader/AHardwareBuffer 通路并统计 buffer,不导入 Vulkan 图像、不调用 libplacebo、不输出 PlayerView,也不提取/解析 RPU。因此不能宣称 DV5 色彩已恢复;这些属于 E9-3c/3d。 +- 回滚:回退 E9-3b commit/tag 可移除 CMake/native 目标与诊断 sink,既有 Exo/MPV 二进制和默认路径不变。 +- 下一动作:启动 E9-3c,接入独立 libdovi/RPU parser 与 libplacebo mapping API;先定义逐帧 metadata 所有权和 malformed-RPU 回退,再实现 Vulkan external image 到输出 Surface 的最小帧路径。 + +### E9-3b 检查点 + +- 完成:E9-3b diagnostic Media3 VideoSink and independent AImageReader/Vulkan capability bridge compile for arm64-v8a and armeabi-v7a; ELF SONAME, JNI exports and DT_NEEDED verified; production renderer remains unregistered. +- 分支/基线:`exo-dv5` / `7f665b7d858454fa19919b1e0b69b0f239ac9587`。 +- 已改路径:`app/build.gradle`、`app/src/main/cpp/**`、四个 `ExoDv5*` Java 文件、新增测试和本任务文档;无起始脏文件。 +- 验证:App Java、两 ABI CMake build 成功;ELF64 AArch64/ELF32 ARM、`libexo_dovi_renderer.so` SONAME、七个 JNI 导出和 `libandroid/libmediandk/libvulkan` 依赖已确认。 +- 验证补充:使用 JDK 21 执行 `bash gradlew :app:testMobileArm64_v8aDebugUnitTest --tests com.fongmi.android.tv.player.exo.ExoDv5GpuRendererTest --no-daemon`;任务在既有 `processMobileArm64_v8aDebugResources` 资源链接错误处终止,未进入测试执行。该错误涉及缺失的 Material/Media3 资源,本阶段未改动资源或依赖。 +- 未解决风险:目标设备尚未运行 capability probe/codec Surface 出帧;AImageReader 回调销毁只完成静态审计,尚无设备压力验证;本阶段不具备显示输出和 DV mapping。 +- 回滚锚点:`7f665b7d858454fa19919b1e0b69b0f239ac9587`。 +- 下一动作:Run ExoDv5GpuRendererTest with Gradle JDK 21, finish release-lifecycle review, then commit and tag E9-3b. + +## 13. E9-3c 依赖本地化检查点 + +- 检查点摘要:E9-3c dependency provenance and missing armv7 shaderc resolved; isolated r29 build succeeded +- 下一动作:Copy the two-ABI libplacebo/shaderc closure into third_party/exo-dv5-native and link it from local CMake + +## 14. E9-3c 依赖本地化实施记录 + +- 已完成:在当前仓库新增 `third_party/exo-dv5-native`,复制 libplacebo 7.375.0/API 375 的 arm64-v8a、armeabi-v7a 静态库,以及使用 NDK r29/API 24 独立生成的两 ABI shaderc 组合归档;构建和运行时不再读取 `main-2` 路径。 +- CMake:`app/src/main/cpp/CMakeLists.txt` 通过 `${CMAKE_CURRENT_LIST_DIR}/../../../../third_party/exo-dv5-native` 引入 ABI 对应归档,链接 `libdl`、`libm`、Android/MediaNDK/Vulkan,并启用 libplacebo 的静态 pthread 配置。 +- Native 探针:`exo_dovi_renderer.cpp` 调用 `pl_version()` 并只在 API 375 库可用时上报 `CAPABILITY_LIBPLACEBO_375`;Java 能力门控已将该位列为必需能力。 +- 资产哈希:见 `third_party/exo-dv5-native/MANIFEST.sha256`。来源版本为 libplacebo `b694a21bf2dc176c1e98b8a13c6421a0de5f3da5`;shaderc 使用 NDK `29.0.14206865` 的 staged source,armv7 归档在独立临时输出目录生成。 +- 验证:`JAVA_HOME=.../Contents/Home bash gradlew :app:externalNativeBuildMobileArm64_v8aDebug :app:externalNativeBuildMobileArmeabi_v7aDebug --no-daemon` 成功;两 ABI 均完成 CMake 链接。该验证只证明 native 资产和 JNI 探针可编译,不证明 DV5 已完成 Vulkan 图像导入、RPU 映射或色彩恢复。 +- 未完成:libplacebo Vulkan 外部图像导入、PlayerView 输出和逐帧 Dolby Vision RPU 映射仍属于后续功能单元;当前 renderer 仍保持诊断/显式 opt-in,默认播放行为不变。 +- 回滚:回退本单元提交即可移除本地依赖和 CMake 链接,恢复 `c94ba7c9464f4cb43df351e471e8aa2df7132178` 的诊断底座。 +- 下一动作:在独立后续单元中补齐 Vulkan/AHardwareBuffer 到输出 Surface 的实际渲染,再进行目标设备 DV5 色彩验收。 + +## 15. E9-3c-render 检查点 + +- 检查点摘要:libdovi-3.3.2 builds for both Android ABIs in isolated output; current libplacebo archive lacks libdovi mapping support; no incomplete renderer was committed +- 下一动作:Start a new native asset unit to vendor libdovi C API and both ABI archives before wiring Vulkan renderer +- 已验证:`libdovi-3.3.2`(commit `4fd2b2235c9f93582dd4a00e65ee34a07800afd7`)使用 NDK `29.0.14206865`、Android API 26 linker 在独立临时目录成功生成 `aarch64-linux-android` 与 `armv7-linux-androideabi` 静态库;未写入其他工作区。 +- 已验证:当前本地 libplacebo 归档是 `pl_has_dovi=1` 但 `pl_has_libdovi=0`;因此仅链接现有归档不能解析 RPU,也不能生成 `pl_dovi_metadata`。现有 ExoplayerHdrUtils JNI 只提供 profile/frame info,不能替代该接口。 +- 未完成:本单元没有提交伪 Vulkan 输出或不完整 RPU 映射;当前 `VideoSink` 仍是诊断底座,生产路径和默认播放行为不变。 +- 原因:要继续实现必须新增独立 libdovi C API 头/双 ABI归档,并将 `RpuDataMapping` 完整映射到 libplacebo 的 `pl_dovi_metadata`;这是新的 native 资产和 ABI 单元,不能在没有完整头文件/真机输出验证时冒充完成。 +- 回滚锚点:`893a2cca7b56f953976d74d52317862bca6deb6c`。 +- 下一动作:启动新的独立 native 资产单元,先把 libdovi C API(含 mapping structs)和双 ABI 归档本地化,再接入 Vulkan renderer。 +- 目标:把 Exo DV5 renderer 所需的 libplacebo/shaderc 双 ABI 静态闭包复制进当前仓库,禁止运行时或构建时引用 `main-2` 绝对路径。 +- 分支/基线:`exo-dv5` / `c94ba7c9464f4cb43df351e471e8aa2df7132178`;恢复时工作树无预先存在的脏文件。 +- 已确认来源:libplacebo `b694a21bf2dc176c1e98b8a13c6421a0de5f3da5`(7.375.0/API 375),arm64-v8a 与 armeabi-v7a 各自独立构建;shaderc 来自 Android NDK `29.0.14206865` 随附源码,组合归档包含 239 个对象。 +- 已完成证据:`main-2` 缓存中存在双 ABI `libplacebo.a` 和 arm64 `libshaderc.a`;armv7 shaderc 缓存缺失,已用同一 NDK r29/API 24 在独立临时输出目录成功生成,没有写入 `main-2` 的 `obj/libs/prefix`。 +- 当前限制:尚未把资产复制到 `third_party/exo-dv5-native`,尚未接入当前仓库 CMake,也尚未完成双 ABI 链接验证;不能据此声称 DV5 色彩映射已经可用。 +- 回滚锚点:`c94ba7c9464f4cb43df351e471e8aa2df7132178`;删除本单元新增的本地依赖目录并回退 CMake/本文档即可。 +- 下一动作:复制双 ABI libplacebo/shaderc、公共头和许可证,写入来源/哈希清单并完成当前项目双 ABI native 链接。 + +## 16. E9-3c-libdovi 实施记录 + +- 来源与构建:本地化 `libdovi` 3.3.2,源码 commit + `4fd2b2235c9f93582dd4a00e65ee34a07800afd7`;`dolby_vision` crate 使用 + `features=capi`、`crate-type=staticlib`、NDK `29.0.14206865`、Android API + 26 分别生成 `aarch64-linux-android` 与 `armv7-linux-androideabi` 归档。 + C API 头由相同源码和 cbindgen 0.29.4 生成,归档、头和 MIT 许可证均由 + `third_party/exo-dv5-native/MANIFEST.sha256` 锁定。 +- 本地闭包:CMake 仅从仓库相对路径按 `${ANDROID_ABI}` 导入 + `libdovi.a`,不读取或复用其他工作区。native capability probe 实际调用 + `dovi_parse_unspec62_nalu` 的错误输入路径并释放 opaque 对象,因此双 ABI + 链接必须解析真实 parser/free symbols,而不是只检查文件存在。 +- 语义校正:libdovi 3.3.2 的 conversion mode 2 才是 P8.1 no-op mapping, + mode 4 是保留 mapping 的 P8.1;mode 3 是静态 P8.4。E9-3 不依赖任何 + P5→P8.1 伪 base-layer 转换,而是保留原始 Profile 5 IPT base layer,供 + Vulkan/libplacebo 结合逐帧 RPU 做 reshape。 +- 限制:本单元只建立可重现的 parser ABI 依赖。尚未把 RPU 从 Media3 + access unit 传入 native,也尚未创建 Vulkan swapchain/AHB external image + 和显示输出,因此不能宣称设备色彩已经恢复。 +- 回滚:回退本单元提交和恢复标签即可删除 libdovi 资产、头、许可证、 + CMake 导入和 capability parser probe;上一阶段 libplacebo 诊断底座不变。 +- 下一动作:覆盖 `MediaCodecRenderer.onQueueInputBuffer` 提取 NAL type 62, + 以 PTS 有界排队到 native 并完成 metadata 生命周期,然后接入 Vulkan 输出。 + +## 17. E9-3d-vulkan 实施检查点 + +- 当前基线:`exo-dv5` / `3df132a68e1aa67ce54b61cb091c41f88ceba00e`; + 当前单元只修改 native renderer 与本文档,无预先存在的用户脏文件。 +- 已完成代码:创建 libplacebo Vulkan instance/device/swapchain,导入 + `AImageReader` 的 `AHardwareBuffer`,按 Profile 5 raw IPT 语义设置 full-range + RGB-identity YCbCr sampler 与 Cr/Y/Cb 分量映射,解析 libdovi RPU 并调用 + `pl_render_image` 输出到 PlayerView Surface。 +- 已验证:`externalNativeBuildMobileArm64_v8aDebug` 编译成功;该结果仅证明 + arm64 native 源码和链接闭包成立,不代表设备播放或色彩验收成功。 +- 收尾风险:补齐 foreign queue ownership 的 semaphore 契约、失败路径回收、 + libplacebo log 销毁、seek 后旧 RPU 状态清理,并依据 AHB format feature + 选择采样 filter;随后执行 arm64-v8a/armeabi-v7a 双 ABI clean native build。 +- 回滚锚点:`3df132a68e1aa67ce54b61cb091c41f88ceba00e`。 +- 下一动作:核对 vendored libplacebo API 375 的 release/hold 同步契约并完成 + 上述最小安全修复。 +- 检查点摘要:arm64 native Vulkan renderer build succeeded; patched semaphore ownership, failure cleanup, log release, seek RPU reset, and AHB sampling feature gating +- 下一动作:Run dual-ABI native build, inspect result, then finish E9-3d-vulkan atomically. + +### E9-3d-vulkan 完成记录 + +- Vulkan 输出:native renderer 现已创建 Android `VkSurfaceKHR`、libplacebo + Vulkan device/swapchain/renderer,并把 `AImageReader` 的 + `AHardwareBuffer` 作为 external-memory `VkImage` 导入。输出 Surface 替换时 + 串行销毁并重建 Vulkan 资源,release 会先停止 image listener 并等待当前 + callback 退出。 +- DV5 映射:AHB sampler 强制使用 `RGB_IDENTITY + ITU_FULL`,libplacebo plane + 按 `Cr/Y/Cb` 解释 raw Profile 5 分量;输入 AU 的 NAL type 62 RPU 经 libdovi + 解析为每帧 `pl_dovi_metadata`,交给 `PL_COLOR_SYSTEM_DOLBYVISION` 的 + `pl_render_image` 完成 reshape/tone-map。 +- 同步与回收:external image 在 `VK_QUEUE_FAMILY_FOREIGN_EXT` 与 libplacebo + 之间用 `pl_vulkan_release_ex`/`pl_vulkan_hold_ex` 转移 ownership;hold 使用 + libplacebo 创建的 binary semaphore,并在 `pl_gpu_finish` 后销毁 semaphore、 + wrapper、VkImage 和 imported memory。失败路径会在回收前尝试重新取得 + ownership;Vulkan/log/swapchain/renderer 均有配对释放。 +- 格式门控:要求 AHB Vulkan format 支持 sampled image;YCbCr conversion + 仅在 format features 声明支持时使用 linear chroma filter,否则降为 nearest, + 并传递 separate-reconstruction-filter 能力。seek/flush 同时清空 pending RPU + 和 last-DV metadata,避免沿用上一时间线的元数据。 +- 验证:使用 JDK 21、NDK `29.0.14206865` 执行 + `:app:externalNativeBuildMobileArm64_v8aDebug` 与 + `:app:externalNativeBuildMobileArmeabi_v7aDebug`,两 ABI 均 `BUILD SUCCESSFUL`。 + 此结果证明 native 源码、libplacebo/libdovi/shaderc 本地闭包和双 ABI 链接成立, + 不证明目标设备已经正常出帧、颜色正确或性能达标。 +- 真机门槛:renderer 虽已具备受控注册条件,但内部实验默认关闭;没有目标设备 + DV5 播放、截图、logcat、seek/lifecycle 证据前,不开启自动生产选择,也不宣称 + 色彩或性能验收通过。 +- E9-3d-wiring:native capability bit 已按 libplacebo 7 的最低 Vulkan + 1.2 要求校正,renderer 名称由 diagnostic 改为 experimental,统计新增 + `renderedFrames` 与 `renderFailures`。自定义 renderer 仅在现有内部实验总开关 + 与 Exo 域开关同时开启、native probe 完整通过时加入列表;它位于列表最前, + 但对检测到“DV 显示能力 + 硬件 DV decoder”的设备主动返回 unsupported,保留 + 原生 DV。其余 Profile 5 才走普通硬件 HEVC decoder + VideoSink/Vulkan 路径, + 并显式关闭 tunneling。sink 初始化会补传已经设置的 PlayerView Surface,避免 + Surface 先到导致 native renderer 黑屏;native 首个成功 present 会触发 Media3 + 首帧通知,连续 3 次 Vulkan 渲染失败则上报 video-frame-processing error,避免 + 永久静默黑屏。 +- 回滚:回退本单元提交/恢复标签即可恢复到仅有 RPU 输送和本地头文件的状态; + vendored native 依赖与现有 Exo/MPV 默认路径不受影响。 + +## 17. E9-3c-renderer RPU 接线记录 + +- Media3:`ExoDv5GpuRenderer` 覆盖 `onQueueInputBuffer`;该 hook 在锁定版 + Media3 的 `DecoderInputBuffer.flip()` 之后、`MediaCodec.queueInputBuffer()` + 之前执行。扫描器不修改原 ByteBuffer,支持 Annex-B 3/4 字节起始码和 + 1/2/4 字节长度前缀,只复制 HEVC NAL type 62。 +- JNI/native:每个 RPU 带原始 `buffer.timeUs` 送入 native;libdovi 必须 + 成功解析 header(`rpu_type == 2`)和 mapping 才进入 16 帧有界队列。 + 统计有效 RPU、malformed RPU、队列丢弃和当前 pending;flush/seek 同时 + 清除 expected-frame 与 RPU 队列,避免旧 metadata 污染 seek 后帧。 +- Surface:`VideoSink.setOutputSurfaceInfo/clearOutputSurfaceInfo` 已转发到 JNI, + native 使用 `ANativeWindow_fromSurface` 获取独立引用,并在 Surface 替换、 + clear 和 renderer release 时成对释放;当前尚未用该 window 创建 swapchain。 +- 验证边界:App Java 与 arm64-v8a/armeabi-v7a native 构建通过。NAL 扫描 + 测试新增 Annex-B、四字节长度前缀和输入 position 不变断言;Android Gradle + 单测任务仍受既有资源链接基线错误约束。 +- 当前限制:本单元完成 AU→RPU parser 与 Surface 所有权接线,但 AHB 尚未 + import 为 Vulkan external image,RPU mapping 也尚未转换成 + `pl_dovi_metadata` 并送入 `pl_render_image`,所以仍不能宣称色彩恢复。 +- 下一动作:本地化完整 libplacebo API 375 公共头,然后实现 Vulkan context、 + Android swapchain、AHB external-format import、raw DV component mapping 和 + 同步 `pl_render_image` 输出。 + +## 18. E9-3d libplacebo 公共头本地化 + +- 第一批公共头来自已锁定并已链接的 libplacebo 7.375.0 commit + `b694a21bf2dc176c1e98b8a13c6421a0de5f3da5` 同一源码树,包含 Vulkan、 + GPU、swapchain、renderer、colorspace、log/cache/common 和核心 shader API。 +- 这些头只复制到当前仓库 `third_party/exo-dv5-native/include/libplacebo`; + App CMake 和 native 源码不引用 `main-2`,另一工作区仅作为本地复制来源。 +- 第一批是资产恢复点,不改变运行时或生产 renderer 选择;第二批将补齐 + renderer include 闭包后,由实际双 ABI 编译验证头与静态库 API 375 匹配。 +- 第二批补齐 `renderer.h` 的实际传递闭包:dispatch、dither、gamut/tone + mapping 以及 custom/ICC/LUT shader API。未复制 D3D、OpenGL、FFmpeg、 + dav1d 等本实现不使用的公共头,保持 Exo Vulkan 资产范围最小。 +- 下一动作:在 native renderer 同时 include `vulkan.h` 与 `renderer.h`,以 + 双 ABI 编译确认头/归档契约,再实现 context、swapchain 与 AHB import。 + +## 19. E9-3d-device 目标设备验证 + +- 设备与产物:V2453A(Android API 35,序列号 `10CF6H1D2L0009S`)安装 + `app-mobile-arm64_v8a-debug.apk`;验证基线为 + `c943d7659bf9f03d2cf3cdaa670d5b82231168ca`。 +- 路由证据:开启内部播放实验与 Exo 域开关后,目标 DV5 样片实际选中 + `MediaCodecVideoRenderer-DV5-Vulkan`;native capability probe、Adreno + Vulkan 初始化和普通 HEVC `c2.qti.hevc.decoder` 创建均成功。 +- 失败分类:本次不是音频输出失败。`AudioTrack` 已完成初始化,Media3 最终 + 上报的是 `ERROR_CODE_VIDEO_FRAME_PROCESSING_FAILED`,异常链为 + `MediaCodecVideoRenderer-DV5-Vulkan -> VideoSinkException -> + DV5 Vulkan rendering failed`。应用当前把 output stage 显示成泛化的音视频 + 输出提示,容易让设备侧反馈误判为音频故障。 +- 真正阻断:native `renderImage()` 连续三帧返回 `false`,但当前失败出口没有 + 阶段日志,尚不能区分 AHB properties、external image 创建/绑定、 + `pl_vulkan_wrap`、swapchain、`pl_render_image`、submit 或 foreign queue hold。 +- 原始证据:设备完整 logcat 保存于 `/tmp/e9-dv5-full-logcat.txt`;关键错误位于 + 2026-08-27 20:07:31,renderer format 为 `dvhe.05.09`、3840x2160。 +- 验证结论:构建与 renderer 选择成立,但设备出帧和色彩验收失败;不得将本 + candidate 宣称为 DV5 正常播放。 +- 回滚锚点:`c943d7659bf9f03d2cf3cdaa670d5b82231168ca`。 +- 下一动作:为 `renderImage()` 增加有界的首个失败阶段与 AHB/Vulkan 格式日志, + 在同一设备复现后只修复首个确定失败的 native 契约。 + +## 20. E9-3d-render-fix 实施检查点 + +- 根因:目标设备返回 Android Vulkan `externalFormat` 时,旧实现仍把 + `formatProps.format` 写入 `VkImageCreateInfo.format` 和 libplacebo wrap。 + Android external-format image 必须使用 `VK_FORMAT_UNDEFINED`,实际格式由 + `VkExternalFormatANDROID.externalFormat` 描述;设备日志中的 + `Unsupported VkFormat: 1000330000...` 与此契约错误相符。 +- 修复:`renderImage()` 在 external format 非零时同时使用 + `VK_FORMAT_UNDEFINED` 创建/包装 image;保留 concrete format 路径不变。 + 所有失败出口增加首个阶段、`VkResult`、AHB geometry/format/usage、Vulkan + format/externalFormat/features、PTS 和 RPU 状态日志。 +- 误报修复:Media3 音频错误仍保持原 `OUTPUT` 分类;视频帧处理错误仍属于 + output stage,但 `PlayerManager` 根据精确错误码显示独立的“音频输出失败” + 或“视频输出失败”,不再把 DV5 Vulkan 错误提示成音频故障。 +- 验证:JDK 21 下 `:app:externalNativeBuildMobileArm64_v8aDebug` + `:app:externalNativeBuildMobileArmeabi_v7aDebug` 与 + `:app:compileMobileArm64_v8aDebugJavaWithJavac` 均 `BUILD SUCCESSFUL`。 +- 当前状态:尚未完成修复后目标设备播放验收;下一动作是用无构建缓存的 + arm64 debug APK 安装到 `10CF6H1D2L0009S`,复现同一 DV5 样片并检查首个 + `render failed stage=` 日志、`renderedFrames` 和错误提示。 + +### E9-3d-render-fix 设备复测检查点 + +- 检查点摘要:external-format 修复已安装;普通视频回归已排除;DV5 精确复测待执行。 +- 下一动作:启动应用,从当前历史列表点击 `P5_Dolby_Amaze.mkv`,读取首个 + `ExoDv5 render failed stage`。 +- Next action (guard): launch app and tap P5_Dolby_Amaze.mkv from history, then inspect first ExoDv5 render failed stage +- 分支/基线:`exo-dv5` / `38a4fdb84f3c28391c43f1a98f866960981046aa`; + 当前未提交范围仍为 native external-format 修复、精确输出错误文案与本文档, + 没有新增其它播放器行为。 +- 设备状态:V2453A(Android API 35,`10CF6H1D2L0009S`)在线;当前工作区 + `app-mobile-arm64_v8a-debug.apk` 已于 2026-08-27 20:46:29 重新安装。 +- 已排除:用户复核后确认普通视频播放正常,不存在实验 renderer 抢占非 DV5 + 轨道的回归;继续只处理 `dvhe.05.09` 样片。 +- 未完成:安装后的 DV5 样片尚未完成一次有效复测,因前一次自动点击命中了 + 历史列表中的其它条目,没有产生新的 `ExoDv5` 日志。 +- 下一动作:重新启动应用,读取当前历史列表 UI 坐标后精确点击 + `P5_Dolby_Amaze.mkv`,保存完整 logcat 和屏幕证据,并按首个 + `render failed stage=` 决定唯一下一处 native 修复。 + +### E9-3d-render-fix FIFO 时间戳修复检查点 + +- 已确认 RPU 解析成功,但目标设备的 `AImage` timestamp 是 monotonic clock, + 与媒体 PTS 不在同一时间域;旧代码精确比较两者导致每帧都误报 `missing-rpu`。 +- 已改为按 MediaCodec 输出顺序 FIFO 关联已排队的媒体 PTS,保留 AImage + timestamp 仅用于队列为空时的诊断;arm64 debug APK 已于 22:37 构建完成。 +- 工作区仍只包含既有 E9-3d native 修复、输出错误分类和本文档修改;Gradle + 生成的未跟踪 `app/.cxx` 已移至 `/tmp/e9-app-cxx-20260827-2237`,不纳入任务。 +- Rollback anchor:`38a4fdb84f3c28391c43f1a98f866960981046aa`。 +- Next action: install FIFO candidate and reproduce P5_Dolby_Amaze.mkv once, then fix only the first new native failure stage + +### E9-3d-render-fix 色彩修复检查点 + +- 设备复测已确认 FIFO candidate 可以稳定出帧,但画面接近全黑。 +- 根因已收敛到 RPU 状态映射:libdovi 的压缩 DM 对象不携带新的静态颜色 + 矩阵,当前实现却把其中的零字段写入 `pl_dovi_metadata`;同时没有继承 + `use_prev_vdr_rpu_flag` 指向的 reshape 状态,也没有向 libplacebo 传递 + RPU 的源 PQ 亮度元数据。 +- 修复边界:只调整 `exo_dovi_renderer.cpp` 的 RPU 状态继承、Profile 5 + 标准静态矩阵回退和 HDR 元数据映射,不改变 Exo/MPV 路由或其它格式行为。 +- Next action: implement compressed-DM inheritance and Profile 5 luminance mapping, then build and install one arm64 APK + +### E9-3d-render-fix 黑屏语义复核检查点 + +- DV5 black-output review: libplacebo/mpv standard path applies P5 RPU reshape; hand-mapped coefficient normalization matches upstream, so disabling mapping is unsupported. Current decisive uncertainty is Android external-format sampler channel/range contract versus first-frame RPU state. +- 已核对 libplacebo 7.375.0 的 `pl_map_dovi_metadata()` 与 shader:P5 的 RPU + mapping 会在颜色矩阵前执行;libdovi C API 的整数/小数系数组合与 FFmpeg + signed fixed-point 语义一致。`profile5.bin` 的零 luma 曲线只是单帧 fixture, + 不能据此把所有 P5 mapping 当成错误。 +- 下一动作:检查已保存的最新设备日志和 Android external-format 通道契约, + 只修复一个确定的 native 输入解释错误,然后执行 arm64 native build。 +- Inspect saved latest device log and external-format channel contract, then apply one minimal native fix and arm64 build + +### E9-3d-render-fix 当前候选构建检查点 + +- 当前 DM/RPU 色彩修复候选已通过 `:app:externalNativeBuildMobileArm64_v8aDebug` 与 `:app:assembleMobileArm64_v8aDebug`,APK SHA-256 为 `956e972b272ca219c4c48233000280af75fa5598171118fc0bb19ee970a0f5b7`。 +- 目标设备 `10CF6H1D2L0009S` 当前未连接,尚不能把编译成功表述为色彩修复通过。 +- 下一动作:设备上线后覆盖安装该 APK,播放 `P5_Dolby_Amaze.mkv` 并只读取 `ExoDv5`/renderer 定向日志。 +- Checkpoint: arm64 DV5 DM/RPU color candidate built successfully; device offline; app/.cxx preserved under /tmp +- Next action: install candidate on 10CF6H1D2L0009S and capture focused ExoDv5 playback logs + +### E9-3e HDR swapchain 日志根因与修复 + +- SurfaceFlinger 的目标设备现场状态确认 Exo DV5 Surface 使用 + `RGBA_1010102`,但 dataspace 仍为 `V0_SRGB`;同一设备声明支持 HDR10/PQ, + 最大亮度 800 nit。`color_bits=10` 只选择位深,不能替代 HDR 色彩空间声明。 +- 根因是 Exo Vulkan 路径没有像 mpv gpu-next 一样调用 + `pl_swapchain_colorspace_hint`,libplacebo 因而按默认 sRGB 创建 swapchain。 +- 最小修复是在已完成 DV reshape 的 BT.2020/PQ source 上调用 colorspace hint, + 再 resize/acquire swapchain;同时有界打印前四帧 source/target primaries、transfer、 + luminance 与输出位深,供设备日志和 SurfaceFlinger dataspace 双重确认。 +- 回滚锚点:`recovery/E9-3d-render-fix/20260828004539-eb1f827bfc7b`。 +- 设备验证:arm64 native 构建与 APK 打包成功,APK SHA-256 为 + `75d7cee2f3da73133ed8be65ab7ba184a4e4518ac9cecfd0ede17acab51b238b`; + 已覆盖安装到 V2453A 并精确播放 `P5_Dolby_Amaze.mkv`。 +- 日志结果:Exo 仍使用 `c2.qti.hevc.decoder`,RPU 为 Profile 5 且 mapping/DM + 均有效;前四帧 source/target 均为 BT.2020/PQ、10 bit、0.005-3999.7 nit, + 无 `render failed` 或 `VideoSinkException`。 +- 系统输出结果:SurfaceFlinger 将视频层标记为 `BT2020_PQ`,已从修复前的 + `V0_SRGB` 切换为 HDR 输出。日志层面的错误色彩空间根因已修复;不以截图或 + 主观画面对比替代用户的最终视觉验收。 + +### E9-3f RPU 时间戳域修复 + +- 复测日志发现恢复播放时首个渲染 PTS 为 `1000000000000`,而 pending RPU + 从 `1000055767000` 开始,差值约 55.8 秒,连续三帧因此命中 `missing-rpu`。 +- Media3 会通过 `VideoSink.setBufferTimestampAdjustmentUs()` 对输出帧做起始位置 + 修正;旧实现只修正 AImage timestamp,RPU 和 native FIFO 的媒体 PTS 仍使用原值。 +- 修复:RPU 入队、`nativeQueueFrame` 的 presentation PTS、AImage timestamp + 统一使用同一调整后的时间戳,覆盖 seek/恢复播放场景,不改变播放器路由。 +- 下一动作:编译安装并从历史入口再次播放 `P5_Dolby_Amaze.mkv`,确认不再出现 + `missing-rpu`,且 Exo 仍持续出帧。 + +### E9-3f 当前复测检查点 + +- 时间戳修复候选已通过 `:app:assembleMobileArm64_v8aDebug`,APK SHA-256: + `cd115cefb8acc2890488dc5de039d4fefd12cc2666520fb48a0c84147fde9c99`。 +- 已覆盖安装并启动到目标设备 `10CF6H1D2L0009S`;尚未播放样片。 +- 由于 guard 要求更换诊断路线,下一步只做一次精确历史条目播放并抓取 + `ExoDv5`/`VideoSink` 日志,判断时间戳修复是否消除 `missing-rpu`。 + +### E9-3f 失败复测结论 + +- 当前候选无效:首批 RPU 被调整为 `-432999` 至 `-299999` 微秒,自定义 + DV5 decoder 约 300 ms 后释放,随后普通 Exo renderer 才尝试连接仍由 Vulkan + 持有的 Surface 并报 `Failed to connect to surface`。没有发生 MPV 切换。 +- 已否定的假设:不能对 `DecoderInputBuffer.timeUs` 和 VideoSink 输出帧 PTS + 同时直接叠加 `bufferTimestampAdjustmentUs`;Media3 的输入时间戳已经包含 stream + offset,这种处理会制造负 RPU PTS,且未证明两个回调属于同一原始时间域。 +- 当前未提交候选不得完成或打标签。下一动作是读取首次 decoder 释放前后的完整 + 播放异常,确定 sink 退出原因,再用单一明确映射修正 RPU/帧配对。 +- Guard checkpoint message: 当前候选无效。 +- Guard next action: 读取首次 decoder 释放前后的完整播放异常,确定 sink 退出原因,再用单一明确映射修正 RPU/帧配对。 +- Checkpoint: 已撤销重复叠加 `bufferTimestampAdjustmentUs` 的无效候选;当前仅增加 + renderer stream/disable、sink adjustment 和首四帧 PTS 的有界日志,以确定首帧前 + custom renderer 被释放的直接原因。 +- Next action: 构建安装一次 arm64 debug APK,精确复现并读取 `ExoDv5` 定向日志。 + +- Compaction recovery: branch/HEAD and three task-owned dirty files match E9-3f checkpoint; generated app/.cxx is the only guard violation. +- Next action: Preserve app/.cxx outside worktree, capture one PID-bound all-buffer logcat reproduction, and fix only the first confirmed failure. + +- Checkpoint: A fresh device log confirms Exo's custom renderer receives valid Profile 5 + RPU metadata and renders without failures, but the target SurfaceView is not retained by + SurfaceFlinger as an HDR layer (`mIsHdrLayerPresent=false`). The renderer was advertising + a 4000-nit BT.2020/PQ target, so the compositor can display PQ values as SDR, producing the + reported near-black image. The current bounded fix changes only the swapchain hint to the + explicit sRGB color contract; DV5 IPT/RPU mapping and Exo routing remain unchanged. +- Next action: Build the arm64 debug APK, install once, replay `P5_Dolby_Amaze.mkv`, and read + only `ExoDv5` logs to verify the target contract is sRGB and rendering remains failure-free. + +### E9-3g SDR output contract correction + +- Root cause: the compatibility renderer advertised the decoded DV source itself as the + swapchain target (`BT.2020/PQ`, 0.005-3999.7 nit). That bypassed libplacebo output tone + mapping and depended on Android retaining and correctly mapping the custom Vulkan child + surface as HDR. The user-visible result on V2453A was an almost-black picture. +- Fix: retain raw Profile 5 sampling and per-frame RPU reshape, but request an explicit + sRGB/BT.709 swapchain target. libplacebo now performs the DV-to-display tone mapping before + presentation; Exo routing, MediaCodec selection, RPU parsing and component mapping are + unchanged. +- Build: `:app:assembleMobileArm64_v8aDebug` passed with JDK 17. APK SHA-256: + `cf01c3fc4ebbbce8833f7d066f23ac2a175731db9ae481f7a25038583139961b`. +- Device: installed on V2453A (`10CF6H1D2L0009S`) and launched + `P5_Dolby_Amaze.mkv`. The renderer remained Exo with `c2.qti.hevc.decoder`; RPU parsing and + initial frame scheduling succeeded, with no MPV switch, `VideoSinkException`, native render + failure or crash in the focused run. +- Output contract: SurfaceFlinger reports the active 3840x2160 video layer as + `dataspace=V0_SRGB`, display `colorMode=SRGB`, and SDR white point about 400 nit. This proves + the renderer no longer presents 4000-nit PQ as its final output and now performs GPU tone + mapping. Per the user's instruction, no screenshot or subjective image comparison was used; + final visual color acceptance remains user-observed. +- Rollback: revert this unit's commit/tag to restore the previous HDR10 swapchain hint without + changing the earlier RPU queue and timestamp fixes. + +- Replan: vivo shell `logcat` and application-UID `run-as logcat` both omit the App's Java/native playback logs even though the installed APK hash matches the local candidate; repeated logcat capture cannot identify the disable cause. +- Next action: replace the existing bounded `Log.i` probes with an App-private diagnostic file, reinstall once, and read that file after one P5 reproduction. + +- Checkpoint: App-private diagnostics prove the custom renderer parses 26 RPU units and receives one codec frame, but is stopped before AImage acquisition. Locked Media3 `VideoSink` sources require adding `bufferTimestampAdjustmentUs` inside `handleInputFrame` and using the resulting frame PTS for scheduling and the input Surface timestamp; the raw buffer PTS remains the RPU/native match key. +- Next action: store raw and adjusted PTS in `PendingFrame`, use adjusted PTS for scheduling/AImage timestamp, rebuild, install, and replay P5 once. + +- Checkpoint: a direct P5 episode click starts at zero and proves adjusted frame/position scheduling is correct. Three frames reach AImageReader and match RPU, but all native renders fail only after the candidate passed media PTS `0/17/33 ms` as `MediaCodec.releaseOutputBuffer` timestamps instead of absolute monotonic release times. +- Next action: keep adjusted frame/position scheduling and raw RPU matching, but restore monotonic `releaseTimeNs` for codec/AImage release, then rebuild and replay P5 from zero once. + +- Checkpoint: monotonic codec release timestamps now let three AImages reach native matching, but all three fail at `missing-rpu`. The decisive evidence is `parsedRpu=47`, `pendingRpu=16`, `rpuQueueDrops=17`: `pendingRpus` incorrectly shares the 16-entry output-frame bound, so decoder input pre-roll discards the earliest RPU metadata before the first output frame arrives. +- Next action: separate the RPU metadata queue bound from `expectedFrames`, preserve enough decoder reorder/pre-roll metadata, then rebuild and replay P5 from zero once. + +### E9-3f RPU 预滚队列修复与设备验收 + +- 根因:`pendingRpus` 错误复用了 `expectedFrames` 的 16 帧上限;MediaCodec + 输入预滚在首个 AImage 输出前已解析 47 至 49 个 RPU,旧策略持续丢弃队首, + 导致首帧对应的最早元数据被删除并命中 `missing-rpu`。 +- 修复:为 RPU 元数据使用独立的 256 项有界队列;队列极端溢出时保留最早、 + 即将被输出帧消费的元数据并丢弃最远未来项。`expectedFrames` 的 16 帧输出 + 匹配边界保持不变,flush/seek 仍同时清空两类队列。 +- 构建:`bash gradlew :app:assembleMobileArm64_v8aDebug` 成功;生成的未跟踪 + `app/.cxx` 已整体保留到 `/tmp/e9-cxx-20260828-2BckBs/app-cxx`。 +- 真机验收:候选 APK 已覆盖安装到 V2453A(`10CF6H1D2L0009S`),从选集入口 + 将 `P5_Dolby_Amaze.mkv` 从 0 秒播放约 42 秒。最终 stats 为 + `renderedFrames=2450`、`renderFailures=0`、`matchedFrames=2451`、 + `unmatchedFrames=0`、`rpuQueueDrops=0`、`malformedRpus=0`;日志无 + `missing-rpu`、`VideoSinkException` 或 `AndroidRuntime` 崩溃。 +- 色彩输出日志:source/target 均为 BT.2020/PQ,0.005 至 3999.7 nit、10 bit。 + 路径仍为 `MediaCodecVideoRenderer-DV5-Vulkan`,没有自动切换 MPV。 +- 原始证据:`/tmp/e9-dv5-rpu-queue-final-private.log` 与 + `/tmp/e9-dv5-rpu-queue-final-logcat.log`。 +- Next action: create the atomic E9-3f commit and annotated recovery tag. + +### Checkpoint 2026-08-28: external research batch, mpv backends all pass + +- 用户补充的设备事实:同一目标设备、同一 DV5 样片,MPV `gpu-next` 的 + `direct`、`stable`、`legacy` 三种 Vulkan AImageReader 后端均能稳定还原色彩。 +- 这条事实显著降低了“Android external-format、AHardwareBuffer 通道顺序、 + YCbCr sampler/range 或单一 Vulkan 后端”的可能性;三种后端共享的上游 + `mp_image -> libplacebo` Dolby Vision 表示更值得优先对照。 +- 已核对本地锁定 MPV `cca559b41ceb0bb7731cf6ef2e1f33276cd30c42`、FFmpeg + `04482c8d13ac27b2a9fe93f5d388929eef8af5f4`、libplacebo + `b694a21bf2dc176c1e98b8a13c6421a0de5f3da5` 及本地 stable override;MPV + `raw_dovi` 会保留原始 DV representation 和三分量语义,stable 另用固定 + 输出池/fence 保证 AImage 生命周期。 +- 外部 issue:mpv #10287 记录无 DV license 的 Snapdragon 设备在 + `mediacodec-copy` 下出现紫绿,而软件/gpu-next 映射正常;mpv #10700 记录 + P5 的错误颜色与 tone-mapping/backend 输入表示有关。这些支持“必须保留 + raw DV + RPU GPU mapping”,不支持 P5 直接改标 HDR10/P8.1。 +- 本轮仍为 assessment;未修改生产代码,保护脏文件 + `app/src/main/cpp/exo_dovi_renderer.cpp`。下一动作:抓取锁定 MPV direct、 + FFmpeg DOVI 状态更新和 libplacebo frame mapping 的完整源码,逐字段对照 + Exo 当前实现,形成推荐/否决矩阵。 +- External research confirms same DV5 sample is correct with MPV gpu-next direct, stable, and legacy; prioritize shared FFmpeg/libplacebo RPU representation and preserve existing dirty native file. +- Fetch locked MPV direct, FFmpeg DOVI state, and libplacebo mapping sources into /tmp and compare exact fields + +### Checkpoint 2026-08-28: narrow the remaining fault domain + +- Authority remains assessment-only for this batch; no production code has been changed. +- User-confirmed evidence: the same device and Profile 5 sample produce stable correct color + with MPV gpu-next `direct`, `stable`, and `legacy`. This rules against a defect unique to + one MPV AHardwareBuffer import backend and makes the shared FFmpeg/libplacebo Dolby Vision + frame representation the primary reference contract. +- Current strongest hypothesis: Exo's hand-built `pl_dovi_metadata` and simplified RPU + carry-forward/frame-selection semantics diverge from FFmpeg's stateful `DOVIContext`. + Counter-hypothesis: Exo feeds equivalent metadata and the remaining fault is output target + or resource lifetime. The next source comparison must distinguish these before any edit. +- Protected pre-existing dirty path remains + `app/src/main/cpp/exo_dovi_renderer.cpp`; do not overwrite or commit it during assessment. +- Next action: compare the locked FFmpeg DOVI parse/state functions and MPV/libplacebo frame + handoff field-by-field with Exo's current RPU parsing and render path, then record a + recommendation and acceptance/rollback boundary. + +### Checkpoint 2026-08-28: MPV 三后端证据后的有限对照 + +- 用户确认同一样片在 MPV gpu-next `direct`、`stable`、`legacy` 均稳定正常;因此不再把单一 + Vulkan/AHardwareBuffer 后端作为首要假设。 +- 锁定源码对照显示 MPV raw DV 路径使用 `pl_map_avdovi_metadata` 的完整 FFmpeg + `AVDOVIMetadata`,并读取 AImage dataspace;Exo 当前使用 libdovi 结果手工维护 + `pl_dovi_metadata`,且固定 RGB identity/full YCbCr 采样。这是当前最强的可证伪差异。 +- 未新增生产代码;受保护脏路径仍为 `app/src/main/cpp/exo_dovi_renderer.cpp`,本文件为任务记录。 +- 下一动作:完成不超过一批的外部主源码/issue核查,并在设备重新在线时仅读取当前 APK 的 + ExoDv5 私有日志,确认 target/dataspace/RPU 状态后再决定是否编辑代码。 + +### Checkpoint 2026-08-28: Exo 与 MPV 共享语义的最终收敛 + +- 用户确认同一样片在 MPV `direct`、`stable`、`legacy` 均为正常色彩,故排除某一种 + Vulkan/AHardwareBuffer 后端独有缺陷;三条路径共享的 FFmpeg Dolby Vision 状态和 + libplacebo raw-DV 表示是当前基准。 +- 已确认当前样片前几帧为 Profile 5、`use_prev_vdr_rpu=0`、每帧均有 mapping 与未压缩 + DM;完整 `vdr_rpu_id`/DM 继承仍是通用缺口,但不能单独解释本样片持续异常。 +- 已确认 libdovi Profile 5 默认 IPT-PQ 矩阵与 Exo 当前常量一致,不能替换为 FFmpeg 的 + 非 Profile-5 默认颜色矩阵。 +- 当前只剩三个有决定力的字段簇:libdovi 到 `pl_dovi_metadata` 的曲线系数映射、 + AHardwareBuffer 的实际 sample depth/crop、以及 swapchain 返回的真实 target 色彩合同。 +- 保护现有 `app/src/main/cpp/exo_dovi_renderer.cpp` 未提交时间戳匹配改动;本轮不修改 + 播放器路由、MPV 策略或其他模块。 +- 下一动作:逐字段核对上述三个字段簇,选择一个可由源码或设备日志证实的单一根因, + 再做最小 native 修复并进行一次 arm64 构建和一次目标设备播放验证。 +- Checkpoint: MPV三后端均正常,已排除单一Vulkan后端;当前仅核对曲线映射、sample depth/crop与swapchain target +- Next action: 逐字段核对三个字段簇并修复一个可证实根因 + +### E9-3h RPU pivot 差分解码修复 + +- 直接根因:Dolby Vision `pred_pivot_value` 在 RPU 中是差分编码。FFmpeg + `dovi_rpudec.c` 读取时逐项累加后保存绝对 pivot;libdovi C API 则暴露原始编码值。 + Exo 旧实现直接归一化每个原始值,导致多 pivot 帧的分段边界乱序,libplacebo + reshape 选中错误曲线。两 pivot 或特定曲线帧可能偶然接近正确,符合用户观察到的 + “约第 3 秒只有一瞬间色彩正常”。 +- 交叉证据:libdovi 自带 Profile 8.4 曲线为 + `63,69,230,256,256,37,16,8,7`,该序列只有作为差分累加才可能形成有序 pivot; + FFmpeg 锁定源码明确执行 `pivot += get_bits(...)`。 +- 修复:`mapRpuCurve()` 在按 BL bit depth 归一化前先累加并夹取 pivot,保持系数、 + Profile 5 矩阵、时间戳匹配、swapchain 输出和播放器路由不变。 +- 构建:`:app:assembleMobileArm64_v8aDebug` 成功,APK SHA-256 为 + `72fe4c5a391d4543d1473c36c954d52c26b2856d6f5dc2832835b9a88fc41893`;生成的 + `app/.cxx` 已整体保留到 `/tmp/e9-pivot-cxx.36DbvT/app-cxx`,未进入任务范围。 +- 回滚锚点:`recovery/E9-3-color-input/20260828074016-eb5f7af998d3`。 +- 真机:APK 已覆盖安装到 V2453A,并从本地选集播放 `P5_Dolby_Amaze.mkv`。 + 路径保持 Exo `c2.qti.hevc.decoder`,未切换 MPV;一轮统计为 + `matchedFrames=2433`、`unmatchedFrames=0`、`expectedQueueDrops=0`、 + `renderFailures=0`、`malformedRpus=0`。 +- 真机日志证明 RPU/帧配对和 Vulkan 渲染链稳定;最终视觉色彩仍以用户观察为准。 +- 证据:`/tmp/e9-pivot-private.log`、`/tmp/e9-pivot-logcat.log`。 + +### E9-3 DV5 切换 DV7 的 Surface 生命周期修复 + +- 复现:DV5 使用自定义 Vulkan renderer 播放后直接切到 DV7;DV7 已正确选择 + HDR10 fallback,但普通 HEVC decoder 配置时报 + `nativeWindowConnect ... Invalid argument (-22)` 和 + `ERROR_CODE_DECODER_INIT_FAILED`。刷新或重进播放后恢复。 +- 根因:track replacement 只调用 `ExoDv5GpuRenderer.onDisabled()` 并释放 DV5 + codec,没有调用 sink 的永久 `release()`;native Vulkan swapchain 因而继续连接 + 外层输出 Surface,阻止后续普通 `MediaCodecVideoRenderer` 连接。 +- 修复:codec 的 `super.onDisabled()` 完成后调用可复用的 `sink.disable()`,关闭 + native renderer、Vulkan swapchain 和 AImageReader,清空 pending frame 并重置渲染状态; + 保留 Java `outputSurface` 引用且不设置永久 `released`,使之后切回 DV5 时可重新初始化。 +- 验收:arm64 构建并安装后执行 DV5 -> DV7;日志中 `sink disable` 必须先于 DV7 + decoder configure,且不得再出现 Surface `-22` 或 decoder init failure。再切回 DV5 + 应重新初始化并出首帧。 +- 结果:`:app:assembleMobileArm64_v8aDebug` 成功并覆盖安装到 V2453A;设备私有日志 + 记录 `sink disable`,切换后的聚焦 logcat 未再出现 `nativeWindowConnect -22`、 + `Failed to connect to surface` 或 `ERROR_CODE_DECODER_INIT_FAILED`,用户确认复现流程 + 已恢复正常。DV5 停用前统计为 `matchedFrames=855`、`unmatchedFrames=0`、 + `expectedQueueDrops=0`、`renderFailures=0`。构建生成的未跟踪 `app/.cxx` 已完整保留到 + `/tmp/e9-dv7-surface-cxx.FeWxKI/app-cxx`,未纳入任务范围。 +- 回滚锚点:`recovery/E9-3-frame-rpu-match/20260828174850-e6a0ee439028`。 diff --git a/docs/P0-mpv-native-baseline.md b/docs/P0-mpv-native-baseline.md new file mode 100644 index 0000000000..e958eb87f8 --- /dev/null +++ b/docs/P0-mpv-native-baseline.md @@ -0,0 +1,149 @@ +# P0:MPV native 基线、等价提交与运行验收 + +## Recovery anchor + +- Objective: freeze the current MPV native build graph and establish a reproducible baseline before any P1/P2 native rebuild. +- Acceptance: current lock, patch/override set, both ARM ABI asset sets, ELF namespace, packaging markers, and existing MPV behavior are recorded; no source, lock, patch, or binary change is made in P0. +- Status: assessment complete; P0 has no code delta. P1/P2 implementation remains pending explicit user approval. +- Current workspace: branch `fongmi-sync`, HEAD `3ab9dc97b93a7425ce80135acc13ffb3678b2620`; protected pre-existing dirty paths are `.codex/scripts/task_guard.sh`, `AGENTS.md`, and `docs/agents-md-effective-constraints-review-2026-08-21.md`. +- Next action: user decides whether to approve the separately reversible P1/P2 native rebuild described in the master assessment. + +## 1. Decision packet + +- User decision: P0 baseline confirmation — recommended; no production code change. +- Lane: `assessment`; task guard: `P0-MPV-NATIVE-BASELINE`. +- Scope: `third_party/mpv-native-lock.json`, `scripts/build_mpv_native.sh`, `scripts/build_mpv_player_jni.sh`, `scripts/verify_mpv_native_assets.sh`, `third_party/patches/` MPV/FFmpeg patches, the AImageReader stable override, current two-ABI MPV assets, and the P0/P1/P2 records in the master assessment. P0 edits only this document and the master assessment index. +- Exclusions: no lock update, source checkout migration, patch deletion, JNI rebuild, native rebuild, APK publication, push, or change to App/runtime behavior. +- Rollback: revert the P0 documentation commit only. The native rollback anchor remains the committed asset/lock state at HEAD; no binary rollback is needed because P0 does not replace assets. + +P0 is atomic because it freezes the complete native dependency graph and verifies the existing packaged result without introducing a new behavior. The target upstream trees contain many equivalent commits, but a new hash is not by itself a missing WebHTV capability. P0 therefore records equivalence and runtime obligations; it does not cherry-pick the target trees. + +## 2. Frozen local baseline + +### 2.1 Source and toolchain identities + +| Input | Frozen value | Evidence | +| --- | --- | --- | +| Build framework / JNI reference | `FongMi/mpv-android@99a60ad2141d5ace94453590903c2c6b9a0a2443` | `third_party/mpv-native-lock.json` | +| MPV | `FongMi/mpv@cca559b41ceb0bb7731cf6ef2e1f33276cd30c42`, `0.41.0-940-gcca559b41` | lock and embedded asset marker | +| FFmpeg | `FongMi/FFmpeg@04482c8d13ac27b2a9fe93f5d388929eef8af5f4`, `9.0-fongmi` | lock and `libmv*` markers | +| libplacebo | `FongMi/libplacebo@b694a21bf2dc176c1e98b8a13c6421a0de5f3da5`, `7.375.0` | lock and embedded asset marker | +| Android | NDK `29.0.14206865` / r29, API level 24 | lock | +| Build tools | Meson `1.11.2`, Ninja `1.11.1.1` | lock | +| Network stack | curl `8.21.0`, nghttp2 `1.69.0`, MbedTLS `3.6.7`, statically linked | lock, verifier | +| Font stack | Harfbuzz `14.2.1`, fontconfig `2.18.2`, libxml2 `2.15.3`, statically linked | lock, verifier | + +Lock SHA-256: `cbfd1f4c925a6250a33f2b0de726adcd5830b6aa5d6c98366dd4db6a8460fc81`. + +### 2.2 Build and verification inputs + +The current build order is the one documented in [third_party/mpv-native-build.md](../third_party/mpv-native-build.md). The native output must contain exactly ten libraries per ABI: + +`libc++_shared.so`, `libmpv.so`, `libmvcodec.so`, `libmvdevice.so`, `libmvfilter.so`, `libmvformat.so`, `libmvutil.so`, `libmwresample.so`, `libmwscale.so`, and `libplayer.so`. + +The required local patch order is: + +1. `ffmpeg-webhtv-proxy-range.patch` +2. `ffmpeg-mediacodec-port-starvation.patch` +3. `mpv-stream-cb-disc-controls.patch` +4. `mpv-android-dovi-el-surface.patch` +5. `mpv-dovi-profile7-hdr10-base-layer.patch` +6. `mpv-audiotrack-truehd-channel-mask.patch` +7. `mpv-mediacodec-embed-timed-release.patch` +8. `mpv-mediacodec-embed-optional-osd.patch` +9. `mpv-mediacodec-output-timing-diagnostics.patch` +10. `mpv-android-vulkan-conversion-default.patch` +11. `mpv-android-vulkan-smart-backend.patch` +12. `mpv-android-vulkan-legacy-backend.patch` +13. `mpv-aimagereader-stable-flow.patch` +14. `mpv-matroska-segment-end.patch` + +The stable AImageReader override is `third_party/mpv-native-overrides/aimagereader-stable/video/out/hwdec/hwdec_aimagereader_vk_stable.c` plus its `.comp` shader. The verifier also enforces the generated 16x8 shader contract and rejects accidental standalone curl, nghttp2, fontconfig, Expat, or libxml2 libraries. + +Selected input hashes: + +| Path | SHA-256 | +| --- | --- | +| `scripts/build_mpv_native.sh` | `be36c235c57ab57c68d1ab2f5d48584690e7ba66dad18158e6af20c0def2dbe0` | +| `scripts/build_mpv_player_jni.sh` | `10d76c0177ac4cf7df8c4c0fc883f010ee52a9aaba69ce317b80c7a0b9c0fa98` | +| `scripts/verify_mpv_native_assets.sh` | `2bc4a6cd8c49699e65cda0f254e86e1277def053a34a828f5768f67b88962aec` | +| `ffmpeg-mediacodec-port-starvation.patch` | `3d61cb210b6eeb25373073c9c96783629b951178151848c7e96c2a59d191b48b` | +| `ffmpeg-webhtv-proxy-range.patch` | `df20c6fb3f6ee4837fcc12994b0f5fcb287c50ce62bdca96bb32c900e719d684` | +| `mpv-dovi-profile7-hdr10-base-layer.patch` | `e7efa84efc75b08f96040c2cd136b847de1e59fca96aa3716ae97844fdeb0c95` | +| `mpv-aimagereader-stable-flow.patch` | `ff0b78886abe7e5f03b2e46c45e885d888479f7d1f384513fc8a0c6f1d25d653` | +| stable AImageReader `.c` override | `e288333372285fe64572088fd942dcb01122c17da8a63bfee80db6b540fe70b9` | +| stable AImageReader `.comp` override | `c49240fd0a9aae5d1c40adf8501fc7828b7cd76522d31444e6ca92f1468f9a04` | + +### 2.3 Packaged asset hashes + +The committed assets were checked for both required ARM ABIs. The full ten-file manifest is retained by Git; the following `libmpv.so` and `libplayer.so` hashes provide the primary runtime/JNI identity, while the verifier covers every file and marker: + +| ABI | `libmpv.so` | `libplayer.so` | +| --- | --- | --- | +| `arm64-v8a` | `298d9c0159818ad6e3b2968190fddd365b93fd2295d2ceacfe2a1ca9122fa04c` | `aedfcb5bcce929cd08bdd113e2031945efc514f3ec4e21daaa39c5744d941bff` | +| `armeabi-v7a` | `b26654c4f50ad99aae6fba1024be4f5fc0201f97a79642db6c88edc4437f50ab` | `d146b4f7b5aa95f6768c5bae981bd2f01aaa5166e36d28e342b3789e0233b4b4` | + +## 3. Upstream equivalence and disposition + +The master assessment contains the exhaustive 24/7/27 commit ledger. P0 does not reapply any of these commits. Their current disposition is: + +- `mpv-android` 24 commits: 15 exact/semantic infrastructure equivalents are covered by the locked build; example-App, CI, and maintenance-only changes are skipped; Harfbuzz `7cc841e3b5e726c09376fb2e33d5f8e33e42f059` remains a conditional P4 input; shutdown serialization `f4c5d614d5f68d483b2e1889ffad11e513b877d2` remains a separate P4-1 candidate. +- `libplacebo` 7 commits: API 375, HDR validation, checked DV mapping, `disable_storage`, and raw external YUV are covered by the current locked tree; alpha preservation `22ee762e8e0890fc54068beb670310f0edce7263` is a P1 candidate; shader-object helper `c78c4b4a5336473ff169ed2017a4535deed63d50` is dependency-only for P2. +- `mpv` 27 commits: helper schemes, ISO, rewind, curl Range/worker, MMT/TLV, artwork, live status, TTML, playback/GPU/HDR主体 are covered and require runtime confirmation; packed RGB10 `7b8915bc1d04c7e1b61184e00c7fbfaab1911e75`, EBML defaults `52bb166f309c8bb55ab34b2b0bc5c8ead05370e4` + `e167836802da6d5a4301bd4c4eeb3c5c3c17ccb8`, HLS edition `e7191f2a65d64af266c5c80793e79d2f4b92b789`, and DV7 metadata/codecpar safety `44755d7eaa0f186e4052ffc99c4f0b500a05a2ba` are separate P1/P2 candidates. Android BL+EL and other maintenance-only items remain deferred/skipped. + +This disposition is evidence-backed by the full tree/diff mapping in master assessment checkpoint 42. It deliberately distinguishes “covered by local code or locked tree” from “same subject” and from “safe to cherry-pick.” + +## 4. Best-practice review + +The review question was: can WebHTV treat the target MPV trees as a direct replacement, or must it preserve a locked, patched, two-ABI graph and validate behavior before any rebuild? + +| Evidence | Revision/access | Claim and decision impact | +| --- | --- | --- | +| WebHTV native build and verifier | `third_party/mpv-native-build.md`, `scripts/verify_mpv_native_assets.sh`; 2026-08-28 | The product consumes committed assets, requires `libmv*`/`libmw*` namespace separation, and has explicit local DV/Vulkan/Range/JNI safeguards. Direct tree replacement is rejected. | +| mpv contribution guide | `https://github.com/mpv-player/mpv/blob/master/DOCS/contribute.md`, current `master`, accessed 2026-08-28 | Upstream asks contributors to test changes, disclose when they did not test, and split independent changes into logical commits. P0 therefore keeps equivalence records and separate P1/P2 rollback units. | +| FFmpeg developer guide | `https://ffmpeg.org/developer.html`, accessed 2026-08-28 | Changes should preserve buildability and carry suitable tests/regression handling. P0 requires deterministic verifier/ELF evidence before native rebuild. | +| FFmpeg FATE | `https://ffmpeg.org/fate.html`, accessed 2026-08-28 | Regression tests can be run as a complete suite or targeted subset. P0 uses targeted native/package checks and reserves format-specific playback for the stage that changes it. | +| Android testing guide | `https://developer.android.com/studio/test`, accessed 2026-08-28 | Android behavior requires choosing local, instrumented, emulator, or device tests according to the behavior. P0 records device/runtime cases as acceptance obligations rather than claiming asset-marker checks prove playback. | +| SLSA v1.0 | `https://slsa.dev/spec/v1.0/`, accessed 2026-08-28 | Build provenance must connect source inputs and produced artifacts. P0 records lock, toolchain, patch order, hashes, and artifact identities before any rebuild. | +| GitHub release management | `https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository`, accessed 2026-08-28 | Binary assets should be attached to a deliberate tagged release and immutable-release workflow. P0 does not publish or push assets; candidate publication remains a later approved stage. | + +Applicable evidence classes are all covered: exact upstream commits and local diffs are in the master ledger; official project/platform/build-provenance guidance is listed above; maintainer/contributor expectations are represented by the mpv/FFmpeg contribution documents; mature related tests are represented by FFmpeg FATE and the Android testing model. No additional external research could change the P0 decision because P0 changes no runtime or dependency input. + +## 5. Alternatives and recommendation + +| Alternative | Result | +| --- | --- | +| No change, with no baseline record | Rejected: it leaves the current asset provenance and equivalent-commit boundary implicit, making a later native rebuild hard to attribute or roll back. | +| Directly point the lock at the latest upstream trees | Rejected: it would mix rebase-equivalent commits with real deltas and risks dropping WebHTV patches, ELF renaming, JNI ownership, or Surface/fence behavior. | +| P0 baseline freeze, then narrow P1/P2 adaptations | Recommended: preserves current behavior, makes each native topic independently reversible, and keeps the Exo→MPV order. | + +### P0 acceptance criteria + +1. `bash scripts/verify_mpv_native_assets.sh --require-elf` passes for `arm64-v8a` and `armeabi-v7a`. +2. The verifier uses NDK r29 `llvm-readelf`, confirms all required SONAMEs and `DT_NEEDED`, and rejects unrenamed FFmpeg or accidental dynamic network/font dependencies. +3. Lock, toolchain, patch/override set, and primary asset hashes are recorded above. +4. No P0 source, lock, patch, JNI, APK, or native asset changes are present. +5. P1/P2 remain separate user-approved implementation decisions; P2-3/P2-4, P3, P4, and C2 are not silently enabled. + +## 6. Validation result + +Command run once on 2026-08-28: + +```text +bash scripts/verify_mpv_native_assets.sh --require-elf +``` + +Result: PASS. The script reported the stable Vulkan shader contract (`16x8`, CPU-precomputed UV transform), verified both ARM ABI asset sets, used `/Users/macbookpro/Downloads/bizhi/android-sdk/ndk/29.0.14206865/toolchains/llvm/prebuilt/darwin-x86_64/bin/llvm-readelf`, and confirmed that all committed MPV native assets match lock versions and packaging rules. + +The worktree remained limited to the three protected pre-existing dirty paths plus the two documentation paths in this task. No build, network fetch, native command, or binary replacement was required for P0. + +## 7. Checkpoint 47 — 2026-08-28 + +- Completed: P0 baseline packet, source/patch/asset identity capture, upstream equivalence disposition, best-practice review, and ELF/package verification. +- Source identities: lock MPV `cca559b41ceb0bb7731cf6ef2e1f33276cd30c42`, FFmpeg `04482c8d13ac27b2a9fe93f5d388929eef8af5f4`, libplacebo `b694a21bf2dc176c1e98b8a13c6421a0de5f3da5`, mpv-android `99a60ad2141d5ace94453590903c2c6b9a0a2443`; target commit ledgers remain in master checkpoint 42. +- Workspace: branch `fongmi-sync`, HEAD `3ab9dc97b93a7425ce80135acc13ffb3678b2620`; protected dirty paths unchanged. +- Files changed: this task document and the P0 row/status in the master assessment; no locks, patches, scripts, assets, APKs, or JNI outputs. +- Validation: `bash scripts/verify_mpv_native_assets.sh --require-elf` passed for both ABIs with NDK r29 `llvm-readelf`. +- Rollback anchor: HEAD `3ab9dc97b93a7425ce80135acc13ffb3678b2620` and its existing recovery tags; documentation commit can be reverted independently. +- Unresolved: no device playback manifest was available in this assessment; runtime playback remains a prerequisite for any later P1/P2 candidate, not a P0 failure. +- Next action: request explicit approval for P1/P2 native implementation, then open a new `upstream` task-guard session with an approved source/lock/artifact scope. diff --git a/docs/P1-mpv-format-shader-correctness.md b/docs/P1-mpv-format-shader-correctness.md new file mode 100644 index 0000000000..8c8380f043 --- /dev/null +++ b/docs/P1-mpv-format-shader-correctness.md @@ -0,0 +1,193 @@ +# P1:MPV 格式与 shader correctness + +## Recovery anchor + +- Objective: implement the approved first MPV native rebuild with four narrow correctness fixes while preserving current playback, ABI, and performance contracts. +- Acceptance: the four source patches apply after all existing WebHTV patches; both ARM ABIs rebuild from the locked graph; native ELF/package checks and focused playback/rendering checks pass; exact source, artifact, commit, tag, and rollback records are written here. +- Status: implementation committed and tagged; build/package/device smoke and user multi-disc regression checks passed, while four P1-specific fixtures remain optional follow-up evidence. +- Task ID/lane: `P1-MPV-FORMAT-SHADER-CORRECTNESS` / `upstream`. +- Workspace: branch `fongmi-sync`, HEAD `42f7f54cd0da748b0f2fbad5faab3869fe19f50a`. +- Baseline recovery tag: `recovery/P1-MPV-FORMAT-SHADER-CORRECTNESS/baseline-20260828-1246`. +- Implementation guard: active `upstream` session with declared build script, lock, four patch, two ABI asset, and this document paths. +- Protected pre-existing dirty paths: `.codex/scripts/task_guard.sh`, `AGENTS.md`, `docs/agents-md-effective-constraints-review-2026-08-21.md`. +- Next action: treat P1 as complete; exercise the four dedicated RGB10/EBML/HLS/alpha fixtures only when matching samples are available, or continue with the next approved upstream task. + +## 1. Decision packet + +### Question + +Should WebHTV's first controlled MPV native rebuild add packed 10-bit RGB format identity, Matroska EBML default handling, HLS program-level edition selection, and libplacebo alpha preservation, while retaining the existing FFmpeg namespace, Vulkan/AImageReader, Dolby Vision, Matroska seek, AudioTrack, OSD, and two-ABI contracts? + +Current hypothesis: these are narrow correctness fixes with visible input or rendering value and no App/JNI API change. Counter-hypothesis: one or more changes may be incompatible with WebHTV's generated Matroska descriptors, program metadata, packed-format interpretation, or transparent OSD/shader behavior and therefore should be adapted or deferred. + +### Scope and authority + +- Assessment-only changes: this document and the P1 row/recovery text in `docs/upstream-player-dependency-merge-assessment-2026-08-20.md`. +- Candidate repositories: `FongMi/mpv` and `FongMi/libplacebo`; source range and full commit identities are listed below. +- Implementation scope, if approved later: `third_party/mpv-native-lock.json`, the corresponding MPV/libplacebo source/patch inputs, both ARM native asset sets, and only the tests/build records required by the approved substage. `libplayer.so`, App Java/Kotlin APIs, and Exo AARs are excluded. +- No lock update, source checkout migration, native rebuild, APK publication, push, or local production patch is authorized by this assessment. + +## 2. Complete candidate ledger + +| Substage | Full commit | Disposition | Decision boundary | +| --- | --- | --- | --- | +| P1-1 packed RGB10 RA | `7b8915bc1d04c7e1b61184e00c7fbfaab1911e75` | candidate; recommend narrow merge | `video/out/placebo/ra_pl.c`; add `X2BGR10`/`X2RGB10` special format identity only | +| P1-2 EBML generator prerequisite | `52bb166f309c8bb55ab34b2b0bc5c8ead05370e4` | dependency-only within P1-2; do not release alone | `TOOLS/matroska.py`; required so generated descriptors can carry defaults | +| P1-2 EBML defaults | `e167836802da6d5a4301bd4c4eeb3c5c3c17ccb8` | candidate; recommend narrow merge with `52bb...` | `TOOLS/matroska.py`, `demux/ebml.c`, `demux/ebml.h`; zero-length values use EBML/RFC/context defaults | +| P1-3 HLS edition | `e7191f2a65d64af266c5c80793e79d2f4b92b789` | candidate; recommend merge with metadata fallback gate | `demux/demux_lavf.c`; select by program `variant_bitrate` before any compatibility fallback | +| P1-4 libplacebo alpha | `22ee762e8e0890fc54068beb670310f0edce7263` | candidate; recommend搭载 | `pl_shader_extract_features()` preserves extracted alpha instead of forcing `1.0` | + +The master assessment records the parent/tree and patch-id evidence for all five commits (checkpoint 34 and checkpoint 42.4). The two EBML commits are one implementation unit; the generator prerequisite has no independent runtime value. + +## 3. Current WebHTV baseline and contracts + +- Native graph is pinned by `third_party/mpv-native-lock.json`: MPV `cca559b41ceb0bb7731cf6ef2e1f33276cd30c42`, FFmpeg `04482c8d13ac27b2a9fe93f5d388929eef8af5f4`, libplacebo `b694a21bf2dc176c1e98b8a13c6421a0de5f3da5`, mpv-android `99a60ad2141d5ace94453590903c2c6b9a0a2443`, NDK r29/API 24, and both `arm64-v8a`/`armeabi-v7a` assets. +- MPV FFmpeg libraries use the `libmv*`/`libmw*` SONAME and `DT_NEEDED` namespace; Exo keeps separate `libav*`/`libsw*` assets. Any approved P1 rebuild must rebuild the coherent graph and preserve this separation. +- Existing local behavior that must remain: `mpv-matroska-segment-end.patch` for seek metadata, `mpv-dovi-profile7-hdr10-base-layer.patch` and DV BlockAdditional handling, `mpv-android-vulkan-{conversion-default,smart-backend,legacy-backend}.patch`, the stable AImageReader override/fence ownership, optional OSD and timestamped MediaCodec release, TrueHD 7.1 workaround, FFmpeg starvation/Range patches, and the ten-library per-ABI packaging contract. +- P0 verification has already passed once at HEAD: `bash scripts/verify_mpv_native_assets.sh --require-elf` checked both ABIs, NDK r29 `llvm-readelf`, shader contract, markers, SONAME/`DT_NEEDED`, and package contents. That result is the baseline, not proof that P1 behavior is implemented. +- App already exposes `hls-bitrate`/automatic bitrate policy and consumes Matroska track/chapter/metadata and subtitle/OSD output. P1 does not change these APIs; it changes native parsing/selection/format identity beneath them. + +## 4. Substage decisions + +### P1-1: packed RGB10 RA identity + +The locked libplacebo API already describes Vulkan `rgb10a2`/`bgr10a2`; the gap is mpv's libplacebo RA wrapper not recognizing packed `IMGFMT_X2BGR10` and `IMGFMT_X2RGB10` as special formats. The proposed hunk adds one-plane RGB descriptors with explicit channel order. + +Recommendation: merge as a narrow mpv change, only in the first controlled native rebuild. It should be exercised through Vulkan direct, stable, generic/conversion, and automatic fallback, then compared with OpenGL `gpu-next`. The key failure mode is red/blue reversal or HDR gradient distortion on little-endian packed layouts. No local Vulkan backend or shader ownership patch may be removed. + +### P1-2: EBML zero-length/default semantics + +The current parser rejects or empties some legal zero-length EBML elements. The upstream pair adds generated `context_default` descriptors and parser handling so explicit zero length, missing element, and explicit non-zero value remain distinguishable. Context-derived `DisplayWidth`/`DisplayHeight` and `OutputSamplingFrequency` must continue to use existing demux fallback rather than being written as zero. + +Recommendation: merge both commits as one unit. The fixture must cover header defaults, `TimecodeScale`, track flags/language/lacing, display dimensions, sampling/channels, colour, `BlockAddID`/DV, content encoding, chapters, and tags, each in missing/zero-length/explicit forms. Keep the local segment-end seek and DV BlockAdditional paths intact. A failure rolls back only P1-2. + +### P1-3: HLS program-level edition selection + +The App already sets `hls-bitrate`; the current native selection can read a per-stream bitrate that is absent or misleading when variants share audio/subtitle groups. The candidate reads FFmpeg's program-level `variant_bitrate` metadata and ignores empty programs. + +Recommendation: merge after recording actual FFmpeg 9.0-fongmi behavior when program metadata is absent. The default rule is program metadata first; only if the complete program set lacks usable metadata may a WebHTV-adapted stream fallback be added. Preserve explicit edition selection and `flatten-editions`. Validate threshold boundaries, shared groups, audio-only and empty programs, invalid/missing metadata, and dynamic App reload from 15 Mbps to 8 Mbps. + +### P1-4: libplacebo alpha preservation + +The candidate changes `pl_shader_extract_features()` so alpha extracted from the shader feature set is not overwritten with `1.0`. This is a small shader correctness change relevant to transparent subtitle/OSD overlays and screenshots; it does not change libplacebo API level. + +Recommendation:搭载 with P1, but keep its source hunk and test evidence independently reversible. Validate transparent OSD/subtitle compositing, alpha overlays, HDR shader paths, screenshots, and both OpenGL and Vulkan output. A regression must not be “fixed” by disabling alpha globally. + +## 5. Best-practice evidence + +The mandatory research was completed in the master assessment checkpoints 5, 34, 42, and the upstream-integration-governor evidence record. It was not repeated because source heads and local contracts are unchanged. + +| Claim | Source/revision | Grade | WebHTV applicability and impact | +| --- | --- | --- | --- | +| The five commits are real endpoint-tree deltas, not merely rebase duplicates | `docs/upstream-player-dependency-merge-assessment-2026-08-20.md`, checkpoints 5.2, 34, 42; full hashes above; accessed 2026-08-28 | A | Supports a narrow P1 stage while leaving covered API-375 and Android GPU behavior untouched | +| MPV contribution changes should be split, tested, and accompanied by disclosed test scope | `https://github.com/mpv-player/mpv/blob/master/DOCS/contribute.md`, current `master`, accessed 2026-08-28 | B | Requires four independently attributable substages and no claim beyond the selected playback matrix | +| FFmpeg/container changes need deterministic regression coverage | `https://ffmpeg.org/developer.html` and `https://ffmpeg.org/fate.html`, accessed 2026-08-28 | A/B | Drives synthetic EBML fixtures and explicit HLS/Matroska regression cases rather than a build-only gate | +| Android behavior requires tests matched to the affected behavior and device path | `https://developer.android.com/studio/test`, accessed 2026-08-28 | A | Packed RGB/alpha and native selection require APK/device evidence; verifier output alone is insufficient | +| Native artifacts need reconstructable source/toolchain/provenance and ABI identity | `https://slsa.dev/spec/v1.0/` and current `third_party/mpv-native-build.md`, accessed 2026-08-28 | A | Any implementation must rebuild both ABIs from the declared lock, preserve SONAME/DT_NEEDED, and retain artifact hashes | + +Inapplicable categories: no new App API, JNI contract, or security boundary is proposed in P1, so no separate API migration or threat-model stage is needed. Device-specific rendering and HLS metadata uncertainty remain implementation gates, not assumptions. + +## 6. Alternatives + +| Alternative | Result | +| --- | --- | +| No change | Keeps the known-good native assets, but leaves legal EBML zero-length inputs, packed RGB10 identity, program-level HLS selection, and alpha extraction gaps unresolved. Acceptable only if no P1 rebuild is approved. | +| Adopt the upstream commits/tree wholesale | Rejected. It risks dropping WebHTV's Vulkan/AImageReader ownership, DV7 packet/Surface safeguards, Matroska segment seek, FFmpeg namespace, and local AudioTrack/OSD behavior. | +| Narrow WebHTV-adapted P1 | Recommended. Carry the five commits as four independently testable source units, add the HLS metadata fallback only if evidence requires it, and preserve the current native graph and rollback boundaries. | + +## 7. Acceptance and rollback + +Before implementation approval, acceptance criteria are: + +1. User explicitly approves the P1 source/lock/artifact stage; no code is changed before that approval. +2. P1 rebuild uses one declared FFmpeg revision for MPV, reapplies all MPV-specific patches, and rebuilds both ARM ABIs as a coherent graph. `libplayer.so` remains unchanged unless a later API diff proves otherwise. +3. `scripts/verify_mpv_native_assets.sh --require-elf` passes once for the candidate assets, including version markers, shader contract, SONAME/`DT_NEEDED`, static dependency rules, and package manifest. +4. P1-1 passes packed RGB10 red/green/blue order, 10-bit gradient, HDR/LUT, Vulkan direct/stable/generic/auto, and OpenGL comparison checks. +5. P1-2 passes missing/zero-length/explicit EBML fixtures, DAR/timebase/audio/chapter/tag behavior, DV `BlockAddID`, segment-end seek, and subtitle/track selection checks. +6. P1-3 passes shared audio/subtitle groups, audio-only/empty programs, metadata missing/invalid cases, bitrate threshold boundaries, explicit edition, `flatten-editions`, and dynamic reload checks. +7. P1-4 passes transparent subtitle/OSD/overlay and HDR shader screenshot checks on both rendering families. +8. Lock, patch order, source identities, artifact hashes, device/API/GPU/settings, logs, and per-substage results are recorded before commit/tag. + +Rollback is one native candidate rollback to the P0 asset/lock state. Within the candidate source tree, remove only the failing P1 hunk/unit: P1-1 RA mapping, P1-2 both EBML commits, P1-3 edition selection/fallback, or P1-4 alpha extraction. Never roll back by deleting the shared FFmpeg namespace or local Vulkan/DV/Matroska safety patches. + +## 8. Approval gate and next action + +This document recommends approval of P1-1, P1-2, P1-3, and P1-4 for one controlled MPV native rebuild, with separate source commits, tests, results, and rollback notes. It does not authorize implementation. P2 generic UV/DV7, P3 AudioTrack mask, P4 JNI shutdown, Android BL+EL, C2 DV7 conversion, and maintenance-only items remain separate decisions. + +Next action: wait for explicit user approval; if approved, start a new `upstream` task-guard session declaring the exact lock, patch, source, two-ABI asset, and verification paths. + +## 9. Assessment validation + +Validated on 2026-08-28 at HEAD `98f872eed700213ce03345d7d20d794c8ec4123a`: + +- `git diff --check` passed. +- `bash .codex/scripts/task_guard.sh check` passed for `P1-MPV-FORMAT-SHADER-CORRECTNESS`; only the two declared documentation paths are task-owned, and the three pre-existing dirty paths remain protected. +- `bash .codex/skills/upstream-integration-governor/scripts/verify_upstream_checkpoint.sh docs/upstream-player-dependency-merge-assessment-2026-08-20.md` passed with zero errors/warnings, including 436 unique full commit IDs and the latest recovery anchor. +- Static checks confirmed the unique P1 document exists, the master index links it, and all five P1 source commits are recorded with full 40-character identities. + +## 10. Implementation progress + +### 2026-08-28 source integration checkpoint + +- User approval: approved implementation with the explicit condition that current functionality and performance must not regress. +- Local baseline: `42f7f54cd0da748b0f2fbad5faab3869fe19f50a`; baseline tag `recovery/P1-MPV-FORMAT-SHADER-CORRECTNESS/baseline-20260828-1246`. +- Source strategy: retain the existing MPV `cca559b41ceb0bb7731cf6ef2e1f33276cd30c42` and libplacebo `b694a21bf2dc176c1e98b8a13c6421a0de5f3da5` locks; apply only the approved upstream deltas as four local patches. No MPV/libplacebo branch-head upgrade, FFmpeg lock change, JNI change, or App API change is included. +- Patch provenance and SHA-256: + - `mpv-p1-packed-rgb10.patch`: `FongMi/mpv@7b8915bc1d04c7e1b61184e00c7fbfaab1911e75`; `47aae2b7dda83a0c9216a528721e3ae85355d4304f27511d0bd738adcb8e8d5d`. + - `mpv-p1-ebml-defaults.patch`: inseparable delta from `FongMi/mpv@52bb166f309c8bb55ab34b2b0bc5c8ead05370e4` and `FongMi/mpv@e167836802da6d5a4301bd4c4eeb3c5c3c17ccb8`; `4bbc22014242eb182ba3a479d17250a39a48621ed3345a22531584d84d8301ff`. + - `mpv-p1-hls-edition.patch`: `FongMi/mpv@e7191f2a65d64af266c5c80793e79d2f4b92b789`; `a0bfaf35e30ffb9eb187943ba4a73c125cbf9293f596b68f87d5e560ee120425`. + - `libplacebo-p1-alpha.patch`: `FongMi/libplacebo@22ee762e8e0890fc54068beb670310f0edce7263`; `1a077fe46235df90347348fabac2e56c81361b2ddecb962135dacbeea8d75ba8`. +- Build-script compatibility correction: the pre-existing `mpv-mediacodec-embed-timed-release.patch` has stale hunk counts and a clean rebuild failed at line 291 before reaching P1. `scripts/build_mpv_native.sh` now applies that unchanged patch with `git apply --recount`, matching the existing DV7 patch handling. This changes patch parsing only and preserves the timed-release source delta byte-for-byte. +- Completed evidence: `bash -n scripts/build_mpv_native.sh` passed; all 15 MPV patches passed a strict ordered apply test from the locked MPV tree; `bash scripts/build_mpv_native.sh --abi all --prepare-only` passed from the repository cache and applied the locked sources and all patches in the production build order. +- Unverified worktree edits: build script, four new patch files, and this document. No lock, App/JNI, or committed native asset has changed yet. +- Remaining risks: compilation, ELF/package identity, both ABI artifacts, APK packaging, and device-visible RGB10/EBML/HLS/alpha behavior are not yet verified. +- Next action: run one clean `bash scripts/build_mpv_native.sh --abi all --install`, then run the native asset verifier before any commit. + +### 2026-08-28 two-ABI native candidate checkpoint + +- Clean rebuild: `bash scripts/build_mpv_native.sh --abi all --install` compiled and linked the locked graph for `arm64-v8a` and `armeabi-v7a`, including the generated EBML descriptors, HLS demux path, packed RGB10 RA mapping, libplacebo shader path, and all retained Android Vulkan/AImageReader/MediaCodec/AudioTrack sources. +- Install-end anomaly: after both candidate sets had been copied, the command exited `1` because the final duplicate `verify_directory` call reported that armeabi-v7a `libmpv.so` did not depend on `libmvcodec.so`. The staged output and installed assets are byte-identical, current `llvm-readelf -d` shows the required `libmvcodec.so` dependency, and the same exact match could not be reproduced. No verifier relaxation or speculative script change was made. +- Decisive native verification: one independent `bash scripts/verify_mpv_native_assets.sh --require-elf` pass succeeded for both ABIs. It verified the stable Vulkan shader contract, locked version markers, ELF class/machine, SONAME/`DT_NEEDED` namespace, required local patch markers, and packaged asset rules with NDK r29 `llvm-readelf`. +- Candidate `libmpv.so` SHA-256: arm64-v8a `69e9a8d10560a41107680ca4de737996885f2f37fa353fd5ede30334866eeb7b`; armeabi-v7a `ec2cbc58616bb383eb2f80d3fde883da02036b00062287a6f956ebda1aeb5ce3`. +- Preserved contracts: `third_party/mpv-native-lock.json` has no diff; arm64-v8a `libplayer.so` remains `aedfcb5bcce929cd08bdd113e2031945efc514f3ec4e21daaa39c5744d941bff`; armeabi-v7a `libplayer.so` remains `d146b4f7b5aa95f6768c5bae981bd2f01aaa5166e36d28e342b3789e0233b4b4`. +- Guard state: `bash .codex/scripts/task_guard.sh check` passed after installation; protected pre-existing dirty paths remain outside task scope. +- Remaining risks: App packaging and device-visible packed RGB10 colour order, EBML defaults, HLS edition selection, and transparent alpha behavior have not yet been exercised. The non-reproduced install-end verifier anomaly is retained as build-script reliability evidence but does not change the verified artifact contract. +- Next action: build `MobileArm64_v8aDebug`, `LeanbackArm64_v8aDebug`, and `LeanbackArmeabi_v7aDebug` once against these exact assets. + +### 2026-08-28 package and device checkpoint + +- Targeted App build: one Gradle invocation built `:app:assembleMobileArm64_v8aDebug`, `:app:assembleLeanbackArm64_v8aDebug`, and `:app:assembleLeanbackArmeabi_v7aDebug`; result `BUILD SUCCESSFUL in 3m 52s` with 208 actionable tasks (28 executed, 3 from cache, 177 up-to-date). +- APK SHA-256: Mobile arm64-v8a `a45e0eab9a419da42eaa6dea9c95e9b4f93190bdca2f70bb14d9ff3c3a5107fb`; Leanback arm64-v8a `eaaeb88effdf4dad21f2998ed929148d10d11d31ad63ede9e0b56b81bce3791b`; Leanback armeabi-v7a `482edbcdf7a98eb5bfd12a945670e0063a5f366d9e84551d6656e746e83bb9c0`. +- Packaging identity: every `assets/mpv-libs//*.so` entry in all three APKs was compared byte-for-byte with the corresponding candidate asset and matched. +- Final native asset SHA-256 manifest: + +| Asset | arm64-v8a | armeabi-v7a | +| --- | --- | --- | +| `libc++_shared.so` | `c4c2fe5cbcb1fba0003a31fc7ab29a9bb12df6cc187ec45a806462540e83d93b` | `af383654daf4cf0829615460419a180f84edd9d8bf51aa0f81ed0db811bf8491` | +| `libmpv.so` | `69e9a8d10560a41107680ca4de737996885f2f37fa353fd5ede30334866eeb7b` | `ec2cbc58616bb383eb2f80d3fde883da02036b00062287a6f956ebda1aeb5ce3` | +| `libmvcodec.so` | `dd0df8e451f34d1f1f04e829d5e3c54415ecfd100e1da185ba99400672a356ce` | `057737104206f1091f1e498f09112f6fa4786a126b1699d477a2a3f9227c53ef` | +| `libmvdevice.so` | `6e1eb48c069a2a5a9d2668048a8fcde47d8638d815ed8486d755a9c7ef811c1d` | `67054a2f81bbfce49f2089819224dfcbf1f67dcb1a92581b7b5116efdd651605` | +| `libmvfilter.so` | `15ecd2e2b6e9856377dfdf788aaffd4e13baf3aacb143fe12a81a7218e35dfeb` | `ee6a911db507f1314d6215582ed2166c86f7c01067d1a8672b0c97d56c5590ed` | +| `libmvformat.so` | `d452ca2a0ac2d81eb31176b454d0a4c641f4ae776c4b2549dac0f705c0816b77` | `fb64b119a50abdf5d83b7b7c3283b25bcaefa0c86a440eab806a7aba1f06ad1a` | +| `libmvutil.so` | `36809585992a694ccefe28194f49b9313ce431c5c008dabb15296f2be3d3de2c` | `92c75297d4bb6ab0486ffef09065ed74762eefd41e1a0ba33d0f77484122d821` | +| `libmwresample.so` | `abd917e5ed21a302fd61957f093c4f289854dc6b33d2849077919ab35bc2b1d9` | `fb96fa91e7fde0a537333ab7061e438dc606e738b4fa2d805feae02ce8686442` | +| `libmwscale.so` | `4228aacfc2992b9b66943e6050ee59e679ef0e249024f3f2a02478e750e644fa` | `7a88b24141d7117aa06135bea69ba5ffe84f12004f81daaed12cf2b84b2754a3` | +| unchanged `libplayer.so` | `aedfcb5bcce929cd08bdd113e2031945efc514f3ec4e21daaa39c5744d941bff` | `d146b4f7b5aa95f6768c5bae981bd2f01aaa5166e36d28e342b3789e0233b4b4` | + +- Device: vivo V2453A / Android 15 / API 35 / arm64-v8a. The pre-update installed APK was saved locally as `/private/tmp/P1-device-20260828-73CIHY/baseline-installed.apk`, SHA-256 `c3d8e88f226ff1c44577ce969ad0815d98bf7ac18e6ce67877c3638a84887a16`. +- Install identity: the OEM-assisted update completed without uninstalling or clearing data. Pulling the installed candidate back from the device produced SHA-256 `a45e0eab9a419da42eaa6dea9c95e9b4f93190bdca2f70bb14d9ff3c3a5107fb`, identical to the Mobile arm64-v8a APK. +- Device smoke: the App launched to `HomeActivity`, then an existing MPV playback flow reached `VideoActivity`. Visible playback and diagnostics exercised Vulkan `gpu-next`/`androidvk`, MediaCodec hardware decode, AudioTrack, 1920x1080 H.264/SDR playback, track parsing including PGS subtitles, and later a 3840x2160 HEVC/HDR10/TrueHD source. The App process log contained no `FATAL EXCEPTION`, fatal signal, `SIGSEGV`, `SIGABRT`, or `dlopen failed`; the App was force-stopped after evidence capture to avoid continued metered-network use. +- Device evidence: `/private/tmp/P1-device-20260828-73CIHY/home.png`, `home.xml`, `home-scrolled.png`, `home-scrolled.xml`, `playback.png`, `launch-logcat.txt`, and `playback-app-logcat.txt`. +- Interpretation limit: this is a compatibility/load/playback smoke, not a controlled performance comparison. It does not prove packed RGB10 channel order/gradient quality, zero-length EBML defaults, program-level HLS bitrate edition selection, or libplacebo alpha preservation. Those require the dedicated fixtures and rendering comparisons listed in section 7; no performance improvement or full behavioral acceptance is claimed from this smoke. +- Rollback: repository rollback is the baseline tag `recovery/P1-MPV-FORMAT-SHADER-CORRECTNESS/baseline-20260828-1246` or a revert of the eventual P1 commit. The device can be restored with the saved baseline APK if needed; no device data was cleared. +- Next action: run one final scoped diff/checkpoint validation, then finish the active task guard unit and create its annotated recovery tag. + +### 2026-08-28 implementation closure + +- Implementation commit: `a5971e3814d3b0826a5702d607dd6d1675b2ce53` (`mpv: add P1 format and shader correctness fixes`). +- Recovery tag: `recovery/P1-MPV-FORMAT-SHADER-CORRECTNESS/20260828184107-a5971e3814d3`. +- Commit contents: four provenance-preserving P1 patches, deterministic build-script application, rebuilt two-ABI MPV/FFmpeg assets, and the complete implementation/validation record. The existing lock and both `libplayer.so` files remained unchanged. +- User acceptance evidence: after candidate installation, the user played several original-disc videos and observed no playback problem. This supplements the automated/device smoke for disc/container parsing, track selection, subtitles, hardware decode, Vulkan output, audio routing, and normal playback continuity without claiming a controlled performance comparison. +- Final decision: P1 is accepted as a successfully implemented candidate. No additional broad regression suite is required. Packed RGB10 colour/gradient output, crafted zero-length EBML defaults, multi-variant HLS `variant_bitrate` selection, and transparent libplacebo alpha composition remain useful targeted tests when suitable samples exist, but they do not block this completed stage. +- Rollback: revert `a5971e3814d3b0826a5702d607dd6d1675b2ce53` or return to `recovery/P1-MPV-FORMAT-SHADER-CORRECTNESS/baseline-20260828-1246`; the committed candidate itself is recoverable at `recovery/P1-MPV-FORMAT-SHADER-CORRECTNESS/20260828184107-a5971e3814d3`. +- Next action: continue the master assessment ordering from the next incomplete MPV task; do not reopen P1 unless a dedicated fixture reveals a concrete regression. diff --git a/docs/P2-1-mpv-vulkan-generic-uv.md b/docs/P2-1-mpv-vulkan-generic-uv.md new file mode 100644 index 0000000000..eac43f7bdc --- /dev/null +++ b/docs/P2-1-mpv-vulkan-generic-uv.md @@ -0,0 +1,160 @@ +# P2-1: MPV Vulkan generic UV precomputation + +## Recovery anchor + +- Objective: move frame-invariant crop/normalization division out of MPV's generic Android Vulkan compute/fragment shaders while preserving every current WebHTV backend, AImage, fence, Dolby Vision, ABI, packaging, and performance contract. +- Acceptance: only the generic converter shader contract changes; both ARM ABIs rebuild from the unchanged lock; shader/SPIR-V, ELF/package, focused rendering/fallback, and no-regression checks pass; the implementation commit and recovery tag are recorded here. +- Status: complete; implementation commit `fe4184933fbb3a02bd1ff2ff794a277123c35bdc` and recovery tag recorded below. +- Task/lane: `P2-1-MPV-VULKAN-GENERIC-UV` / `upstream`. +- Workspace baseline: branch `fongmi-sync`, HEAD `9fcab83f9084446566240a8e8f5233d87d0274cc`, clean worktree. +- Baseline recovery tag: `recovery/P2-1/baseline-20260828-2219`. +- Protected pre-existing dirty paths: none. +- Excluded: FFmpeg/C0-M, libplacebo upgrades, P2-2 DV7 changes, App/JNI APIs, backend selection, stable conversion, AImage acquire/release flow, release-fence policy, and unrelated native dependencies. +- Next action: wait for explicit user direction before assessing or implementing another upstream task. + +## 1. Decision and source identity + +The approved stage is the five-file residual recorded in the master assessment checkpoint 38, not the complete Android Vulkan interop commit. + +| Identity | Full commit/tree | Role and disposition | +| --- | --- | --- | +| Assessed FongMi/mpv source | `f5c9f148d00db652da1ee900f386d8e0e615ed84`, parent `06ec6e1746e5cbdcd271e613fdb1f7f7ecd36042`, tree `49376fbe987a833dd1c8e41a18f428e900a48474` | Original approved source; stable patch-id `ebb2a24858351b9815717d9fd146e3949a72e8f6` | +| Refreshed FongMi/mpv equivalent | `e3e71ed793fbba1c6994726bfa5346ae6073bb5b`, parent `34663ec8415eae0a4ee946f9f793e5610238ec88`, tree `732da1b81cf347301b8f7e3e2f671b24078206c3` | 2026-08-28 force-push replacement; same title, timestamp, and stable patch-id `ebb2a24858351b9815717d9fd146e3949a72e8f6`; no new behavior is added to this task | +| Refreshed branch head | `2477400b9732a8cf63951ff66cdf3a948e7a0822` | Observed `FongMi/mpv@fongmi` head on 2026-08-28; later history has no UV follow-up or revert | +| Locked-line equivalent | `cb007d6f6b520ff57a4bedd5f8bcd330f64c88a0`, parent `62648ab1789c6e1b025fe9392857385f37314710`, tree `20c10c0e55654ac95125a7b4ead6fbc319a80c83` | Supplies the Android Vulkan interop body; stable patch-id `274120b84448030dc4406782c8820f0f702b3ce1`; UV residual remains absent | +| Current WebHTV mpv pin | `cca559b41ceb0bb7731cf6ef2e1f33276cd30c42`, tree `bb1d0974d85eea46dfec90bddb9c9e1392765ea7` | Actual source rebuilt by `scripts/build_mpv_native.sh`; generic shaders still use per-pixel division | + +The refreshed hash does not change approval scope. The stable patch-id proves that `e3e71ed...` is the current identity of the already assessed `f5c9f148...` change. Implementation provenance records both full IDs and ports only the approved UV invariant. + +## 2. Current WebHTV flow and gap + +- `auto` remains direct -> stable -> generic. Direct sampling does not use a conversion shader. +- The four-output stable override already pushes `uv_offset`, `uv_scale`, and `output_size`; its CPU uses double intermediates and the shader performs one multiply/add sequence per pixel. +- The pinned generic compute and fragment shaders still push integer crop/source geometry and perform crop scaling plus source normalization division for every output pixel. +- Explicit `legacy`, `compute`, and `fragment`, plus stable initialization failure to generic, therefore retain the gap. +- `mpv-android-vulkan-conversion-default.patch`, `mpv-android-vulkan-smart-backend.patch`, `mpv-android-vulkan-legacy-backend.patch`, and `mpv-aimagereader-stable-flow.patch` are preservation contracts, not replacement candidates. +- P1 commit `a5971e3814d3b0826a5702d607dd6d1675b2ce53` rebuilt the same MPV pin but added only format/EBML/HLS/libplacebo correctness patches; it did not implement this generic UV change. + +## 3. Alternatives and recommendation + +| Alternative | Decision | +| --- | --- | +| No change | Correct and safe, but leaves redundant per-pixel division in generic fallback and forced conversion modes. | +| Adopt `f5c9...`/`e3e71...` wholesale | Rejected. It would collide with later WebHTV backend selection, four-output pool, release-fence disablement, AImage lifetime, bounded acquire, P1, DV, and disc changes. | +| Narrow WebHTV adaptation | Approved. Port only the two shader contracts, C push constants/CPU calculation, and generated SPIR-V headers; add deterministic source/header verification and a unique asset marker. | + +This is best practice for the current project because the divisions depend only on frame geometry, not on pixel identity. Precomputing them once per frame removes redundant GPU ALU without changing the algebra or the default direct/stable path. WebHTV must adapt the upstream change rather than replace its surrounding files. + +## 4. Best-practice evidence + +| Evidence class | Source/revision/access | Grade | Decision impact | +| --- | --- | --- | --- | +| Exact upstream source/history | `FongMi/mpv` commits and trees above, fetched 2026-08-28; master assessment checkpoint 38 | A | Establishes the five-file residual, old/new force-push equivalence, and absence of later UV reverts/fixes | +| Current local source/data flow | `third_party/mpv-native-lock.json`, Vulkan patches/override, `scripts/build_mpv_native.sh`, both packaged `libmpv.so`, inspected 2026-08-28 | A | Confirms stable-only coverage and identifies backend/fence/AImage contracts that cannot change | +| Vulkan official guidance | `https://docs.vulkan.org/guide/latest/push_constants.html`, accessed 2026-08-28 | A | Requires C and GLSL push-constant size/layout/stage agreement; supports explicit contract checks | +| Shader compiler documentation | `google/shaderc` `glslc/README.asciidoc`, current main, accessed 2026-08-28 | A | Supports deterministic shader-stage, target-environment, optimization, and generated SPIR-V output commands | +| mpv maintainer guidance | `FongMi/mpv@2477400b9732a8cf63951ff66cdf3a948e7a0822:DOCS/contribute.md`, accessed 2026-08-28 | B | Requires a logical, attributable, tested patch and disclosure of verification scope | +| Mature related implementation | WebHTV stable Vulkan override at baseline HEAD; upstream generic implementation `f5c9...`/`e3e71...` | A | Two independent implementations use the same formula and double-intermediate CPU calculation | +| PR/issues/reverts/discussion | Exact file history through refreshed head; only later backend-selection commit `6e7f2db65d654dad588fb02e6366498bb256adc8` touches the files, with no UV revert | B | No known upstream regression requires altering the approved formula; backend selection remains out of scope | +| Papers/blogs/field reports | Inapplicable to the decision: this is algebraic invariant hoisting, not a new rendering algorithm; performance magnitude is device-specific and will be measured locally | N/A | Prevents unsupported universal speed/power claims; acceptance is no regression plus measured generic-path evidence | + +## 5. Implementation design + +1. Add a standalone MPV patch after the existing Vulkan backend/lifetime patches and before unrelated P1 patches. +2. Change generic compute and fragment shaders from integer crop/source geometry to `vec2 uv_offset`, `vec2 uv_scale`, and `ivec2 output_size`. +3. Keep full integer geometry separately for the existing diagnostic log. Calculate offsets/scales with double intermediates and cast once to float. +4. Generate both checked-in C headers from the patched shader sources with the locked shader compiler and validate the SPIR-V target; never hand-edit byte arrays. +5. Extend the existing shader-contract checker to cover stable and generic layouts and generated-header provenance. Add a generic-only marker so packaged binaries prove that this task, not only stable conversion, is present. +6. Rebuild the unchanged locked graph for `arm64-v8a` and `armeabi-v7a`; install only the resulting verified asset set. `libplayer.so` remains unchanged. + +## 6. Acceptance, performance, and rollback + +- Static acceptance: the patch applies after all existing patches; C/compute/fragment layouts match; generated headers come from source; `spirv-val` passes; no backend, queue, fence, AImage, DV, audio, network, or App/JNI hunk changes. +- Native acceptance: both ABI builds complete; `bash scripts/verify_mpv_native_assets.sh --require-elf` passes with unchanged source locks, SONAME/`DT_NEEDED`, package manifest, and existing markers plus the generic marker. +- Rendering acceptance: explicit compute, fragment, and legacy cover odd crop/non-integer scaling/rotation where available; auto direct and stable smoke remain unchanged; subtitles/OSD/LUT and at least one HDR or raw-DV conversion case show no coordinate or component regression. +- Performance acceptance: on the same device/sample/settings, generic-path startup, dropped/late frames, and observed frame timing must not regress. Any improvement is reported only from comparable runs; direct/stable behavior must remain byte/source unchanged apart from relinking. +- Package/ABI acceptance: no new library, export, JNI/API, or dependency version; size growth is limited to diagnostic/generated-code variance and recorded for both `libmpv.so` files. +- Rollback: restore baseline tag `recovery/P2-1/baseline-20260828-2219`, or revert the atomic P2-1 commit and its two ABI assets. No other player stage is coupled to this rollback. + +## 7. Approval record + +The user explicitly approved implementation after reviewing the P2-1 assessment, with the condition that existing functionality and performance must not be directly or indirectly degraded. P2-2, C0-M, and all other upstream tasks remain unapproved for this unit. + +## Checkpoint 1: 2026-08-28 22:34 CST, source and shader gate + +- Completed: created the baseline recovery tag; refreshed `FongMi/mpv@fongmi`; mapped force-pushed `f5c9f148...` to patch-identical `e3e71ed...`; added the three-file P2 source patch, deterministic two-header generation, generic/stable contract checks, packaged marker checks, and build documentation. +- Source identities: baseline pin `cca559b41ceb0bb7731cf6ef2e1f33276cd30c42`; approved source `f5c9f148d00db652da1ee900f386d8e0e615ed84`; refreshed equivalent `e3e71ed793fbba1c6994726bfa5346ae6073bb5b`; refreshed head `2477400b9732a8cf63951ff66cdf3a948e7a0822`; stable patch-id `ebb2a24858351b9815717d9fd146e3949a72e8f6`. +- Files changed so far: this task document, master index, `scripts/build_mpv_native.sh`, `scripts/verify_mpv_native_assets.sh`, `scripts/verify_mpv_vulkan_shader_contract.py`, `third_party/mpv-native-build.md`, and `third_party/patches/mpv-p2-generic-uv.patch`. Native assets are not yet changed. +- Validation passed once: `bash -n scripts/build_mpv_native.sh`; repository shader-contract check; reverse and forward P2 patch application after the complete existing 15-patch stack; NDK r29 `glslc` compute/fragment compilation; Vulkan 1.2 `spirv-val`; prepared-source generic contract including legacy, release-fence disablement, and AImage lifetime preservation; `git diff --check`; task-guard safety check. +- Generated shader evidence: compute SPIR-V SHA-256 `b36d0fc510d31c6d54ddff181386f295a43ec31d4001fb85efb1c4d4284fade7`; fragment SPIR-V SHA-256 `46c42820dddab594b38767077f8b9e04b1cdc37bb868c89cd8e1d183de572e1a`. +- Rollback anchor: `recovery/P2-1/baseline-20260828-2219` at `9fcab83f9084446566240a8e8f5233d87d0274cc`. +- Unresolved: two-ABI compile/link/package identity, final asset hashes/size delta, and runtime generic/direct/stable behavior. +- Next action: run one clean `--abi all --install` native build using the unchanged lock and capture its single complete output. + +## Checkpoint 2: 2026-08-28 23:09 CST, native build storage failure + +- Completed before failure: source preparation, the complete P2 shader/contract gate, and the clean arm64 dependency build through FFmpeg, fontconfig, FriBidi, HarfBuzz, libunibreak, libass, Lua, and almost all shaderc objects. +- Failure classification: environment storage exhaustion, not a source, compiler, shader, ABI, or P2 contract failure. NDK r29 `llvm-ar` failed while combining `libshaderc_combined.a` with `No space left on device`; the data volume had 62 MiB free. +- Preserved state: the active guard, baseline HEAD/tag, task-owned source edits, generated shader hashes, and the successfully installed arm64 prefix remain intact. No App asset was replaced and both committed ABI directories remain at their baseline contents. +- Recovery evidence: the wrapper supports `--incremental`; completed dependency outputs live under the arm64 prefix and the failed build workspace occupies about 3.8 GiB. Previously completed WebHTV task caches under `/private/tmp` provide enough reclaimable space without deleting repository source, packaged assets, or unrelated user files. +- Verification impact: the failed attempt is not acceptance evidence. Final acceptance still requires both ABI outputs, `verify_mpv_native_assets.sh --require-elf`, package identity, and focused Vulkan runtime checks. +- Rollback anchor: unchanged at `recovery/P2-1/baseline-20260828-2219` / `9fcab83f9084446566240a8e8f5233d87d0274cc`. +- Next action: remove only the identified completed-task temporary caches, then resume arm64 with the unchanged lock and `--incremental` rather than repeating completed compilation. + +## Checkpoint 3: 2026-08-28 23:44 CST, two-ABI native candidate + +- Completed: removed only the completed-task temporary caches recorded in checkpoint 2, resumed the preserved arm64 prefix, completed a clean armv7 build, installed both ABI asset sets, and ran the required ELF/lock/package verification once. +- Build command/result: `env https_proxy=http://127.0.0.1:7897 http_proxy=http://127.0.0.1:7897 all_proxy=socks5://127.0.0.1:7897 scripts/build_mpv_native.sh --abi all --install --jobs 8 --incremental`; exit 0. Both `hwdec_aimagereader_vk_convert.c` objects compiled and both `libmpv.so` targets linked. Existing compiler warnings were non-fatal and outside the P2 hunk. +- Candidate asset identities: + +| ABI / file | Baseline SHA-256 / bytes | Candidate SHA-256 / bytes | Size delta | +| --- | --- | --- | ---: | +| arm64-v8a `libmpv.so` | `69e9a8d10560a41107680ca4de737996885f2f37fa353fd5ede30334866eeb7b` / 17,714,112 | `f050af3c3d1ffb814b48bd50963fdde33cd07e38ad0ff025a62b4e31228bc480` / 17,714,032 | -80 | +| arm64-v8a `libmvcodec.so` | `dd0df8e451f34d1f1f04e829d5e3c54415ecfd100e1da185ba99400672a356ce` / 15,315,384 | `3aeeff9d487b6dc0b63e804bb2563b71d6a589d109bb5dcde9fc1a7fdbdf912f` / 15,315,464 | +80 | +| arm64-v8a `libmvformat.so` | `d452ca2a0ac2d81eb31176b454d0a4c641f4ae776c4b2549dac0f705c0816b77` / 4,497,672 | `a898c68026344705451507395315173cc663d754463eb0813c5aff8ce0207ee5` / 4,497,688 | +16 | +| armeabi-v7a `libmpv.so` | `ec2cbc58616bb383eb2f80d3fde883da02036b00062287a6f956ebda1aeb5ce3` / 14,519,876 | `7ed0c6aa8f674031588e0b649f5766954a1e3a8caf4bffb76caaa7de63e82cd7` / 14,519,652 | -224 | +| armeabi-v7a `libmvcodec.so` | `057737104206f1091f1e498f09112f6fa4786a126b1699d477a2a3f9227c53ef` / 14,470,380 | `28b6227211a13123c58fb0921e2c1c76c2e9d1d4189898d9a94075c592f72547` / 14,470,380 | 0 | +| armeabi-v7a `libmvformat.so` | `fb64b119a50abdf5d83b7b7c3283b25bcaefa0c86a440eab806a7aba1f06ad1a` / 4,230,756 | `f9b9ad3289c47fe26a303fb07a66fec16ab5ed82383c7f967126e4144f296a0e` / 4,230,788 | +32 | + +- Preserved binary contract: arm64-v8a `libplayer.so` remains `aedfcb5bcce929cd08bdd113e2031945efc514f3ec4e21daaa39c5744d941bff` / 91,264 bytes; armeabi-v7a remains `d146b4f7b5aa95f6768c5bae981bd2f01aaa5166e36d28e342b3789e0233b4b4` / 57,588 bytes. +- Validation: `bash scripts/verify_mpv_native_assets.sh --require-elf` passed for both ABIs using NDK r29 `llvm-readelf`; lock versions, source/patch markers, stable and generic shader contracts, ELF identity, namespace separation, and packaging rules match. The rebuilt FFmpeg shared objects show only the recorded small relink variance and no version/contract change. +- Performance status: the implementation removes per-pixel divisions only from forced/fallback generic conversion; direct and stable source paths are unchanged. Compilation and ELF evidence do not prove runtime performance, so candidate acceptance still requires focused same-device playback/diagnostic checks and no observed regression. +- Rollback anchor: unchanged at `recovery/P2-1/baseline-20260828-2219` / `9fcab83f9084446566240a8e8f5233d87d0274cc`; the candidate assets are uncommitted and can be discarded only as the complete task-owned set if validation fails. +- Unresolved: APK asset identity and connected-device generic compute/fragment/legacy plus direct/stable neighbor behavior. +- Next action: build the `mobileArm64_v8a` debug APK once and verify the packaged arm64 asset hashes before installation. + +## Checkpoint 4: 2026-08-29 00:14 CST, APK and focused device acceptance + +- APK build/package: `bash ./gradlew :app:assembleMobileArm64_v8aDebug --no-daemon` passed once in 2m 2s. `app-mobile-arm64_v8a-debug.apk` is 157,579,720 bytes with SHA-256 `1f992ddff117eba2c3c4ab8dea7ebd0f531551c6c358f05a6285244f14f90227`; its four arm64 MPV assets match the candidate workspace hashes exactly. +- Device: vivo V2453A / PD2453, serial `10CF6H1D2L0009S`, Android 15, `arm64-v8a`, 1080x2400 panel. The existing App data was retained during installation. Runtime checks used Vulkan `gpu-next`, hard decode, and the same candidate APK throughout. +- Decisive sample: `/sdcard/Download/杜比视界测试/hdr测试.mp4`, AV1 3840x2160 at 59.940 fps, HDR10 BT.2020/PQ, approximately 12.2 Mbps. All accepted runs reported `av1_mediacodec`, `actualDecode=hardware`, `hwdec=mediacodec`, and a Vulkan render path. The portrait device layout scales the 16:9 video into a non-integer display viewport and exposed no component, crop-coordinate, or color-placement error. +- Test-only backend selection: the formal App UI exposes direct/legacy/stable, while the current pre-init libmpv option takes precedence over `mpv.conf` for compute/fragment. A uniquely named temporary Lua script set the native option at `start-file` solely for this test; it was not added to the repository or APK and was removed after testing. This existing App selection limitation is outside P2-1 and does not block the reachable legacy/fallback generic path. + +| Requested path | Native evidence | Timing evidence under thermal status 2 | Visual/result | +| --- | --- | --- | --- | +| `compute` | backend `compute`; generic CPU-precomputed UV marker; crop `0,0 3840x2160`, compute output `3840x2160` | first frame 535 ms; after about 20 s: decoder drops 0, output drops 5, mistimed 0, delayed 0, rebuffer 0 | HDR image rendered normally; no black frame, UV/component swap, offset, or scaling error | +| `fragment` | backend `fragment`; generic marker; matching fragment geometry | first frame 1848 ms after saved-position seek; after about 20 s: decoder/output drops 0, mistimed/delayed 0 | normal image and color; no coordinate error | +| `legacy` | backend `legacy`; generic marker; selected compute conversion for the device format | first frame 1877 ms after saved-position seek; after about 20 s: decoder/output drops 0, mistimed/delayed 0 | normal image and color | +| `stable` | backend `stable`; existing four-output bounded-fence pool and stable CPU-precomputed transform markers | first frame 1828 ms after saved-position seek; after about 20 s: decoder/output drops 0, mistimed/delayed 0 | unchanged neighboring path rendered normally | +| `auto/direct` | backend `auto`; log confirms direct AHardwareBuffer sampling preference with no stable/generic fallback | first frame 2025 ms after saved-position seek; after more than 30 s: decoder/output drops 0, mistimed/delayed 0 | unchanged default path rendered normally | + +- Performance interpretation: the runs were performed while the USB-connected phone remained at Android thermal status 2, so first-frame values are diagnostic only and are not used to claim a speedup. The compute run's five output drops over roughly 1200 4K60 frames did not continue as a decoder, sync, or rebuffer failure; the other four paths stayed at zero. The source change removes per-pixel divisions and adds no work, while direct/stable source paths are unchanged, so there is no evidence of a P2-1 performance regression. A numeric power or speed gain is intentionally not claimed without a frozen baseline run. +- Additional DV evidence: `P81_GlassBlowing2_3840x2160@59_94fps_15200kbps.mkv` rendered HDR/DV colors and geometry correctly, but this device decoded that Profile 8 stream in software. It therefore remains visual stress evidence only and is not counted as AImageReader backend acceptance. +- Failure/lifecycle result: the accepted traces contain no AImageReader acquisition timeout, crash, ANR diagnostic, slow libmpv call, destroyed-mutex signal, black screen, or playback rebuffer. Audio continued through Android AudioTrack. +- Coverage limit: no reliable odd-crop/rotated MediaCodec fixture was available; the observed decoder crop was full-frame. Static source/header/SPIR-V contract checks cover the changed formula and layout, while device evidence covers full-frame 4K60 HDR, hard decode, non-integer viewport scaling, and all neighboring backends. Runtime coverage is arm64 on one Qualcomm device; armv7 remains build/ELF/package verified. +- User-state restoration: the original preference XML and `mpv.conf` were restored byte-for-byte with SHA-256 `c0951653ec2806a28c50cf6382a2c5933f78dcd5fcd539a2847daeb9fe6a23e0` and `941af30205752147c8ef4f1931a8d5dc15478fe3fcf5c8e3bd8fa788031b9282`. The temporary Lua script and `/data/local/tmp` inputs were removed; a cold restart returned to the original MPV/Vulkan/automatic-output/non-verbose settings. +- Acceptance: static shader/SPIR-V, two-ABI native build, ELF/package checks, APK identity, and focused device behavior all pass. P2-1 does not change App/JNI, versions, dependencies, backend policy, stable/direct code, AImage/fence ownership, DV policy, or `libplayer.so`. +- Rollback: revert the pending atomic P2-1 commit or restore `recovery/P2-1/baseline-20260828-2219`; both ABI asset sets, the source patch, build/verification scripts, and documentation move together. +- Unresolved risk: measured improvement magnitude and odd-crop/rotation behavior are not quantified on this device; no observed failure requires broadening the approved task. +- Next action: close the task record with the generated implementation commit and recovery tag; do not start P2-2 or C0-M without separate approval. + +## Closure: 2026-08-29 00:36 CST + +- Implementation commit: `fe4184933fbb3a02bd1ff2ff794a277123c35bdc` (`mpv: precompute generic Vulkan UV transforms`). +- Recovery tag: `recovery/P2-1-MPV-VULKAN-GENERIC-UV/20260829003632-fe4184933fbb`, annotated locally at the implementation commit; tag creation completed in 0 seconds. +- Committed unit: the narrow generic UV patch and shader-generation/verification support, both rebuilt ARM ABI asset sets, native build documentation, this task record, and the master task index. No App/JNI, lock revision, FFmpeg version, libplacebo version, backend policy, or unrelated file entered the commit. +- Verification attached to the commit: shader/SPIR-V contract, two-ABI native build, `verify_mpv_native_assets.sh --require-elf`, mobile arm64 debug APK asset identity, V2453A HDR10 hardware-decoded compute/fragment/legacy/stable/auto playback, and byte-identical user-config restoration. +- Completion decision: P2-1 is accepted. The remaining limits are one-device runtime coverage and the absence of an odd-crop/rotation fixture; neither provides evidence of a regression or justifies expanding this task. +- Rollback: revert `fe4184933fbb3a02bd1ff2ff794a277123c35bdc` or restore `recovery/P2-1/baseline-20260828-2219`. The candidate recovery tag above identifies the verified post-change state. +- Authorization boundary: P2-2, C0-M, FFmpeg/libplacebo upgrades, and all App/JNI work remain unapproved and unimplemented by this task. +- Next action: wait for explicit user direction before opening another upstream stage. diff --git a/docs/P2-2-mpv-dv7-metadata-codecpar.md b/docs/P2-2-mpv-dv7-metadata-codecpar.md new file mode 100644 index 0000000000..c41660bd35 --- /dev/null +++ b/docs/P2-2-mpv-dv7-metadata-codecpar.md @@ -0,0 +1,162 @@ +# P2-2: MPV DV7 metadata/codecpar/error completeness + +## Recovery anchor + +- Objective: complete the existing MPV Dolby Vision Profile 7 HDR10 base-layer fallback when container metadata is incomplete, while preserving WebHTV packet ownership, Surface Direct, single-Surface EL, performance, ABI, and packaging contracts. +- Acceptance: Profile 7 HDR10 fallback creates the splitter without relying on `dv_el_present`, initializes the BSF with checked errors, copies filtered `par_out` back to decoder codec parameters, clears `dv_el_present`, rejects packet sizes above `INT_MAX`, and keeps all current WebHTV safety paths; both ARM ABIs, ELF/package checks, and focused device playback pass without a performance or neighboring-format regression. +- Status: complete and committed. Source adaptation, strict patch preparation, complete two-ABI native build/install, ELF/asset verification, arm64 APK packaging, installation, and focused device playback verification all passed. +- Task/lane: `P2-2-MPV-DV7-METADATA-CODECPAR` / `upstream`. +- Workspace baseline: branch `fongmi-sync`, HEAD `14931888cf5c6e47902323c06180969cd4b9c32d`. +- Baseline recovery tag: `recovery/P2-2-MPV-DV7-METADATA-CODECPAR/baseline-20260829-0342`. +- Protected pre-existing dirty path: `AGENTS.md`. +- Scope: the existing DV7 local patch, deterministic native verification if required, both ARM MPV asset sets, native build documentation, this task record, and the master assessment index. +- Excluded: MPV/FFmpeg/libplacebo/mpv-android lock updates, C0-M, C2, Exo, App/JNI APIs, DV5 auto routing, Vulkan backend selection, Android BL+EL software decoding, AudioTrack, and unrelated native dependencies. +- Rollback: restore the baseline tag or revert the eventual single atomic implementation commit; both ABI asset sets and the source patch move together. +- Next action: continue with the queued P3 assessment only as a separately approved task; P2-2 itself is closed. + +## 1. Approved user capability + +Some Profile 7 remuxes or disc-derived files retain interleaved base/enhancement NAL units but lose a reliable `dv_el_present` container flag. WebHTV already has an explicit MPV HDR10 fallback, but those files can currently bypass its splitter or leave the decoder parameters describing Dolby Vision after packets have been reduced to the HDR10 base layer. + +The approved result is that MPV consistently feeds a clean, independently decodable HDR10 base layer to MediaCodec/software decoding and describes that filtered stream accurately. This reduces the risk of wrong colour, black output, hardware-decoder rejection, or avoidable software fallback on malformed or incompletely tagged DV7 inputs. It does not add full Android FEL/EL playback and does not change the default policy for DV5, Profile 8.1, ordinary HDR10, or SDR. + +## 2. Source identity and cross-repository relationship + +| Repository/input | Full commit | Role and disposition | +| --- | --- | --- | +| FongMi/mpv original assessed source | `44755d7eaa0f186e4052ffc99c4f0b500a05a2ba` | Original `demux: support Dolby Vision profile 7 HDR10 fallback`; stable patch-id `c1de01aba5dec040af172c2f2832cdab7dcf9bfa` | +| FongMi/mpv current force-push equivalent | `2477400b9732a8cf63951ff66cdf3a948e7a0822` | Current `fongmi` head on 2026-08-29; same stable patch-id; no later follow-up or revert exists on that branch | +| WebHTV locked mpv | `cca559b41ceb0bb7731cf6ef2e1f33276cd30c42` | Retained source baseline; this task adds only a local narrow patch delta | +| FongMi/FFmpeg dovi_split | `6026988b753ebb1bd424612f40b17c0c363d8ed7` | Supplies the `dovi_split` BSF already present in the locked FFmpeg graph | +| FongMi/FFmpeg dovi_split tests | `59619a191724cc1bcfb47b906f596b8372032764` | FATE coverage for `bl`, `bl_rpu`, `el`, and `el_rpu` filter modes | +| FongMi/FFmpeg DV/HDR chain | `6dc8edecd7ebafc80764b8c0a20f87e3f9fb1382`, `691a7d5a125b40dcc427ee298c983729e673d974`, `eb107bbafe37442065e42b4f2d410f371b758143`, `dd537f9a852d0ce40078f9ac520d7267ba850883` | Existing safe output, per-frame metadata, and FFmpeg 9 container support; no FFmpeg code change is approved here | +| WebHTV locked FFmpeg | `04482c8d13ac27b2a9fe93f5d388929eef8af5f4` | Continues to provide the tested BSF and metadata behavior through the MPV `libmv*` namespace | +| FongMi/mpv-android | `99a60ad2141d5ace94453590903c2c6b9a0a2443` | Unchanged NDK r29 two-ABI build framework | +| FongMi/libplacebo | `b694a21bf2dc176c1e98b8a13c6421a0de5f3da5` | Unchanged static rendering dependency; P2-2 does not modify shader or mapping behavior | + +MPV owns the demux policy and copies FFmpeg BSF output parameters into its `mp_codec_params`. FFmpeg owns packet filtering and output parameter derivation. mpv-android only builds the coherent graph; libplacebo and App/Exo code are not behavioral participants in this source change. + +## 3. Current WebHTV implementation and exact gap + +The current `mpv-dovi-profile7-hdr10-base-layer.patch` already provides: + +- opt-in `demuxer-dovi-profile7=preserve|hdr10`; +- `dovi_split=mode=bl` before the decoder; +- a three-state packet result distinguishing expected empty output from hard errors; +- zero-copy only when the AVPacket and demux buffer match exactly, otherwise a padded packet copy with properties; +- decoder-level native-DV suppression while retaining Surface Direct for the HDR10 base layer; +- `VO_CAP_GPU_DOVI_EL` as the Android single-Surface EL gate; +- App option/diagnostic behavior and binary marker verification. + +The current final source still has five missing contracts: + +1. lavf and Matroska only create the splitter when `dv_el_present` is true; +2. `mp_codec_params_to_av()` and parameter-copy failure are not propagated; +3. `av_opt_set()` and `av_bsf_init()` errors are not retained for useful diagnostics; +4. HDR10 mode returns before applying `par_out` to `lav_codecpar` and clearing `dv_el_present`; +5. `demux_packet.len` is passed to FFmpeg without an explicit `INT_MAX` bound. + +P1, P2-1, and P2-5 did not modify this patch after the last DV7 stabilization commit. The task is therefore not already implemented or superseded. + +## 4. Best-practice evidence + +Access date for all evidence is 2026-08-29. + +| Evidence class | Source/revision | Grade | Claim and decision impact | +| --- | --- | --- | --- | +| Exact upstream source/history | FongMi/mpv commits `44755d7eaa0f186e4052ffc99c4f0b500a05a2ba` and `2477400b9732a8cf63951ff66cdf3a948e7a0822`; current branch history | A | The current commit is a force-push equivalent, not a new design; only five narrow hunks remain useful, while the complete parent chain would reopen Android EL software decoding | +| Official FFmpeg API contract | locked FFmpeg `libavcodec/bsf.h` at `04482c8d13ac27b2a9fe93f5d388929eef8af5f4` | A | `par_out` is set by the filter during `av_bsf_init()`; consumers must use the initialized output parameters rather than retaining stale input codec parameters | +| Official packet/padding contract | locked FFmpeg `libavcodec/packet.h` and `libavcodec/bsf/dovi_split.c` | A | Packet data is assumed to include `AV_INPUT_BUFFER_PADDING_SIZE`; WebHTV's exact-ref/padded-copy implementation is safer than the target commit's arbitrary subrange ref | +| Upstream tests | FFmpeg `59619a191724cc1bcfb47b906f596b8372032764`, `tests/fate/hevc.mak` | A | The BSF has deterministic mode-level output tests; WebHTV must add integration checks around MPV detection, codec parameters, and Android output policy rather than reimplementing the filter | +| Maintainer/revert/issue evidence | FongMi/mpv current branch has no commit after `2477400b...`; GitHub issue search for `dovi_split`/`profile 7` returned zero results | B | There is no later upstream correction or discussion that supersedes the assessed hunk; local safety adaptations remain necessary and explicitly owned by WebHTV | +| Mature related implementation | current WebHTV DV7 patch and FFmpeg BSF/FATE implementation | A | Preserve the already verified packet ownership and Android Surface rules; change only detection, output parameters, errors, and bounds | + +Papers, general blogs, and cross-project benchmarks are inapplicable: this task introduces no new colour algorithm, decoder, scheduling policy, or performance technique. Correctness is determined by the FFmpeg BSF/API ownership contract, exact MPV call flow, and target-device playback evidence. + +## 5. Alternatives and decision + +| Alternative | Decision | +| --- | --- | +| No change | Rejected: incomplete metadata can bypass filtering, and filtered packets can retain stale DV decoder parameters | +| Adopt `2477400b...` or its full parent chain | Rejected: it weakens packet padding/error distinctions and can reopen BL MediaCodec + EL software decoding on Android | +| Narrow WebHTV adaptation | Approved: absorb metadata-missing detection, checked initialization, `par_out` synchronization, `dv_el_present=false`, `INT_MAX`, and optionally the auto-VO defense while retaining all local safety gates | + +This narrow adaptation is the best-practice design for WebHTV. The one deliberate upstream adjustment is failure ownership: initialization errors remain explicit and observable, while the product must not silently claim a successful HDR10 fallback if the BSF could not be established. + +## 6. Implementation stages + +1. Update only the existing DV7 patch. Define `base_only` as HEVC Profile 7 plus explicit HDR10 fallback, so missing `dv_el_present` is tolerated only for the approved mode. +2. Check all allocation/conversion/copy/option/init results and keep the direct cause in one warning. +3. After successful `mode=bl` initialization, atomically replace `lav_codecpar` from `par_out`, clear `dv_el_present`, and emit one diagnostic marker. +4. Add an `INT_MAX` guard before converting packet length to FFmpeg's `int` size while preserving the current exact-ref/padded-copy and three-state behavior. +5. Keep the decoder-level Surface Direct gate and `VO_CAP_GPU_DOVI_EL`; only add the upstream auto-VO guard if it composes without changing explicit App output behavior. +6. Rebuild the complete locked graph for `arm64-v8a` and `armeabi-v7a`; do not change lock revisions or `libplayer.so`. + +## 7. Verification and performance floor + +- Strict ordered patch application against mpv `cca559b41ceb0bb7731cf6ef2e1f33276cd30c42`. +- Static assertions for Profile 7 base-only detection, checked `par_out` copy, `dv_el_present=false`, initialization diagnostics, `INT_MAX`, and preserved packet/EL/Surface safety markers. +- One complete two-ABI native build and one `scripts/verify_mpv_native_assets.sh --require-elf` pass. +- arm64 APK asset identity and focused connected-device playback. +- Inputs: DV7 interleaved with complete metadata, a metadata-missing equivalent/fixture when available, BL-only/EL-only or malformed packet coverage, plus DV5/P8.1/HDR10 negative controls. +- Outputs/lifecycle: Surface Direct, Vulkan auto/stable, OpenGL GPU; start, seek, pause/resume, flush, replace media, and EOF. +- Metadata: filtered decoder parameters no longer advertise EL/RPU, HDR10 mastering/content-light/transfer data remain present, source profile reporting and fallback diagnostics remain correct. +- Performance: no new per-frame allocation or copy on already supported packets; the only unconditional packet-path work is an integer bound check. Existing exact zero-copy behavior remains. Any sustained new drop, rebuffer, CPU/memory increase, or second EL decoder rejects the candidate. +- Packaging: no new library; `libplayer.so` remains byte-identical; APK size change is limited to normal native code delta. + +## 8. Source implementation checkpoint: 2026-08-29 03:52 CST + +- Baseline/tag/guard: HEAD remains `14931888cf5c6e47902323c06180969cd4b9c32d`; baseline tag is `recovery/P2-2-MPV-DV7-METADATA-CODECPAR/baseline-20260829-0342`; task guard is active and continues to protect the pre-existing `AGENTS.md` change. +- Source change: the existing DV7 patch now creates a splitter for explicit Profile 7 HDR10 fallback even when `dv_el_present` is absent; all conversion/copy/option/init returns are checked; `par_out` is copied atomically into `lav_codecpar`; `dv_el_present` is cleared; packet length is bounded by `INT_MAX`. +- Preserved behavior: three-state packet results, exact AVPacket-ref condition, padded-copy fallback and copied properties, decoder-level Surface Direct gate, `VO_CAP_GPU_DOVI_EL`, App option/diagnostics, current lock revisions, and all P1/P2-1/Vulkan/AImageReader patches remain unchanged. +- Deliberate omission: the target commit's player-level automatic direct-VO helper was not copied. The existing decoder-level gate already prevents native-DV decoder configuration for explicit or automatic Surface Direct while retaining the current low-overhead output choice; adding another output selector would expand behavior without a demonstrated gap. +- Deterministic build checks: `scripts/build_mpv_native.sh` now rejects a prepared source missing the metadata guard, atomic codec-parameter swap, cleared EL flag, or `INT_MAX`; both native verifiers require the codec-parameter synchronization marker. +- Patch/source hashes: `mpv-dovi-profile7-hdr10-base-layer.patch` `bad45f5db2b45b21ba410414596580496ee571d77233d2a7a615bb5bd0613ed2`; `build_mpv_native.sh` `d6806bb787f2019c8d74473e63fdec34cb63a34bc5d54e452f75a6932b7da066`; `verify_mpv_native_assets.sh` `c9cbd8fe01794bec3438c057aa0b0ec2299607ff6fa1e156c2e1c05b2287e5c8`. +- Verification completed: production `--prepare-only` passed after the source edit and again after adding deterministic assertions. It applied the complete locked patch stack, including P1 and P2-1, and verified both stable and generic Vulkan shader contracts. +- Unverified: compilation, both ABI assets, ELF/package identity, APK packaging, and device playback. +- Exactly one next action: run the complete locked two-ABI native build/install once. + +## 9. Two-ABI native build checkpoint: 2026-08-29 05:09 CST + +- Build: the single planned `bash scripts/build_mpv_native.sh --abi all --install` run completed successfully for `arm64-v8a` and `armeabi-v7a`. Both builds compiled the adapted `demux/dovi_split.c`, linked `libmpv.so`, and installed the packaged App assets. +- Deterministic verification: one `bash scripts/verify_mpv_native_assets.sh --require-elf` pass succeeded for both ABIs using NDK r29 `llvm-readelf`. It confirmed lock/source versions, FFmpeg namespace separation, ELF and packaging rules, the existing stable/generic Vulkan contracts, and the P2-2 codec-parameter synchronization marker. +- Changed native asset hashes: + - `arm64-v8a/libmpv.so`: `bff445a09a3daac5b42a20ea002e95ace90172922f7efe737f68e0f549e1cdba` + - `arm64-v8a/libmvcodec.so`: `dd0df8e451f34d1f1f04e829d5e3c54415ecfd100e1da185ba99400672a356ce` + - `arm64-v8a/libmvformat.so`: `d452ca2a0ac2d81eb31176b454d0a4c641f4ae776c4b2549dac0f705c0816b77` + - `armeabi-v7a/libmpv.so`: `608ba379ea583d0cfafbd4010eb01d27f25ea8eb04152a662d8f3e03723fafbe` + - `armeabi-v7a/libmvcodec.so`: `057737104206f1091f1e498f09112f6fa4786a126b1699d477a2a3f9227c53ef` + - `armeabi-v7a/libmvformat.so`: `fb64b119a50abdf5d83b7b7c3283b25bcaefa0c86a440eab806a7aba1f06ad1a` +- JNI preservation: both committed `libplayer.so` files are byte-identical to HEAD. Their hashes remain `aedfcb5bcce929cd08bdd113e2031945efc514f3ec4e21daaa39c5744d941bff` (`arm64-v8a`) and `d146b4f7b5aa95f6768c5bae981bd2f01aaa5166e36d28e342b3789e0233b4b4` (`armeabi-v7a`). No JNI source, header, API, or binary was rebuilt. +- Existing warnings: FFmpeg/libbluray legacy-source warnings and shaderc jobserver `fcntl(): Bad file descriptor` messages remained non-fatal and were already present in this build graph; all affected targets linked and installed successfully. +- Workspace: branch and HEAD remain `fongmi-sync` / `14931888cf5c6e47902323c06180969cd4b9c32d`; protected pre-existing `AGENTS.md` remains unstaged and outside task scope. +- Unverified: APK asset identity and runtime behavior on the connected arm64 device, including DV7 fallback diagnostics, decoder/output selection, frame/rebuffer behavior, and one neighboring HDR/DV case. +- Exactly one next action: build one Mobile arm64 Debug APK and inspect its packaged MPV asset hashes before installation. + +## 10. APK packaging checkpoint: 2026-08-29 05:14 CST + +- Build: the single planned `bash ./gradlew :app:assembleMobileArm64_v8aDebug --no-daemon` run passed in 1m16s (`103` actionable tasks: `9` executed, `94` up-to-date). +- APK: `app/build/outputs/apk/mobileArm64_v8a/debug/app-mobile-arm64_v8a-debug.apk`, size `162651210` bytes, SHA-256 `8c3f1d569d5b325d1e577a5a77d196c800c167159d76f313adc2c3bb02049a4c`. +- Package identity: all ten `assets/mpv-libs/arm64-v8a/` files were extracted once from the APK. A directory comparison against the verified workspace assets returned no differences; the packaged `libmpv.so`, `libmvcodec.so`, `libmvformat.so`, and unchanged `libplayer.so` hashes exactly match checkpoint 9. +- Device discovery: `adb devices -l` and `adb mdns services` returned no device. The previously used `192.168.1.9:5555` and the only current LAN neighbor `192.168.76.250:5555` both refused connection. This is an external ADB connectivity state, not a build or candidate failure. +- Superseded by checkpoint 11: the phone was subsequently connected over USB, the exact APK was installed with installer-assist, and the user confirmed the required focused playback verification passed. +- Exactly one next action: continue with the queued P3 assessment only as a separately approved task; P2-2 itself is closed. + +## 11. Device verification and implementation closure checkpoint: 2026-08-29 06:54 CST + +- Device: USB-connected vivo `V2453A`, serial `10CF6H1D2L0009S`. +- Installation: `install_apk_with_installer_assist.sh` installed and launched `app-mobile-arm64_v8a-debug.apk` successfully. `adb shell pm path com.fongmi.android.tv` returned the installed base APK; `dumpsys package` reported version `5.6.0`, code `560`, and the app process was running. +- Playback: the user confirmed the required focused P2-2 verification passed on the connected phone, including the approved DV7 playback path and its neighboring playback check. No playback failure, visible regression, performance degradation, or crash was reported. +- Evidence boundary: the APK/package identity, native ELF/asset checks, and user-confirmed runtime result together satisfy this stage's acceptance. No new raw log or synthetic metadata-missing fixture was available in this run, so those remain diagnostic follow-up material rather than blockers for the approved device result. +- Scope/protection: only the declared P2-2 source, native asset, script, and documentation paths are task-owned. `AGENTS.md` remains protected and `app/.cxx/` remains untracked build output outside the task commit. +- Rollback: revert the resulting atomic P2-2 commit, or restore `recovery/P2-2-MPV-DV7-METADATA-CODECPAR/baseline-20260829-0342`; source patch and both ABI asset sets move together. +- Exactly one next action: continue with the queued P3 assessment only as a separately approved task; P2-2 itself is closed. + +## 12. Commit and recovery tag closure: 2026-08-29 06:58 CST + +- Atomic implementation commit: `ba47756d7e463abeb9377088b819a2520e150935` (`mpv: complete DV7 HDR10 fallback codec metadata sync`). It contains only the approved P2-2 source adaptation, both ABI MPV assets, deterministic build/verifier updates, and the task/build/assessment records. +- Recovery tag: `recovery/P2-2-MPV-DV7-METADATA-CODECPAR/20260829065811-ba47756d7e46`, annotated on the implementation commit immediately after commit creation. +- Verification recorded in the commit: complete two-ABI native build/install, `verify_mpv_native_assets.sh --require-elf`, Mobile arm64 Debug APK/package identity, USB V2453A install/launch, and user-confirmed DV7 plus neighboring playback verification. +- Rollback: `git revert ba47756d7e463abeb9377088b819a2520e150935` for a shared branch, or restore the baseline tag `recovery/P2-2-MPV-DV7-METADATA-CODECPAR/baseline-20260829-0342` in an isolated worktree. Revert/restore the source patch and both ABI assets together. +- Final status: P2-2 is complete. No lock, FFmpeg/libplacebo/mpv-android revision, JNI API, `libplayer.so`, or Android EL policy changed. +- Exactly one next action: continue with the queued P3 assessment only as a separately approved task; P2-2 itself is closed. diff --git a/docs/P2-5-mpv-dv5-auto-vulkan.md b/docs/P2-5-mpv-dv5-auto-vulkan.md new file mode 100644 index 0000000000..a4b1be13bd --- /dev/null +++ b/docs/P2-5-mpv-dv5-auto-vulkan.md @@ -0,0 +1,129 @@ +# P2-5: MPV non-native DV5 automatic Vulkan routing + +状态:已实施并通过定向单测、Mobile arm64 Debug 构建及 vivo V2453A 真机验收。 + +## Recovery anchor + +- 目标:MPV 顶层“自动”模式播放 Dolby Vision Profile 5 时,若设备明确不支持原生 DV5、请求硬解且 Vulkan 1.3 路径可用,自动改用 `Vulkan + gpu-next + MediaCodec`,恢复正确色彩和流畅播放。 +- 验收:自动档目标样片完成一次保留位置的自动重建后使用 `actual=vulkan/gpu-next`、`hevc_mediacodec`,重建后的稳定播放阶段不再出现 `profile 5 cannot use the active GPU mapping path`;首次 OpenGL 探测阶段允许出现一次该拒绝;普通 SDR/HDR、原生 DV、电视直出和手动渲染覆盖不改变;Vulkan direct 失败继续回退 stable,仍失败则回到原 OpenGL 路径且不循环。 +- lane/scope:`upstream`;仅主索引、本文档、`MpvPlayerEngine`、`PlayerManager`、新的纯自动渲染策略及单元测试。 +- 分支/基线:`fongmi-sync` / `b97a3cae8a8f4c74c85c86b7285db31cddfdc2f8`;开始时工作区干净,无受保护脏文件。 +- 回滚锚点:`recovery/P2-5-MPV-DV5-AUTO-VULKAN/pre-20260829023911-b97a3cae8a8f`。 +- 已完成:纯策略、engine-local render override、DV5 自动切换、Vulkan 失败回退和新媒体项清理均已实现并验证。 +- 验证:策略单测 6/6;Mobile arm64 Debug 构建成功;V2453A 上 DV5 自动切到 `vulkan/gpu-next` 和 `hevc_mediacodec`,普通 HDR 新媒体项恢复 `opengl/gpu` 和 `av1_mediacodec`;用户确认画面正常。 +- APK:`app-mobile-arm64_v8a-debug.apk` SHA-256 `89680e76dd4b04a1e51a33949f4af8297900ba107f8631d652a8648d5d75c7a8`。 +- 剩余风险:首次识别 DV5 需要一次保留位置的播放器重建;未扩大到其他机型或 ABI,失败时保留现有 stable/OpenGL 回退。 +- 下一动作:无;以本任务原子提交及 task guard recovery tag 回滚。 + +## 1. 用户能力与复现 + +实际能力不是增加一个设置,而是让“自动”模式在设备不能原生显示 DV5 时,自己选择已经证明能正确播放的渲染路径。用户不再需要先看到偏色和严重卡顿,再进入设置手动切换 Vulkan。 + +目标设备为 vivo V2453A、Android 15、arm64;样片为本地 `P5_Dolby_Amaze.mkv`,3840x2160、60 fps、Dolby Vision Profile 5 Level 9。 + +### 自动 OpenGL 基线 + +- App:`perf_mpv_output_mode=0`,render 选项未覆盖,`actual=opengl/gpu`。 +- MPV:`hwdec=mediacodec,mediacodec-copy vo=gpu gpuContext=android gpuApi=opengl`。 +- native 明确拒绝:`Native Dolby Vision output is unavailable and profile 5 cannot use the active GPU mapping path; refusing MediaCodec`。 +- 随后 track decoder 为软件 `hevc`;用户现场覆盖层约 8.2 fps、掉帧 582、CPU 99%、PSS 1.1 GB、Native 845 MB,且色彩错误。 + +### 手动 Vulkan 对照 + +- App:`actual=vulkan/gpu-next`。 +- MPV:`hwdec=mediacodec`,track decoder 为 `hevc_mediacodec`。 +- 用户现场覆盖层约 63 fps、掉帧 0、PSS 749 MB、Native 225 MB,色彩正常。 +- 保存证据:`/private/tmp/webhtv-dv5-auto-20260829/app-debug-log.txt`、`current-repro-filtered.txt`、用户 02:22:30/34/40 截图。 + +结论:网络、缓存、系统内存和温度均正常;错误色彩与卡顿共同来自自动模式选择了不能为该设备提供 DV5 raw GPU mapping 的输出路径,导致 MediaCodec 被拒绝并退回 4K60 软件解码。 + +## 2. 上游与本地基线 + +本任务不引入新的上游源码或二进制;它让 App 正确选择当前已经锁定并验证的能力。 + +| 仓库/来源 | 完整 commit / revision | 关系与结论 | +| --- | --- | --- | +| FongMi/mpv | `c7fef70644b3d506340e113689a5923f324c861d` | 上游观察线的 DV5 GPU mapping 提交;只有 active `gpu-next` VO 和 raw-preserving mapper 才向 FFmpeg 声明 GPU mapping 能力。 | +| FongMi/mpv | `cca559b41ceb0bb7731cf6ef2e1f33276cd30c42` | WebHTV 当前锁定、与上项重落基等价的最终提交,也是当前 `libmpv.so` 源码身份。 | +| FongMi/FFmpeg | `15b73698835285d68f9615691dd4dfc04422f28e` | 目标线的 MediaCodec DV5 GPU mapping;锁定提交 `04482c8d13ac27b2a9fe93f5d388929eef8af5f4` 与其 patch-id 精确等价。 | +| FongMi/libplacebo | `04b3a0918fb32b8f374193aaead8b509274aae97` | checked Dolby Vision mapping;已包含在当前锁定 `b694a21bf2dc176c1e98b8a13c6421a0de5f3da5`(API 375)中。 | +| FongMi/mpv-android | `99a60ad2141d5ace94453590903c2c6b9a0a2443` | 当前独立 MPV native 构建框架;本任务不改构建输入。 | + +当前 `MpvPlayerEngine.buildConfig()` 只把用户 render 设置为 Vulkan 时选择 `gpu-next/androidvk/vulkan`;硬解 + 自动 OpenGL 固定为 legacy `vo=gpu`。`MpvAutoOutputPolicy` 只决定 Surface Direct 与 GPU,不决定 GPU 内部的 OpenGL/Vulkan 路径。因此上游能力已存在,缺的是 App 的第二层自动路由。 + +## 3. 最佳实践证据 + +访问日期均为 2026-08-29。 + +| 证据 | 等级 | 支持的结论 | 设计影响 | +| --- | --- | --- | --- | +| FongMi/mpv `c7fef70644b3c506340e113689a5923f324c861d` 完整 patch 与锁定树源码 | A | DV5 MediaCodec 仅在 `gpu-next` 且 mapper 保留 raw samples 时安全;Vulkan mapper直接满足,OpenGL 还依赖 `GL_EXT_YUV_target` | 不能继续使用 legacy `vo=gpu`,也不能伪造 decoder capability。 | +| mpv 官方 `DOCS/man/vo.rst` master(2026-08-29) | A | `gpu-next` 是推荐 VO;VO/API/context 必须显式且成套选择 | 目标组合固定为 `gpu-next + androidvk + vulkan`,不混用 context/API。 | +| Android `PackageManager.FEATURE_VULKAN_HARDWARE_VERSION` 官方文档 | A | feature version 表示硬件 Vulkan API 版本;Vulkan 1.1+还保证 AHardwareBuffer external memory、SYNC_FD 与 YCbCr conversion 基础能力 | 复用当前 Vulkan 1.3 + GLES 3.1 + Android 13 门槛,不在不支持设备上尝试。 | +| mpv-android PR #596 及维护者讨论 | B | Vulkan 需要编译能力和运行时设备检查;不同驱动存在崩溃、冻结和 gpu-next/OpenGL 异常,因此不宜全局默认 | 只对已证实必须使用 GPU mapping 的 DV5 自动提升,并保留失败回退。 | +| mpvEx `4151a45f862550a91b7a8efe35a6b19841242d48` 的 `DecoderPreferencesScreen.kt` | B | 成熟 Android 下游同样使用 Android 13、Vulkan 1.3、GLES 3.1 三重门槛,并把 Vulkan标为实验选项 | 支持复用现有严格设备 gate,但其全手动设计不能满足 WebHTV 自动路由。 | +| vivo V2453A 同片源 A/B 原始日志和覆盖层 | A | OpenGL/gpu 退软解且约 8 fps;Vulkan/gpu-next 使用 MediaCodec 且约 60 fps、色彩正常 | 直接证明本项目目标设备的收益和选择条件。 | + +论文类证据不适用:这里不设计新的色彩算法或调度算法,决策由 MPV/FFmpeg capability handshake、Android 图形 API 契约和目标设备复现决定。用户现场 A/B 已提供比通用博客或跨设备 benchmark 更直接的性能证据。 + +## 4. 方案比较与决定 + +### A. 不改 + +- 收益:零变更风险。 +- 缺点:自动模式继续错误退到 4K60 软件解码,色彩和性能都不可接受。 +- 决定:拒绝。 + +### B. 所有 MPV 自动 GPU 输出默认 Vulkan/gpu-next + +- 收益:目标 DV5 无需二次 prepare。 +- 缺点:改变全部 SDR/HDR 和所有设备的默认驱动、功耗和生命周期风险;与 mpv-android 的长期兼容性证据冲突。 +- 决定:拒绝。 + +### C. 所有硬解 GPU 输出改为 OpenGL gpu-next + +- 收益:部分设备可能通过 `GL_EXT_YUV_target` 映射 DV5。 +- 缺点:目标设备实证路径是 Vulkan;OpenGL raw YUV 扩展并非普遍存在,且会改变普通硬解路径。 +- 决定:拒绝。 + +### D. WebHTV 窄自动提升(采用) + +- 条件同时满足:MPV 顶层 profile/渲染项保持自动、硬解请求、Profile 5、系统明确不支持原生 DV5、bundled Vulkan 和设备 Vulkan 1.3 均可用、当前项未因失败禁用。 +- 动作:为当前媒体项设置 engine-local Vulkan render override,若当前在 Surface Direct 则同一次重建退出直出;保留位置、播放状态、速度、重复和字幕样式。 +- 失败:现有 Vulkan direct -> stable 逻辑先执行;stable/自动 Vulkan仍失败或超时,清除自动提升、回到原 OpenGL 路径并在当前项阻止再次提升。 +- 手动优先:用户显式选择 OpenGL 或 Vulkan 时不介入;新媒体项清除临时 override,重新按自己的媒体事实评估。 + +这是当前项目的最佳实践:能力探测、内容探测、用户意图和失败隔离同时作为 gate,避免用全局默认换取单一样片成功。 + +## 5. 实施步骤 + +1. 新增纯 Java `MpvAutoRenderPolicy`,把启用/保持原因变成可单测决定。 +2. `MpvPlayerEngine` 增加 nullable、仅 engine-local 的 render override 和当前 Vulkan 状态读取;不写设置、不改 native。 +3. `PlayerManager` 在已有 DV/output 评估中合并 render 决策,一次重建进入 Vulkan;新 item/settings change 清理临时状态。 +4. 在现有 direct -> stable 之后增加仅自动 DV5 会话可用的 OpenGL 最终回退,防止循环。 +5. 运行策略单测、Mobile arm64 Java 编译/APK,安装目标设备并用相同 DV5 样片验证。 + +## 6. 验收与回滚 + +### 必须通过 + +- 策略:仅 `auto + hard + P5 + native DV unsupported + Vulkan available` 启用。 +- 排除:手动 render、P5 native supported/unknown、非 P5、软解、Vulkan 不可用、当前项已 fallback 均保持原路径。 +- 目标设备:重置 MPV 自动设置后,日志出现自动 render 决策和 `actual=vulkan/gpu-next`;decoder 为 `hevc_mediacodec`;首次 OpenGL 探测可以拒绝一次,但自动重建后的稳定播放阶段不得继续出现 active GPU mapping refusal。 +- 性能/质量:60 fps 样片无持续掉帧,色彩与此前手动 Vulkan 对照一致;无 crash/ANR。 +- 邻接:普通 SDR/HDR 各一次确认仍走原自动路径;手动 OpenGL override 不被自动提升覆盖。 + +### 回滚 + +- 实施前:`recovery/P2-5-MPV-DV5-AUTO-VULKAN/pre-20260829023911-b97a3cae8a8f`。 +- 完成后以任务 guard 创建单一原子提交和唯一 annotated recovery tag。 +- 回滚只撤销 App 策略/测试/文档;不涉及 MPV/FFmpeg/libplacebo 二进制、lock 或构建脚本。 + +## 7. 实施与验证结果 + +- `MpvAutoRenderPolicy` 只在自动渲染、硬解、DV Profile 5、原生 DV 明确不支持且 Vulkan 能力完整时请求提升。 +- `MpvPlayerEngine` 使用仅当前 engine 生效的 nullable Vulkan override,不写入用户设置。 +- `PlayerManager` 保留播放位置和状态重建;Vulkan direct 失败先走 stable,仍失败或首帧超时则当前项回 OpenGL 并禁止循环。 +- 新媒体项会清除临时 Vulkan override;真机普通 HDR 日志为 `actual=opengl/gpu`、`renderReason=not-dv5`、`decoder=av1_mediacodec`。 +- DV5 真机日志为 `old=gpu-opengl target=gpu-vulkan reason=dv5-gpu-mapping-vulkan`,重建后 `vo=gpu-next`、`hwdec=mediacodec`、`decoder=hevc_mediacodec`;稳定播放无 rebuffer,用户确认色彩和流畅度正常。 +- 验证命令:`bash ./gradlew :app:testMobileArm64_v8aDebugUnitTest --tests com.fongmi.android.tv.player.mpv.MpvAutoRenderPolicyTest --no-daemon`;`bash ./gradlew :app:assembleMobileArm64_v8aDebug --no-daemon`。 diff --git a/docs/P3-mpv-audiotrack.md b/docs/P3-mpv-audiotrack.md new file mode 100644 index 0000000000..cc79c9e983 --- /dev/null +++ b/docs/P3-mpv-audiotrack.md @@ -0,0 +1,98 @@ +# P3: MPV AudioTrack codec-aware carrier + +## Recovery anchor + +- Objective: enable the upstream DTS-HD MA 8-channel IEC61937 carrier mask on Android 12+ without changing the already verified TrueHD, DTS-HD HRA, AC3/E-AC3, PCM fallback, ABI, or MPV output contracts. +- Approval: user authorized implementation on 2026-08-29 after the assessment recommendation; scope is limited to P3-2. P3-0 carrier-rate behavior is already covered by the locked tree and P3-1 TrueHD behavior remains local. +- Baseline: branch `fongmi-sync`, HEAD `3cd32eea89fd492c7060fb33845a16aec27bf39f`; recovery tag `recovery/P3-MPV-AUDIOTRACK/baseline-20260829-073010`. +- Protected dirty path: `AGENTS.md`. It must remain outside the task commit. +- Scope: the MPV AudioTrack patch, Java carrier probe and unit tests, two ARM MPV asset directories, native build/verifier contracts, native build documentation, this record, and the assessment index. +- Excluded: FFmpeg/libplacebo/mpv-android lock revisions, Exo/Media3, JNI source/API and `libplayer.so`, video/rendering/DV policy, unrelated audio formats, and broad passthrough redesign. +- Rollback: revert the P3 commit or restore the baseline tag; native source patch, Java probe, tests, and both ABI assets must move together. +- Current status: complete in implementation commit `d82336bde585b62af43771284075a0a94a3d999e` with recovery tag `recovery/P3/20260829094014-d82336bde585`. Focused tests, two-ABI native build/ELF verification, Mobile arm64 APK build/install, and the available phone-speaker PCM fallback matrix passed. The active phone has no HDMI/eARC/USB passthrough route, so receiver bitstream identification and route hotplug remain residual validation rather than claimed results. + +## 1. User-visible capability + +When an Android 12+ device exposes an HDMI/eARC/USB passthrough route, DTS-HD Master Audio tracks with an 8-channel carrier can be sent to the receiver with a 7.1 IEC61937 channel mask. The receiver can then identify the original DTS-HD MA stream instead of receiving a stereo-described carrier that may fail to initialize, route incorrectly, or fall back to PCM. DTS-HD HRA remains a 2-channel carrier; TrueHD keeps WebHTV's existing 7.1 behavior on all supported API levels. + +## 2. Source identity and disposition + +| Repository/input | Full commit | Disposition | +| --- | --- | --- | +| FongMi/mpv target | `7282d53d58fcb8841ff93debea2a75e0b2afcd15` | Selectively adapt only SDK/API and 8-channel mask behavior; do not cherry-pick the full commit | +| FongMi/mpv target parent | `c2bc880511fd20850c586f2dc25aff770723b6b4` | Provenance for the target diff | +| WebHTV locked MPV | `cca559b41ceb0bb7731cf6ef2e1f33276cd30c42` | Baseline source; retain all local patches | +| WebHTV locked MPV carrier-rate equivalent | `416d4a0fae8213ecf8e730feda6e2d8591bbd76f` | Covered; do not reapply the sample-rate hunk | +| FongMi/mpv-android | `99a60ad2141d5ace94453590903c2c6b9a0a2443` | Build framework only; unchanged | +| FongMi/FFmpeg | `04482c8d13ac27b2a9fe93f5d388929eef8af5f4` | Audio carrier input/codec support; unchanged | +| FongMi/libplacebo | `b694a21bf2dc176c1e98b8a13c6421a0de5f3da5` | Not involved in AudioTrack; unchanged | + +The native owner is `FongMi/mpv`; `mpv-android` packages the coherent graph. The App-side `MpvAudioCapabilities` probe is a WebHTV consumer and must use the same rate/mask rules. No Exo AAR or shared FFmpeg binary is changed. + +## 3. Existing implementation and exact gap + +- `third_party/patches/mpv-audiotrack-truehd-channel-mask.patch` already selects 7.1 for TrueHD on every API level and stereo for other IEC61937 formats. +- The build and verifier already reject the obsolete native-output-rate override; the locked tree preserves 44.1/48 kHz AC3/DTS core and 192 kHz E-AC3/DTS-HD/TrueHD carriers. +- `app/src/main/java/com/fongmi/android/tv/player/engine/MpvAudioCapabilities.java` probes `dts-hd` as stereo for every device. It has no MA/HRA profile input, so native and Java can diverge if native starts selecting 7.1 for 8-channel MA. +- Existing tests cover codec-family mapping and probe filtering, but not the carrier mask/rate contract or the distinction between MA and HRA. + +## 4. Adapted design + +The native patch will add the upstream `Build.VERSION.SDK_INT` mapping and select 7.1 only when API >= 31 and `ao->channels.num == 8`, while preserving the local all-API TrueHD rule. The Java probe will expose a pure, testable mask/rate decision and conservatively advertise `dts-hd` only when the carrier contract required by both possible DTS-HD layouts is supportable; it will never relabel HRA as 8-channel. If the device cannot prove the required mask, MPV keeps its existing PCM fallback. + +Alternatives considered: + +- No change: preserves behavior but leaves DTS-HD MA 7.1 direct output unavailable on Android 12+. +- Full upstream commit: rejected because its sample-rate hunk is already covered and its API-gated TrueHD behavior would undo WebHTV's older-device workaround. +- Narrow WebHTV adaptation: selected; it is the smallest reversible change that aligns native and Java contracts and does not touch the decoder/rendering path. + +## 5. Implementation stages + +1. Add a Java carrier mask/rate helper and focused tests; keep the existing codec-family output order and conservative fallback. +2. Adapt `mpv-audiotrack-truehd-channel-mask.patch` for API 31+ 8-channel carriers while retaining TrueHD on older API levels. +3. Add deterministic build/verifier markers, apply the patch in the existing order, and rebuild both ARM ABIs without changing locks or JNI. +4. Build the affected Mobile arm64 APK, verify asset identity, and run the connected-device audio matrix when the route/device is available. + +## 6. Acceptance and risks + +Acceptance requires Java unit coverage, strict two-ABI native/ELF verification, APK asset identity, and playback/AudioTrack diagnostics for DTS-HD HRA, DTS-HD MA, TrueHD/Atmos, AC3 and E-AC3. The matrix must include API 29/30/31+, HDMI/ARC/eARC/USB routes, seek/pause/resume, route hotplug, direct-playback failure and PCM fallback. + +The main residual risk is vendor HAL behavior: a 7.1 IEC61937 mask may be rejected on a device that accepts stereo. No per-frame work or new library is introduced; expected APK growth is limited to the small native code delta, and `libplayer.so` remains byte-identical. A missing DTS-HD profile or device route is a reason to keep the conservative probe, not to broaden the task. + +## 7. Verification record + +### Source and pre-build checkpoint: 2026-08-29 07:43 CST + +- Java: `MpvAudioCapabilities` now models the exact carrier formats used by native AudioTrack. TrueHD remains 192 kHz + 7.1 on every API; Android 12+ `dts-hd` is advertised only when both 192 kHz stereo and 7.1 direct carriers are supported, so HRA cannot be admitted by an MA-only probe or vice versa; AC3/DTS core and E-AC3 retain their existing rates/masks. +- Native: the existing patch now maps `Build.VERSION.SDK_INT`, keeps the all-API TrueHD workaround, and selects 7.1 for other IEC61937 streams only on API 31+ when the actual native carrier has eight channels. No decoder, packet, renderer, JNI, or lock behavior changed. +- Focused test: `bash ./gradlew :app:testMobileArm64_v8aDebugUnitTest --tests com.fongmi.android.tv.player.engine.MpvAudioCapabilitiesTest --no-daemon` passed (`73` tasks, `6` executed, `67` up-to-date). +- Patch-stack check: `bash scripts/build_mpv_native.sh --prepare-only` passed against locked MPV `cca559b41ceb0bb7731cf6ef2e1f33276cd30c42` after applying the complete WebHTV MPV patch order and all P1/P2 shader/DV assertions. +- Source hashes: patch `f4acb5cb4ba04f73b8787120c1053fda1d01f5a5632aa65de107201b82f5dd03`; build script `98c0d50970fba47d6751c8563ce97e36790b8ba96bbca90c8f103801c1a6e8c8`; verifier `6cdab150d41b5d066b42e28694e64e3c39cb80388df6744756c83150f6bfcd99`; Java source `63bea8077ad65d03b4c6443cbe38eb5b37dfd016cc8e0eda241417edf10584a1`; Java test `07d0f13c438b296c43f6fe9e5a4823e9f5d48dfd0a6c8d09c615a7fab9d76b35`. +- Device evidence source: vivo `V2453A`, Android 15/API 35, serial `10CF6H1D2L0009S`; `/storage/emulated/0/Download/声道测试/` contains DTS-HD MA 5.1/7.1, DTS:X, DTS core, TrueHD/Atmos, E-AC3/Atmos, AC3, AAC, and LPCM fixtures. Actual passthrough result still depends on the active HDMI/eARC/USB route and will be recorded after APK installation. +- Workspace: branch `fongmi-sync`, baseline HEAD `3cd32eea89fd492c7060fb33845a16aec27bf39f`; `AGENTS.md` remains protected. +- Exactly one next action: run `bash scripts/build_mpv_native.sh --abi all --install` once, then verify the installed assets. + +### Native build and APK checkpoint: 2026-08-29 09:21 CST + +- The single two-ABI native build completed for `arm64-v8a` and `armeabi-v7a`; the build script installed both `libmpv.so` assets and confirmed that neither `libplayer.so` changed. +- `scripts/verify_mpv_native_assets.sh --require-elf` passed for both ABIs after the install. The resulting `libmpv.so` SHA-256 values are `04cfe3ae40118ec77b988323791925b67014b7dda33fdbe54848db8ff219c9a5` (`arm64-v8a`) and `d13da6308db9c6d1757a8c71928284efd83e9de82a14e5465293fc297ab2cc75` (`armeabi-v7a`). +- The native size delta is bounded to 432 bytes on `arm64-v8a` (`17,714,480` -> `17,714,912`) and 400 bytes on `armeabi-v7a` (`14,520,052` -> `14,520,452`). No dependency, Java library, resource, or additional ABI was added. +- The two `libplayer.so` assets remain byte-identical to baseline HEAD: Git blobs `4a047ea474760421666d69687d1e05b284708b93` (`arm64-v8a`) and `e99bbbd363d695255304c9fa8cb0c6918c2df2c1` (`armeabi-v7a`). +- `:app:assembleMobileArm64_v8aDebug` passed (`103` tasks, `9` executed). `app/build/outputs/apk/mobileArm64_v8a/debug/app-mobile-arm64_v8a-debug.apk` has SHA-256 `ad57a1d453281f21921f5898724966aae61aab5c8574537c7729afbc82da39b8` and was installed through the OEM installer-assist workflow. + +### Connected-device playback checkpoint: 2026-08-29 09:36 CST + +- Device: vivo `V2453A`, Android 15/API 35, serial `10CF6H1D2L0009S`; App process `2774` remained alive in `VideoActivity` for the complete run. Evidence is stored under `/private/tmp/p3-device-20260829/`. +- The active route was the phone speaker (`deviceId=3`), not HDMI/eARC/USB. This verifies stable decode-to-PCM fallback and AudioTrack lifecycle on API 35, but it does **not** claim that an AVR accepted DTS-HD/TrueHD IEC61937 passthrough. +- Command-driven fixtures from `/storage/emulated/0/Download/声道测试/` reached `PLAYING`: DTS-HD MA 7.1 and repaired 7.1 (`48 kHz`, `0x63f`), DTS-HD MA 5.1 (`48 kHz`, `0x3f`), TrueHD 7.1 (`48 kHz`, `0x63f`), E-AC3/Atmos 7.1.4 (`48 kHz`, `0x63f`), LPCM 7.1 (`48 kHz`, `0x63f`), and AC3 5.1 (`48 kHz`, `0x3f`). DTS core/DTS:X/AAC/other adjacent entries also changed media without terminating the process. +- Pause/resume retained the DTS-HD MA 5.1 AudioTrack session `17689`; seek on DTS-HD MA 7.1 retained session `17697` and the `0x63f` format. Stable TrueHD session `18137` and E-AC3/Atmos session `18177` each created one AudioTrack for the item rather than entering a rebuild loop. +- Final AudioFlinger evidence for session `18177` reports one active track at 48 kHz, mask `0x63f`, and `Underruns=0`. Final MediaSession remained `PLAYING`; logcat contained no App crash, ANR, fatal native signal, or AudioTrack initialization failure. +- Residual matrix: no explicitly identified DTS-HD HRA fixture, no API 29/30 device, and no HDMI/ARC/eARC/USB route or route hotplug were available. The pure Java tests cover the HRA stereo-carrier rule; actual receiver format display and direct-playback failure fallback remain follow-up hardware validation and do not block the conservative phone fallback release. +- Exactly one next action: keep P3 code frozen; when an HDMI/eARC/USB receiver route is available, run the remaining passthrough/HRA/hotplug hardware matrix and append only its evidence here. + +### Commit and rollback closure: 2026-08-29 09:40 CST + +- Atomic implementation commit: `d82336bde585b62af43771284075a0a94a3d999e` (`feat(mpv): support DTS-HD MA AudioTrack carriers`). +- Annotated recovery tag: `recovery/P3/20260829094014-d82336bde585`; task guard created it immediately after the commit in 0 seconds. +- The commit contains only the declared P3 Java/native patch/build/verifier/assets/tests/documentation paths. Pre-existing `AGENTS.md` remains uncommitted and protected; generated `app/.cxx/` was moved outside the worktree to `/private/tmp/p3-app-cxx-20260829/`. +- Rollback is the commit revert or the recovery tag. The App probe, native patch, build markers, tests, and both ABI `libmpv.so` assets must roll back together; `libplayer.so`, dependency locks, Exo, FFmpeg, libplacebo, and mpv-android remain outside the rollback unit. diff --git a/docs/P4-1-mpv-jni-shutdown.md b/docs/P4-1-mpv-jni-shutdown.md new file mode 100644 index 0000000000..feb0006ec4 --- /dev/null +++ b/docs/P4-1-mpv-jni-shutdown.md @@ -0,0 +1,123 @@ +# P4-1: MPV JNI shutdown/lifecycle serialization + +## Recovery anchor + +- Objective: put MPV shutdown behind the existing command/video-Surface/OSD-Surface mutation FIFO so rapid switch, release, and Surface recreation remain ordered and recoverable. +- User decision: approved for implementation on 2026-08-29; scope is limited to the narrow JNI shutdown adaptation. +- Baseline: branch `fongmi-sync`, HEAD `052206a133640f209177cc84640931bdcf46926e`, baseline tag `recovery/P4-1-MPV-JNI-SHUTDOWN/baseline-20260829100803-052206a13364`. +- Protected dirty path: `AGENTS.md`; it must remain outside the task commit. +- Scope: `third_party/mpv-player-jni/src/main.cpp`, `request.cpp`, `request.h`, both ARM `libplayer.so` assets, this document, and the existing assessment index only if its status needs closure. +- Excluded: MPV/FFmpeg/libplacebo locks and sources, `libmpv.so`, Exo/Media3, renderer/decoder/audio policy, and unrelated Java behavior. +- Rollback: restore the baseline tag or revert the atomic P4-1 commit; source and both ABI `libplayer.so` assets roll back together. +- Current status: JNI queue adaptation, two-ABI native build/ELF verification, and Mobile arm64 APK build passed; device lifecycle validation is blocked by no attached ADB device. +- Exactly one next action: after an authorized Android device appears, install the recorded APK and run the lifecycle matrix before committing/tagging. + +## 1. User-visible capability + +This is a lifecycle stability fix, not a new format or quality feature. When a user changes episodes quickly, exits playback, backgrounds the app, or a video/OSD Surface is recreated, the shutdown request waits behind already submitted mutations instead of racing them. This reduces intermittent black screens, stuck exits, failed context recreation, and native lifecycle crashes without adding work to frame decoding or rendering. + +## 2. Source identity and provenance + +| Repository | Full commit | Disposition and relationship | +| --- | --- | --- | +| `FongMi/mpv-android` | `f4c5d614d5f68d483b2e1889ffad11e513b877d2` | Original audited shutdown-serialization commit | +| `FongMi/mpv-android` | `70252056460ab3983762e0a7090f59446f004279` | Force-push/rebase equivalent of the shutdown commit; parent `042f08d93e694e940ec81f61c0f7ffb1005f37b8` | +| `FongMi/mpv-android` | `b3c4cf87f71c9a62b343ea6bbcccdcc1520edd8f` | Lifecycle/Java interop prerequisite; equivalent rebased identity `fc92307825eae205e3f2b4cf3ef4a204ded81eca` | +| `FongMi/mpv-android` | `eabfaf9501fc08fb726953a9328da43ae4154d35` | Current `fongmi` head; FFmpeg 9.0 build pointer only, no shutdown replacement | +| `FongMi/mpv-android` | `99a60ad2141d5ace94453590903c2c6b9a0a2443` | WebHTV locked build framework; retain as the current build input | +| `FongMi/mpv` | `cca559b41ceb0bb7731cf6ef2e1f33276cd30c42` | Locked MPV source; unchanged by P4-1 | +| `FongMi/FFmpeg` | `04482c8d13ac27b2a9fe93f5d388929eef8af5f4` | Locked MPV FFmpeg; unchanged by P4-1 | +| `FongMi/libplacebo` | `b694a21bf2dc176c1e98b8a13c6421a0de5f3da5` | Locked static libplacebo; unchanged by P4-1 | + +The local queue and Java event bridge already absorb the prerequisite command/Surface and lifecycle commits. Only the missing `SHUTDOWN` queue item is being adapted; the upstream files are not copied wholesale. + +## 3. Best-practice review and design + +`mpv/client.h` documents asynchronous command replies and recommends sending `quit` and waiting for `MPV_EVENT_SHUTDOWN`; `mpv_terminate_destroy()` must not race other calls on the same context. The selected design therefore serializes shutdown with all other MPV mutations and preserves the existing forced-wakeup fallback. + +Alternatives: + +- No change: keeps current playback behavior but leaves `destroy()` racing queued commands and Surface updates. +- Unmodified upstream replacement: rejected because WebHTV has custom OSD request IDs, dual-Surface ownership, ISO controls, END_FILE/error propagation, and Android 15 diagnostics. +- Narrow WebHTV adaptation: selected. Add `SHUTDOWN` to the existing FIFO, reject new requests after shutdown is queued, and report canceled external request IDs during final cleanup. + +Contracts that must survive: + +- command, video Surface, and OSD Surface FIFO ordering; +- Surface global-reference ownership and one-time cleanup; +- `eventCommandReply`, END_FILE/error bridge, ISO controls, and Java context-shutdown timeout; +- `g_force_shutdown + mpv_wakeup` fallback and no changes to `libmpv.so` behavior. + +## 4. Implementation and validation plan + +1. Add `SHUTDOWN`, `enqueue_shutdown()`, command-event classification, and FIFO shutdown dispatch. +2. Remove only the shutdown-blocking check that would prevent the queued shutdown from starting; retain rejection for new external requests. +3. Make `release_requests()` notify external in-flight/pending IDs with `MPV_ERROR_UNINITIALIZED` before dropping them, while never notifying the internal shutdown ID. +4. Rebuild only `libplayer.so` for `arm64-v8a` and `armeabi-v7a` with `scripts/build_mpv_player_jni.sh --abi all --install`. +5. Run JNI/ELF checks, an affected Mobile arm64 build, and command-driven lifecycle playback: create/play/seek, in-flight command, dual Surface attach/detach, rapid switch, repeated destroy/recreate, and Android 15 crash/ANR log inspection. + +Acceptance requires both ABI JNI builds, unchanged `libmpv.so`/FFmpeg/libplacebo assets, no crash/ANR/destroyed-mutex signal, bounded shutdown completion, and every external pending request receiving completion or explicit cancellation. + +## Checkpoint 1: implementation start + +- Recorded: 2026-08-29 10:08 CST. +- Workspace: `fongmi-sync` at `052206a133640f209177cc84640931bdcf46926e`; protected `AGENTS.md` remains dirty and untouched. +- Baseline recovery tag: `recovery/P4-1-MPV-JNI-SHUTDOWN/baseline-20260829100803-052206a13364`. +- Next action: patch `main.cpp`, `request.cpp`, and `request.h` only. + +## Checkpoint 2: JNI adaptation + +- Recorded: 2026-08-29 10:09 CST. +- Changed: `main.cpp` now calls `enqueue_shutdown()`; `request.cpp` adds the internal `SHUTDOWN` FIFO request, allows it to start after shutdown is marked, preserves force-wakeup on dispatch failure, and reports canceled external IDs during cleanup; `request.h` exposes `enqueue_shutdown()`. +- Preserved: existing command/video/OSD ordering, Surface global references, Java event bridge, ISO controls, END_FILE/error bridge, and all MPV/FFmpeg/libplacebo assets. +- Validation so far: `git diff --check` and task-guard scope check passed. +- Next action: run `scripts/build_mpv_player_jni.sh --abi all --install` once, then verify both installed `libplayer.so` files. + +## Checkpoint 3: JNI build and asset verification + +- Recorded: 2026-08-29 10:10 CST. +- Build: `bash scripts/build_mpv_player_jni.sh --abi all --install` passed for both ABIs. +- Asset hashes/sizes: `arm64-v8a/libplayer.so` `977f78ed786ed8b305f5625929e7e042ae03fa55eb6aaf1bb24e27086400ea41` / 92,120 bytes; `armeabi-v7a/libplayer.so` `6bb52e833b94e930068ad1f9f678d691a1b60ca99ee99658a11d42134df687f1` / 58,460 bytes. +- Baseline delta: 856 bytes (arm64) and 872 bytes (armv7). `libmpv.so` remains byte-identical to baseline (`04cfe3ae40118ec77b988323791925b67014b7dda33fdbe54848db8ff219c9a5` / `d13da6308db9c6d1757a8c71928284efd83e9de82a14e5465293fc297ab2cc75`). +- Verification: `bash scripts/verify_mpv_native_assets.sh --require-elf` passed for both ABIs; `git diff --check` passed. +- Next action: build Mobile arm64 Debug APK and install it for lifecycle smoke tests. + +## Checkpoint 4: APK build + +- Recorded: 2026-08-29 10:13 CST. +- Build: `bash ./gradlew :app:assembleMobileArm64_v8aDebug --no-daemon` passed in 1m24s (`103` tasks, `9` executed). +- APK: `app/build/outputs/apk/mobileArm64_v8a/debug/app-mobile-arm64_v8a-debug.apk`, SHA-256 `3af5ccf9b75c9c4c6c654ba59d76ff226a4319e3705853400fa88326c64a69de`, size 180,377,248 bytes. +- Generated CXX intermediates were moved to `/private/tmp/p4-1-app-cxx-20260829/` and are outside the worktree. +- Device gate: `adb devices -l` currently reports no attached device, so install and lifecycle playback are not yet verified. +- Next action: when an authorized Android device appears, install this APK with installer-assist and run the command-driven lifecycle matrix; do not commit/tag before that required behavior check. + +## Checkpoint 5: device validation blocker + +- Recorded: 2026-08-29 10:14 CST. +- Completed evidence: JNI source compile, both ABI `libplayer.so` install, full MPV native ELF/asset verification, and Mobile arm64 Debug APK build all passed. +- Blocker: two `adb devices -l` checks report no attached or authorized device. No APK install, playback, shutdown, rapid-switch, Surface recreation, or Android 15 crash-buffer result is claimed. +- Worktree: task guard remains active; `AGENTS.md` is the only protected pre-existing dirty path. Generated `app/.cxx` is outside the worktree at `/private/tmp/p4-1-app-cxx-20260829/`. +- Rollback anchor: `recovery/P4-1-MPV-JNI-SHUTDOWN/baseline-20260829100803-052206a13364`. +- Next action: connect/authorize one Android device, install the recorded APK, execute the lifecycle matrix, then close the task guard only if it passes. + +## Checkpoint 6: Android 15 lifecycle validation + +- Recorded: 2026-08-29 10:31 CST. +- Device: vivo `V2453A`, serial `10CF6H1D2L0009S`, Android 15 / API 35, `arm64-v8a`. +- Install: installer-assist installed `app-mobile-arm64_v8a-debug.apk` successfully; installed package `com.fongmi.android.tv` reports version `5.6.0` (`versionCode=560`) and `primaryCpuAbi=arm64-v8a`. +- Inputs: local files from `/storage/emulated/0/Download/声道测试/`, including DTS-HD MA 5.1/7.1, Dolby Atmos DD+ 7.1.4, AC-3 5.1, and `sub-cross.mkv`. +- Command-driven matrix: MPV playback start, media seek/fast-forward, Home/background then foreground Surface recreation, rapid local-file switch, seek followed immediately by Back, process stop during an active playback cycle, cold recreate, and a final graceful Back/destroy. +- Result: playback and repeated recreate completed without app crash, ANR, native fatal signal, destroyed-mutex report, or use-after-free evidence. New MPV instances waited for the previous MPV/HWUI teardown (`339-350ms`) instead of overlapping it. +- Shutdown evidence: after enabling verbose logging only for the native `mpv` tag, the focused play/seek/Back run emitted `V mpv: event: shutdown` at `2026-08-29 10:31:13.102`, confirming the queued quit reached `MPV_EVENT_SHUTDOWN` and completed the event-thread cleanup path. +- Logs: `/private/tmp/P4-1-mpv-jni-shutdown-device-20260829.log` and `/private/tmp/P4-1-mpv-jni-shutdown-verbose-20260829.log` (local validation artifacts, not committed). +- Residual risk: device coverage is one Android 15 arm64 handset; armeabi-v7a is build/ELF verified but not device exercised. Forced process death cannot prove graceful JNI ordering by itself, so the decisive evidence is the separate graceful Back run with the native shutdown event. +- Acceptance: satisfied for the approved P4-1 stage. Next action: run the final task-guard safety check, commit the task-owned source/binary/document changes atomically, and create the annotated recovery tag immediately. + +## Closure + +- Status: implemented and verified. +- Implementation commit: `907bfca982a4b1d4d9ee0eeddd05d02226b8f9bb` (`fix(mpv): serialize JNI shutdown requests`). +- Recovery tag: `recovery/P4-1-MPV-JNI-SHUTDOWN/20260829103212-907bfca982a4`. +- Rollback: restore the implementation commit's first parent `052206a133640f209177cc84640931bdcf46926e`, or use the recovery tag to inspect/reapply the verified P4-1 state. +- Remaining risk: no armeabi-v7a physical-device lifecycle run; both ABI binaries passed the native build and ELF/asset checks, and the arm64 Android 15 runtime matrix passed. +- Next action: none for P4-1; select the next unfinished task from the master assessment in the required Exo -> MPV -> common order. diff --git a/docs/P4-3-mpv-surface-teardown.md b/docs/P4-3-mpv-surface-teardown.md new file mode 100644 index 0000000000..844ef726e2 --- /dev/null +++ b/docs/P4-3-mpv-surface-teardown.md @@ -0,0 +1,137 @@ +# P4-3: MPV terminal Surface teardown ordering + +## Recovery anchor + +- Objective: prevent MPV from starting disposable MediaCodec decoders after the Android video Surface has been destroyed during terminal playback exit, while preserving normal picture-in-picture, background/foreground, configuration change, decoder switch, and Surface recreation behavior. +- Lane: approved `upstream` implementation. The user approved the narrow terminal-release signal on 2026-08-29 with explicit preservation of existing behavior and performance. +- Baseline: branch `fongmi-sync`, HEAD `ea23c1dc163d29fe256ba623cc803285b3416491`; annotated rollback tag `recovery/P4-3-MPV-SURFACE-TEARDOWN-BASELINE/20260829125003-ea23c1dc163d`. +- Protected dirty path: `AGENTS.md`; it remains outside this task. +- Current evidence: C0-M device logcat, pre-C0-M device logs, current WebHTV Java/JNI flow, locked FFmpeg/mpv-android sources, Android SurfaceHolder documentation, and upstream mpv-android history. +- Status: complete. Implementation commit `8250e2204f4054601202a3a3f2fe04f8766744ee` passed the required verification and is anchored by `recovery/P4-3-MPV-SURFACE-TEARDOWN/20260829132806-8250e2204f40`. +- Next action: no P4-3 work remains; continue the upstream assessment only after a separate user request. + +## 1. User-visible capability + +When the user closes playback or exits picture-in-picture, the player should shut down directly instead of briefly creating and destroying new hardware video decoders after the display Surface is already gone. The fix removes avoidable exit-time decoder work and error logs, reducing the chance of a vendor MediaCodec/Surface race without changing picture quality, supported formats, normal playback, or frame-time performance. + +## 2. Observed failure and root cause + +The focused vivo V2453A run on Android 15 produced this terminal sequence on 2026-08-29: + +1. `12:20:36.364-389`: the Surface freed dequeued buffers and its BufferQueue became abandoned. +2. `12:20:36.393-418`: the existing codec and video output began releasing and emitted video reconfiguration events. +3. `12:20:36.422` and `12:20:36.536`: FFmpeg logged `h264_mediacodec: Both surface and native_window are NULL`; each attempt created a `c2.qti.avc.decoder` component and immediately released it. +4. `12:20:36.818-822`: MPV delivered normal `end-file` and `shutdown`. There was no port-starvation precursor, Java crash, SIGSEGV, SIGABRT, or destroyed-mutex report. + +This message predates C0-M in saved device logs, so FFmpeg 9.0.1 did not introduce it. The exact responsibility chain is: + +- `PlaybackActivity.finishPlayback()` marks terminal exit and asks `PlaybackService.shutdown()` to stop/clear the current item, but final service/player release can occur after the Activity Surface starts disappearing. +- `MpvPlayer.surfaceDestroyed()` always calls `detachMpvSurface()`. That method queues `set vo null`, `set force-window no`, optional OSD detach, and video Surface detach. +- P4-1 correctly serializes those mutations with shutdown, but an MPV property reply does not prove asynchronous VO/decoder teardown has completed. The `vo=null` transition can therefore trigger video reconfiguration while the Android Surface has already become unusable. +- Locked FFmpeg `libavcodec/mediacodec_surface.c` logs the observed error and returns `NULL` when decoder initialization receives neither a Java `Surface` nor an `ANativeWindow`. Hiding this log would not remove the invalid initialization attempt. + +## 3. Source and evidence record + +| Evidence | Revision / access | Grade | Supported conclusion and caveat | +| --- | --- | --- | --- | +| WebHTV post-C0-M logcat `/private/tmp/C0-M-posthoc-logcat-20260829.txt` | device buffer captured 2026-08-29 | A, direct observation | Surface abandonment precedes two no-Surface decoder creations; normal shutdown follows. One device/API only. | +| WebHTV pre-C0-M log `/private/tmp/webhtv-dv5-auto-20260829/app-debug-log.txt` | captured before `9b7cf9cfbbeac00b0e5a342d4c6071c2c2d7a223` | A, direct observation | The same FFmpeg error exists before C0-M, so this is not a 9.0.1 regression. Other occurrences also follow decoder fallback and must not be globally suppressed. | +| Android `SurfaceHolder.Callback.surfaceDestroyed()` | , accessed 2026-08-29 | A, platform contract | After the callback returns, code must no longer access the Surface and rendering threads must no longer touch it. It does not prescribe WebHTV's shutdown API. | +| FongMi/mpv-android locked tree | `99a60ad2141d5ace94453590903c2c6b9a0a2443` | A, exact source | `BaseMPVView.surfaceDestroyed()` uses `vo=null` then detach and explicitly states a race may remain because setting the property may not wait for VO deinit. The sample App has no separate terminal-release state. | +| mpv-android background-output history | `4e7916ea995e07ad09eb4285c2b2f23c4f891cd1`, `e185cdf53429653e3923a16f7453d7c523310319`, `cc30506e012a49ac6721baab54ee2421ad468860` | A, upstream history | `vo=null` was selected to preserve cache/background behavior, not as a terminal shutdown primitive; copying it unchanged cannot distinguish transient and terminal Surface loss. | +| mpv-android issue 1107 | , accessed 2026-08-29 | B, maintainer issue | Background Surface/VO transitions can overwrite intended output state. It corroborates the need to preserve local VO ownership but does not supply this teardown fix. A second bounded search found no direct upstream race fix. | +| WebHTV P4-1 | `907bfca982a4b1d4d9ee0eeddd05d02226b8f9bb` | A, current local implementation | Shutdown and Surface mutations share one FIFO and native cleanup releases global Surface references. P4-3 should use that cleanup rather than rebuild JNI. | +| FongMi/FFmpeg | `177f090e0503b7e013922ca903bde14b1c375f18` | A, exact source | `ff_mediacodec_surface_ref()` emits the error when both handles are absent and returns `NULL`. Changing FFmpeg would only move or hide the symptom. | + +Independent papers, benchmarks, and general technical blogs are not decision-relevant here: the disputed contract is concrete Android Surface ownership and the locked mpv/FFmpeg lifecycle implementation, not a codec algorithm or performance model. No applicable academic evidence was found or required. + +## 4. Current contracts that must survive + +- Transient Surface destruction must still detach native output so configuration changes, PlayerView replacement, decoder/output switches, and real background/foreground recreation do not retain stale Java Surface references. +- Picture-in-picture entry and return must continue playing and reusing/rebinding the intended output path. +- P4-1 FIFO ordering, pending request cancellation, `MPV_EVENT_SHUTDOWN`, force-wakeup fallback, and one-time JNI Surface global-reference cleanup must remain unchanged. +- `vo=null` background behavior must remain available outside terminal release; no cache, decoder, renderer, DV/HDR, OSD/subtitle, audio, network, ABI, or binary ownership policy changes. +- No frame-loop branch or native rebuild is justified. The exit-only branch should reduce codec work and have no playback performance cost. + +## 5. Alternatives + +| Alternative | Benefit | Defect / risk | Decision | +| --- | --- | --- | --- | +| No change | Zero code risk | Keeps unnecessary decoder creation after Surface loss and leaves a vendor lifecycle race | Reject | +| Suppress or downgrade the FFmpeg log | Small patch | Hides a real invalid initialization and also masks non-terminal decoder-fallback occurrences | Reject | +| Always use `vid=no`, reorder detach, or delay commands | Can stop decoding before detach in some cases | Changes cache/background semantics, still depends on asynchronous VO timing, and can slow or break normal Surface recreation | Reject | +| Copy upstream `surfaceDestroyed()` unchanged | Matches sample App | That source contains an explicit race FIXME and has no terminal-release distinction | Reject | +| Narrow WebHTV terminal-release signal | Separates permanent exit from transient Surface loss; shutdown owns final native reference cleanup | Requires a small service-to-player signal and focused lifecycle verification | Select | + +## 6. Recommended WebHTV adaptation + +Add an idempotent terminal-release signal that is set synchronously when `PlaybackService.shutdown()` commits to permanent shutdown, before `stopAndClear()` and before the Activity Surface can disappear. + +Planned behavior: + +1. `PlayerManager` exposes a narrow terminal-release preparation method and forwards it only when the current engine is MPV. `MpvPlayerEngine` forwards to `MpvPlayer`. +2. `MpvPlayer` records `terminalReleaseRequested`. After that point, Surface create/change callbacks do not reattach output. +3. On terminal video/OSD `surfaceDestroyed`, clear only Java-side callback/state references and mark the native attachment state as owned by shutdown. Do not enqueue `vo=null`, `force-window`, or Surface-detach mutations. +4. The existing P4-1 shutdown path remains responsible for final MPV destruction and JNI global-reference cleanup. Normal non-terminal Surface loss continues through the current detach/rebind path unchanged. +5. `PlayerManager.release()` repeats the signal as an idempotent fail-safe for service destruction paths that bypass the ordinary `shutdown()` entry. + +Expected implementation scope: + +- `app/src/main/java/com/fongmi/android/tv/service/PlaybackService.java` +- `app/src/main/java/com/fongmi/android/tv/player/PlayerManager.java` +- `app/src/main/java/com/fongmi/android/tv/player/engine/MpvPlayerEngine.java` +- `app/src/main/java/androidx/media3/mpvplayer/MpvPlayer.java` +- one focused package-level policy/test under `app/src/main/java/androidx/media3/mpvplayer/` and `app/src/test/java/androidx/media3/mpvplayer/` if needed for deterministic transient-versus-terminal coverage +- this document and the master assessment status + +Excluded: FFmpeg/mpv/mpv-android source revisions, JNI/C++, native assets, renderer/decoder policy, Exo/IJK behavior, and unrelated playback-service refactoring. + +## 7. Impact and risk + +- Benefit: avoids two observed decoder create/release cycles and the no-Surface error on terminal exit; reduces exposure to vendor codec/BufferQueue races. +- Compatibility: no format, ABI, Android API, or package-size impact. The new method is internal App code only. +- Performance: no frame-path work; terminal exit should do less work. Startup, seek, steady playback, and normal PiP performance are unchanged by design. +- Main regression risk: incorrectly classifying transient Surface loss as terminal could leave playback without output. Mitigation is an explicit service shutdown signal, not inference from pause, stop, `mediaItem == null`, or Activity state. +- Secondary risk: pending OSD/video Surface requests may already be in the P4-1 FIFO when shutdown begins. They remain ordered ahead of shutdown and are bounded; the implementation must prevent any new attachment after the terminal flag and leave final reference cleanup to native shutdown. +- Best practice: explicit ownership state plus idempotent terminal transition is preferable to timing delays, log suppression, or accessing a destroyed Surface. The WebHTV adaptation is narrower than modifying upstream/native code and preserves the upstream transient-background intent. + +## 8. Acceptance and rollback + +Minimum verification after approval: + +1. Focused unit tests prove transient Surface loss still requests native detach, terminal Surface loss skips detach/rebind, and repeated terminal signaling is idempotent. +2. Compile the affected Mobile arm64 Java/App target once; no native or dual-ABI rebuild is required. +3. On the connected V2453A, use command-driven playback of one local H.264/TS or MKV sample. Verify normal HOME picture-in-picture and return continue playback with Surface recreation. +4. Exit playback terminally and require: `end-file` plus `shutdown`; no decoder component creation after BufferQueue abandonment; no `Both surface and native_window are NULL` in that terminal window; no crash/ANR/native fatal/destroyed-mutex signal. +5. One rapid reopen after exit must create the next MPV context normally, proving P4-1 cleanup and the terminal flag are instance-local. + +Rollback is a revert of the one atomic P4-3 commit and its App-only Java/test/document paths. Existing C0-M binaries and P4-1 JNI assets remain untouched. + +## 9. Recommendation and decision + +Recommendation: **implement** the narrow terminal-release signal. Do not patch FFmpeg, change global `surfaceDestroyed()` semantics, add sleeps, or rebuild native libraries. + +User decision: **approved for implementation** on 2026-08-29. Scope remains the Java-only terminal-release signal recorded above; native/FFmpeg changes and unrelated lifecycle refactors remain unapproved. + +## 10. Implementation and verification + +Implemented the approved Java-only design: + +- `PlaybackService.shutdown()` and service destruction synchronously prepare terminal release before stopping or releasing the player. +- `PlayerManager` forwards the signal only to `MpvPlayerEngine`; Exo and IJK behavior is unchanged. +- `MpvPlayer` uses an instance-local, idempotent `MpvSurfaceTeardownPolicy`. Normal Surface loss keeps attach/detach enabled; terminal release blocks new video/OSD attachment and skips teardown commands that can reconfigure video after Surface destruction. +- Existing P4-1 native context destruction remains the sole final owner of JNI Surface-reference cleanup. No FFmpeg, mpv, JNI, native asset, renderer, decoder, ABI, or package dependency changed. + +Verification on 2026-08-29: + +- Focused test and App build passed in one corrected Gradle invocation: `bash ./gradlew :app:testMobileArm64_v8aDebugUnitTest --tests androidx.media3.mpvplayer.MpvSurfaceTeardownPolicyTest :app:assembleMobileArm64_v8aDebug --no-daemon`; `BUILD SUCCESSFUL in 3m 48s`, 112 tasks, 11 executed. The first attempted invocation used the nonexistent flavor spelling `Arm64` rather than `Arm64_v8a` and did not execute tests or compilation. +- APK: `app/build/outputs/apk/mobileArm64_v8a/debug/app-mobile-arm64_v8a-debug.apk`, 162,651,210 bytes, SHA-256 `42bef6007367653686ca301ad6791519a3efde54d20a025b7bbaa84d07ec2d07`. +- Install: OEM installer-assist completed successfully on vivo V2453A (`10CF6H1D2L0009S`, Android 15); installed package remained version `5.6.0`, code `560`, `arm64-v8a`. +- Representative input: `/storage/emulated/0/Download/声道测试/LPCM7.1原盘文件.m2ts`, using MPV (`player=2`) and `c2.qti.avc.decoder`. +- Transient lifecycle: HOME entered a real pinned task while media remained `PLAYING`; position advanced from 39.294 s to 42.323 s during the observed PiP interval and continued beyond 165 s. A compact rerun restored the same `VideoActivity` to `RESUMED` through its existing media-notification `PendingIntent`; playback remained `PLAYING` at 16.954 s. +- Terminal lifecycle: normal BACK returned to `HomeActivity`; MPV emitted `end-file` at `13:17:01.614` and `shutdown` at `13:17:02.175`. The only `c2.qti.avc.decoder` creation in that run was initial playback startup at `13:15:01.079`; there was no decoder creation after terminal Surface teardown, no `Both surface and native_window are NULL`, and no Java/native crash, ANR, fatal signal, or destroyed-mutex report. +- Reopen: after the verified shutdown, a fresh process (`11128`, replacing `9808`) created media session `/1028`, resumed `VideoActivity`, and played the same input. This confirms terminal state is instance-local and does not block the next MPV context. + +Performance/compatibility result: no frame-path or native work was added. The only new checks run on Surface/OSD lifecycle and terminal release events; normal PiP/recreation retained playback, while terminal exit performed less decoder work. No observed compatibility, playback, performance, ABI, or package-size regression remains. + +Rollback: revert `8250e2204f4054601202a3a3f2fe04f8766744ee`, or restore the annotated tag `recovery/P4-3-MPV-SURFACE-TEARDOWN/20260829132806-8250e2204f40`. The rollback affects only the Java lifecycle policy/wiring, its focused unit test, and this task's documentation; P4-1 JNI and C0-M native assets remain unchanged. diff --git a/docs/P4-4-mpv-autoplay-pause-race.md b/docs/P4-4-mpv-autoplay-pause-race.md new file mode 100644 index 0000000000..536de10f41 --- /dev/null +++ b/docs/P4-4-mpv-autoplay-pause-race.md @@ -0,0 +1,142 @@ +# P4-4: MPV autoplay pause callback race + +## Recovery anchor + +- Objective: preserve the latest Media3 play/pause intent when libmpv delivers a delayed or coalesced `pause` property notification during prepare or rapid media replacement. +- Acceptance: autoplay-on files advance without a second play command; user pause remains paused; resume advances; rapid source switching, cache pause, output selection, decoding, and lifecycle behavior do not regress. +- Authority: implementation approved by the user on 2026-08-29 after the device reproduction and root-cause report. +- Lane/scope: MPV App adapter only. Allowed files are `MpvPlayer.java`, one package-private pause-intent policy and test, this document, and the master assessment index. +- Baseline: branch `fongmi-sync`, HEAD `025f15ec4ac905059b468489df7f1ac5b03c683d`; rollback tag `recovery/P4-4-MPV-AUTOPLAY-PAUSE-RACE/baseline-20260829133913-025f15ec4ac9`. +- Protected pre-existing dirty path: `AGENTS.md`; it is outside task scope and must not be staged or changed. +- Current status: complete. Implementation commit `e8a1582d74844df0292cb27c6c8259a3d5eb5dfa` passed the required verification and is anchored by `recovery/P4-4-MPV-AUTOPLAY-PAUSE-RACE/20260829135715-e8a1582d7484`. +- Unresolved risk: a custom native mpv script that directly toggles `pause` is outside WebHTV's supported control path. Normal App, MediaSession, audio-focus, noisy-output, and user controls all enter through Media3 `setPlayWhenReady`. +- Next action: none for P4-4. + +## Problem and reproduced evidence + +On the connected Vivo V2453A running Android 15/API 35, MPV autoplay was enabled and `player=2`. Every tested item in `/storage/emulated/0/Download/杜比视界测试/` opened successfully but settled in `PAUSED` until another play command was sent. + +The retained App debug log `/private/tmp/webhtv-debug-autoplay-20260829.txt` shows the decisive sequence for `P7_FEL_GIJoe_The_Rise_of_Cobra.mkv`: + +1. `MpvPlayerEngine.start` received `play=true`. +2. libmpv completed `start-file`, `file-loaded`, two video reconfigurations, `playback-restart`, READY, and first-frame reporting in about 941 ms. +3. The pre-load and post-load `pause` property writes took about 118 ms and 77 ms respectively on the main thread. +4. After the first frame, the adapter changed from `playWhenReady=true` to `false` without a user pause command; position remained at 17 ms while more than 30 seconds was buffered. +5. A single Android media-session `PLAY` command changed the state to PLAYING and advanced `hdr测试.mp4` from 48 ms to 3062 ms in three seconds. Decoder, demuxer, renderer, and output were therefore healthy. + +The only local paths that can assign `MpvPlayer.playWhenReady` are initialization, `handleSetPlayWhenReady`, and the observed `pause` property branch. No playback-control or lifecycle pause appeared between READY and the false state. The observed property branch is therefore the falsifiable cause. + +## Source and history ledger + +| Repository/source | Full revision | Role and disposition | +| --- | --- | --- | +| WebHTV local | `025f15ec4ac905059b468489df7f1ac5b03c683d` | P4-4 baseline; reproduced defect. | +| WebHTV local | `cfc4bfc9843cc00db22cb3a563f34c6dde507062` | Introduced the Media3 MPV adapter's play/pause bridge; retained as historical provenance. | +| WebHTV local | `9a591de3921e0c898959d3107b4d5ca1f900b3ac` | Changed unconditional native `pause` reflection to conditional reflection while moving runtime properties off hot state queries; partial mitigation, but still lets a delayed property overwrite user intent. | +| WebHTV local | `655b1d01d3be19f89b2698819ee13583010d6841` | Preserves intentional pre-load `pause=true` and post-load restore behavior; this startup protection remains required. | +| FongMi/mpv | `cca559b41ceb0bb7731cf6ef2e1f33276cd30c42` | Current locked native source. Client API documents coalesced property notifications; no native change is required. | +| FongMi/mpv-android | `99a60ad2141d5ace94453590903c2c6b9a0a2443` | Current locked Android builder/reference. Its view exposes native `pause` directly and does not implement Media3's separate user-intent contract; reference only, not an implementation to copy. | +| fish2018/webhtv Media3 fork | `e3e922d5c01bc0b564849940fe589daf37360d15` | Current packaged Media3 source. `Player` defines `playWhenReady` as user intention and `SimpleBasePlayer` routes play/pause requests through `handleSetPlayWhenReady`. | +| AndroidX media release | `2bc207851df311340767e913931ca7b28cab1794` | Official release-branch identity observed on 2026-08-29; corroborates the Media3 contract used by the fork. | + +There is no upstream candidate commit to cherry-pick. P4-4 is a WebHTV adapter correction between the locked MPV client API and the locked Media3 state contract. FFmpeg, libplacebo, native JNI, binaries, locks, and both ABI assets are unchanged. + +## Best-practice evidence + +Decision-shaped question: may an asynchronously delivered native `pause` observation replace the latest Media3 user play/pause intent, or should the adapter preserve the intent and reconcile native state to it? + +| Evidence | Grade | Supported claim and WebHTV impact | +| --- | --- | --- | +| `FongMi/mpv@cca559b41ceb0bb7731cf6ef2e1f33276cd30c42`, `include/mpv/client.h`, accessed 2026-08-29 | A | `mpv_observe_property` notifications are coalesced and are not precise; the client also receives an initial notification. An observed value is state evidence, not a causally ordered acknowledgement of WebHTV's latest command. | +| Same MPV revision, `DOCS/man/input.rst` | A | `pause` and `paused-for-cache` are distinct properties. Preserving user pause intent does not disable cache-buffering state reporting. | +| `fish2018/webhtv@e3e922d5c01bc0b564849940fe589daf37360d15`, `Player.java` and `SimpleBasePlayer.java`, accessed 2026-08-29 | A | Media3 explicitly defines `playWhenReady` as user intention and routes supported play/pause commands to `handleSetPlayWhenReady`; native readiness/suppression is separate. | +| Reproducible V2453A/API 35 logs and media-session samples, 2026-08-29 | A | Latest requested intent was play, native load/first frame succeeded, then the property observer alone changed the adapter to paused; another play command resumed immediately. | +| `FongMi/mpv-android@99a60ad2141d5ace94453590903c2c6b9a0a2443`, `MPVView.kt` | B | Mature upstream Android code observes and exposes native `pause` directly, but it has no independent Media3 intent field. It cannot be copied unchanged into this two-contract adapter. | +| GitHub issue searches for `observe_property pause async` and `MPV_EVENT_PROPERTY_CHANGE stale`, accessed 2026-08-29 | B/none | No exact mpv issue or revert was found. `mpv-android#1201` concerns paused-frame orientation corruption and is not applicable. Absence of an issue does not override direct API documentation and reproduction. | + +Academic papers, benchmarks, and general technical blogs are inapplicable: the decision is defined by two explicit API contracts and a deterministic event-order reproduction, not an algorithmic or throughput claim. Security, license, ABI, and supply-chain behavior are unchanged because no dependency or binary changes. + +## Alternatives and decision + +### No change + +Reject. Autoplay remains unreliable and every affected file requires a second user action. The failure is already reproducible across all files in the target directory. + +### Unmodified native-state reflection + +Reject. Treating every native `pause` observation as authoritative is suitable for a direct mpv view with no separate intent model, but violates Media3's documented `playWhenReady` ownership and reproduces the race. + +### Delayed play or retry after READY + +Reject. A fixed delay hides one timing instance, adds startup latency, and can still lose to a later coalesced event. Repeated unconditional play would also break deliberate user pause during startup. + +### WebHTV-adapted intent reconciliation + +Approve and implement. Keep `playWhenReady` authoritative because it records the latest App/MediaSession/user request. For a native `pause` observation: + +- if it matches `!playWhenReady`, do nothing; +- if it disagrees before a file is active, do not alter intent because the existing file-loaded restore owns that boundary; +- if it disagrees during active playback, reapply the requested native pause value without changing `playWhenReady`; +- do not reconcile during stop, EOF, IDLE, or ENDED transitions. + +This preserves the existing pre-load pause barrier, autoplay-off behavior, manual pause/resume, audio-focus/noisy-device pauses, cache pause reporting, HLS paused preload, output selection, and lifecycle cleanup. + +## Performance and compatibility + +- Hot-path impact: none. `time-pos`, frame timing, cache metrics, decoder, renderer, and Surface paths are unchanged. +- Pause-event cost: one small pure decision on the rare `pause` property event. A native property write occurs only when an observed value conflicts with the latest intent during active playback. +- Startup: no delay, retry timer, rebuild, decoder restart, or additional media load. +- Compatibility: no public API, preference, MediaSession action, ABI, native asset, package size, codec, color, subtitle, audio, or network behavior changes. +- Main risk: over-correcting a native pause generated outside Media3. WebHTV has no supported direct native input/script control path; all supported controls enter Media3 first. EOF/stop/inactive gates prevent lifecycle reactivation. + +## Implementation and verification plan + +1. Add a package-private pure policy returning `NONE`, `WAIT`, or `REASSERT` from requested intent, observed native pause, and whether reconciliation is safe for the active file. +2. Replace the `pause` observer's mutation of `playWhenReady` with that decision; log and reapply only on active mismatches. +3. Unit-test matching play/pause, stale startup pause, stale unpause after user pause, pre-load mismatch, and inactive/EOF behavior. +4. Run the focused MPV policy unit test and the smallest affected mobile arm64 compile/build once. +5. Install the resulting APK and use ADB, not screenshots, to launch/switch at least three files from `杜比视界测试`; sample media-session positions automatically. +6. Verify manual pause holds position and resume advances. Check the retained debug log for crashes, reloads, repeated reconciliation, decoder/output fallback, and lifecycle errors. + +Rollback is a revert of the single P4-4 commit or restoration of `recovery/P4-4-MPV-AUTOPLAY-PAUSE-RACE/baseline-20260829133913-025f15ec4ac9`. No native or binary rollback is involved. + +## Implementation and verification result + +Implemented the approved adapted design: + +- `MpvPauseIntentPolicy` treats Media3 `playWhenReady` as the latest supported user/App/MediaSession intent. +- A matching native `pause` observation is ignored. +- A mismatch before active media waits for the existing file-loaded restore boundary. +- A mismatch during an active non-terminal file reasserts the requested native `pause` value without changing `playWhenReady`. +- Stop, EOF, IDLE, and ENDED paths cannot trigger playback reactivation. + +No timer, reload, decoder restart, media replacement, native/JNI call shape, FFmpeg/libplacebo asset, lock, ABI, preference, or package dependency changed. The runtime cost is one enum decision for a rare `pause` property notification and one native write only on a conflicting observation. + +Verification on 2026-08-29: + +- Focused unit test: `bash ./gradlew :app:testMobileArm64_v8aDebugUnitTest --tests androidx.media3.mpvplayer.MpvPauseIntentPolicyTest --no-daemon` passed; `BUILD SUCCESSFUL in 1m 32s`, 73 tasks, 6 executed. It covers matching play/pause, delayed startup pause, delayed unpause after user pause, and pre-active-media mismatch. +- Target APK: `bash ./gradlew :app:assembleMobileArm64_v8aDebug --no-daemon` passed; `BUILD SUCCESSFUL in 2m 25s`, 103 tasks, 7 executed. +- Installed `app/build/outputs/apk/mobileArm64_v8a/debug/app-mobile-arm64_v8a-debug.apk` successfully on Vivo V2453A, Android 15/API 35, serial `10CF6H1D2L0009S`, preserving existing App data/settings. +- Cold launch of `P4_LG_Dolby_Trailer_4K_Demo.mkv` reached media-session `PLAYING` instead of settling in the reproduced false pause. +- Warm ACTION_VIEW replacement to `P7_FEL_GIJoe_The_Rise_of_Cobra.mkv` stayed `PLAYING` and advanced from 117 ms to 2941 ms over the three-second sample interval. +- Warm replacement to `hdr测试.mp4` stayed `PLAYING` and advanced from 55 ms to 2896 ms over the three-second sample interval. +- The final explicit pause/resume command was inconclusive because the short sample session had already ended and MediaSession reported `NONE`; it did not reveal a regression and is not counted as acceptance evidence. +- Retained device log: `/private/tmp/P4-4-device-final-20260829.txt`. Targeted screening found no Java/native crash, `SIGSEGV`, decoder failure, video-output failure, shutdown timeout, or repeated pause-reconciliation loop. + +Acceptance is satisfied for the reported defect and its direct state-transition neighbors. The existing user-confirmed click-to-resume behavior before the fix plus the focused delayed-unpause unit test cover preservation of deliberate pause/resume semantics; no broader renderer, codec, audio, network, or native matrix is warranted because those paths and artifacts did not change. + +Implementation commit: `e8a1582d74844df0292cb27c6c8259a3d5eb5dfa`. + +Recovery tag: `recovery/P4-4-MPV-AUTOPLAY-PAUSE-RACE/20260829135715-e8a1582d7484` (created immediately by task guard in 0 seconds). + +Rollback: revert `e8a1582d74844df0292cb27c6c8259a3d5eb5dfa`, or use the recovery tag to restore/inspect the verified P4-4 state. The baseline remains `recovery/P4-4-MPV-AUTOPLAY-PAUSE-RACE/baseline-20260829133913-025f15ec4ac9`. + +## Checkpoint 1: verified candidate before commit + +- Completed: research, adapted policy implementation, focused unit test, mobile arm64 APK build, install, cold launch, and two rapid media replacements. +- Source identities: WebHTV baseline `025f15ec4ac905059b468489df7f1ac5b03c683d`; locked mpv `cca559b41ceb0bb7731cf6ef2e1f33276cd30c42`; locked mpv-android `99a60ad2141d5ace94453590903c2c6b9a0a2443`; packaged Media3 fork `e3e922d5c01bc0b564849940fe589daf37360d15`. +- Workspace: `fongmi-sync`; protected pre-existing dirty `AGENTS.md` remains outside scope. +- Task-owned files: `MpvPlayer.java`, `MpvPauseIntentPolicy.java`, `MpvPauseIntentPolicyTest.java`, this document, and the assessment index. +- Rollback: baseline tag `recovery/P4-4-MPV-AUTOPLAY-PAUSE-RACE/baseline-20260829133913-025f15ec4ac9` or revert the forthcoming atomic implementation commit. +- Unresolved: final hardware-specific pause/resume command was not rerun after the sample ended because the user accepted the result and requested closure; pure-policy coverage is conclusive for the changed contract. +- Next action: none; P4-4 is committed, tagged, verified, and documented. diff --git a/docs/agents-md-effective-constraints-review-2026-08-21.md b/docs/agents-md-effective-constraints-review-2026-08-21.md new file mode 100644 index 0000000000..a234467e67 --- /dev/null +++ b/docs/agents-md-effective-constraints-review-2026-08-21.md @@ -0,0 +1,65 @@ +# AGENTS.md 有效约束实践评审 + +日期:2026-08-21 + +目的:为 WebHTV 的 AI 协作规则确定可执行、低开销、不会牺牲任务完成度的约束方法。 + +## 结论摘要 + +公开项目的有效做法不是把 AGENTS.md 写成百科全书,而是把规则写成可判断的动作:明确作用域、唯一推荐命令、禁止的高成本误操作、最小验证路径、生成文件边界和失败分类。规则越接近具体文件/命令/调用方式,越容易执行;“认真检查”“不要浪费时间”这类口号不能形成可靠门禁。 + +AGENTS.md 仍然只是模型可见的指令层,不能单独强制模型、阻止 `--no-verify`、读取真实剩余上下文 token 或保证自动提交。必须把关键约束分层:AGENTS.md 负责决策顺序和边界,脚本只负责范围/初始状态保护/原子提交/tag,CI 负责组织级强制验证。 + +## 公开来源与观察 + +访问日期均为 2026-08-21;通过项目配置的 HTTP(S) 代理访问。 + +| 来源 | 关键观察 | 对 WebHTV 的可用经验 | +| --- | --- | --- | +| [OpenAI Codex 官方 AGENTS.md 指南](https://learn.chatgpt.com/docs/agent-configuration/agents-md) | 全局、项目根到当前目录逐层加载;更近的文件后加载并覆盖前面的规则;每个目录只取一个 `AGENTS.override.md`/`AGENTS.md`;合并文档默认有 32 KiB 上限;提供“从根目录到专用目录”的分层方法。 | 根规则保持短小;播放器/脚本等高风险目录可增加更具体的规则;必须检查是否被 override 或大小上限截断。 | +| [OpenAI Codex 公共仓库 AGENTS.md](https://github.com/openai/codex/blob/main/AGENTS.md) | 规则具体到命令和代码形态:不要直接运行 `cargo test`,按项目使用 `just test -p`;共享 crate 才扩大测试;避免重复运行;要求改依赖时同步 lock;限制模块和变更行数;要求改动 agent 行为时添加集成测试。 | “最小正确命令”“按影响面扩展”“禁止重复测试”“改动大小触发拆分”比抽象质量口号更有效。 | +| [Vercel Next.js AGENTS.md](https://github.com/vercel/next.js/blob/canary/AGENTS.md) | 明确目录结构和构建入口;按模式选择测试;要求一次捕获完整输出再过滤,禁止换 grep 重跑同一测试;建议 throwaway worktree;根据改动范围选择局部 build 或全量 build;清楚标注环境导致的假错误。 | 先给最小决定性检查;保存输出;区分环境问题和产品回归;大型/不可信操作隔离 worktree。 | +| [Kubernetes AGENTS.md](https://github.com/kubernetes/kubernetes/blob/master/AGENTS.md) | 生成文件只读;明确生成命令和禁止命令(例如不要手工改 `go.mod`、不要 `go mod tidy`);要求改动聚焦、补测试;提供局部测试和全量验证入口。 | 对 lock、AAR、native 资产、生成代码建立“来源文件 + 生成命令”,禁止手工修产物。 | +| [AGENTS.md 开放格式示例](https://github.com/agentsmd/agents.md/blob/main/README.md) | 最小示例包含环境入口、测试入口、lint 和提交前要求;建议让 agent 直接使用仓库已有命令而不是重新探索。 | 根文件应优先记录项目特有事实和命令,不重复通用编程知识。 | +| [Git hooks 官方文档](https://git-scm.com/docs/githooks) | hook 可由 `core.hooksPath` 改变;`pre-commit`/`commit-msg` 可阻止提交但可用 `--no-verify` 绕过;`post-commit` 发生在提交之后,不能阻止结果;普通仓库不会因为提交一个 hook 文件就自动启用它。 | hook 不能作为唯一强制机制;使用显式 task guard,CI 再做最终门禁;tag 必须由显式脚本在提交后创建。 | +| [GitHub Copilot 仓库指令文档](https://docs.github.com/en/copilot/customizing-copilot/adding-repository-custom-instructions-for-github-copilot) | 仓库级指令和路径级指令可叠加;最近的 `AGENTS.md` 优先;官方建议指令不超过约两页,并记录 bootstrap/build/test/lint 的具体顺序。 | 根 AGENTS.md 控制在短篇幅;路径规则就近放置;把常用命令写全,减少 agent 搜索和试错。 | + +## 约束分层 + +| 目标 | AGENTS.md 能做什么 | 必须自动化的部分 | +| --- | --- | --- | +| 防止需求蔓延 | 要求先写完成句、允许路径、排除项;新行为/模块/依赖边界先停下复盘 | 脚本比较初始和当前 changed paths;超范围返回非零 | +| 快速定位 | 规定“复现/证据 -> 精确调用链 -> 一个假设 -> 最小修复 -> 一次决定性验证” | 单条命令防挂起超时、输出保存、CI 结果留档 | +| 防止无限搜索/测试 | 规定按风险扩展、禁止同命题重复尝试、优先局部命令 | 不使用脚本计数门禁;CI 约束矩阵和并发 | +| 上下文恢复 | 在真实跨会话风险下记录 hash、结果、下一动作 | 脚本记录 branch/HEAD/范围;文档保存 durable state | +| 自动 commit/tag | 要求使用统一 finish 命令,禁止未验证和未提交 tag | 脚本只 stage task-owned paths,`git commit` 后创建唯一 annotated tag | +| 质量不降级 | 明确速度只能删重复工作,不能删关键回归;构建不等于行为正确 | 领域测试、ABI/ELF/设备 CI、发布审批 | + +## WebHTV 采用的规则 + +1. 根 `AGENTS.md` 只保留高优先级合同:短任务默认路径、范围封闭、风险驱动验证、checkpoint、原子 commit/tag、上游 Exo -> MPV 顺序和能力边界。 +2. 上游 Skill 负责跨仓库提交台账、证据等级、功能阶段和播放器门禁;继续任务只按需加载 references,避免上下文膨胀。 +3. `.codex/scripts/task_guard.sh` 只负责可计算且低开销的安全边界:初始 dirty 文件保护、声明路径、分支/HEAD、staged 范围、原子提交和 recovery tag。 +4. 不再设置固定分钟数、文件数量、cycle 计数、强制 checkpoint/replan 或状态目录归档。`check` 仅是按需使用的只读安全审计,`finish` 自行执行最终安全检查。 +5. 当前工作区已有的播放器 Java、测试和 lock dirty 修改不纳入治理变更,也不能被自动提交。 +6. commit 成功后立即以一次本地、非交互、禁签名的 annotated-tag 命令创建 recovery tag,正常目标不超过 5 秒;commit 与 tag 之间禁止重新测试、构建、联网搜索、反复看 diff 或重复验证 tag。 +7. 简单规则/文档/Skill 和局部 bug 都走最短证据路径:必要修改、一次最小验证、获授权时的 commit/tag 和交付;不使用固定分钟节点制造额外动作。 +8. 本次低效的直接原因是把固定时间、cycle、文件数量、强制 checkpoint/replan、状态归档和仓库内临时文件都混入安全门禁。现已将守卫收缩为范围与回滚保护,并保留 governance-maintenance fast path。 + +## 不采用的做法 + +- 不把每次文件编辑都打 tag;tag 只标记已验证的逻辑提交或阶段恢复点。 +- 不把全量测试、全 ABI native 构建和互联网搜索设为所有任务默认步骤。 +- 不用 Git hook 假装强制 AI 行为;hook 需要显式安装且可绕过,适合补充检查,不适合承载唯一策略。 +- 不用固定分钟数、cycle、文件数量或强制 checkpoint/replan 判断任务进度;完成度由目标、验证和回滚边界决定。 +- 不把单条命令的防挂起 timeout 外推成任务 timeout;命令超时后缩小、恢复或换路径继续完成任务。 +- 不原样循环失败的 tag 命令;只记录一次错误,修正直接原因后再执行。 +- 不对未改变且已成功的文件/命令反复校验;只有相关内容再次修改或首次结果不确定才允许重跑。 + +## 验证记录 + +- 官方文档、公开 AGENTS.md、Git hooks/GitHub 指令文档已通过代理直接读取。 +- 本次治理 Skill 通过 `skill-creator` 的 `quick_validate.py`。 +- `bash -n .codex/scripts/task_guard.sh` 通过。 +- `git diff --check` 通过。 +- 本轮按效率收口:脚本完成一次 `bash -n`,Skill 完成一次 `quick_validate.py`,仓库完成一次 `git diff --check`;不再为规则文字维护搭建额外测试仓库。 diff --git a/docs/upstream-player-dependency-merge-assessment-2026-08-20.md b/docs/upstream-player-dependency-merge-assessment-2026-08-20.md index 6f9686b456..0e88e9d447 100644 --- a/docs/upstream-player-dependency-merge-assessment-2026-08-20.md +++ b/docs/upstream-player-dependency-merge-assessment-2026-08-20.md @@ -4,7 +4,7 @@ 文档状态:进行中。本文按检查点持续落盘;未标记“已完成逐提交审阅”的仓库,不应据此直接升级依赖。 -当前恢复入口:以“稳定任务 ID 与唯一文档索引”及各任务文档顶部状态为准。完整逐提交审计已完成至检查点 43;`E1`、`E2-2`、`E-SP1` 已实施,`E-SP2` 候选已接入但仍待实机性能/seek 验收,`E-SP3` 已实施并纠正 `E-SP1` 的记载偏差(该任务声明不改超时,实际撤销了启播超时),下一项待评估任务是 `E2-1`。后续仍按 Exo → MPV 顺序处理;`C2` 默认暂缓,`C3` 随 `E7-2` 联合处理。 +当前恢复入口:以“稳定任务 ID 与唯一文档索引”及各任务文档顶部状态为准。完整逐提交审计已完成至检查点 43;`E1`、`E2-2`、`E-SP1`、`E2-1`、`E3-1a`、`E7-1`、`E7-2 + C3`、`E-SP3`、`E9-3`、`P1`、`P2-1`、`P2-5`、`P2-2`、`P3`、`P4-1` 和 `C0-M` 已完成验证,`E-SP2` 候选已接入但仍待实机性能/seek 验收。C0-M 已在 `9b7cf9cfbbeac00b0e5a342d4c6071c2c2d7a223` 把 MPV FFmpeg 从 `04482c8d13ac27b2a9fe93f5d388929eef8af5f4` 切换到 Exo 已验证的 `177f090e0503b7e013922ca903bde14b1c375f18`;`C2` 默认暂缓。 ## 稳定任务 ID 与唯一文档索引 @@ -25,27 +25,31 @@ | 1 | `E1` | Exo | nextlib 内置 FFmpeg 升级至 9.0.1 | 已完成 | [E1-exo-ffmpeg-9.0.1.md](E1-exo-ffmpeg-9.0.1.md) | | 2 | `E2-2` | Exo | DV7→P8.1 codec/CSD 一致性 | 已实施 | [E2-2-exo-dv7-p81-csd.md](E2-2-exo-dv7-p81-csd.md) | | 3 | `E-SP1` | Exo 性能 | 首帧已渲染时立即解除遮罩 | 已完成 | [E-SP1-exo-first-frame-visible.md](E-SP1-exo-first-frame-visible.md) | -| 4 | `E-SP2` | Exo 性能 | 远程大 MKV 延后 Cues、首次 seek 按需建索引 | 候选已实现,待实机性能/seek 验收 | [E-SP2-exo-remote-mkv-deferred-cues.md](E-SP2-exo-remote-mkv-deferred-cues.md) | -| 4.1 | `E-SP3` | Exo 性能 | BUFFERING 停滞看门狗(修 `E-SP1`/DV7 撤超时导致的永久转圈) | 已实施,待实机验收 | [E-SP3-exo-buffering-stall-watchdog.md](E-SP3-exo-buffering-stall-watchdog.md) | -| 5 | `E2-1` | Exo | HDR/Dolby Vision parser safety | **下一项待评估/决策** | `docs/E2-1-exo-hdr-parser-safety.md` | -| 6 | `E3-1a` | Exo | Pixel E-AC3 JOC capability guard | 待处理 | `docs/E3-1a-exo-pixel-eac3-joc-guard.md` | -| 7 | `E3-1b` | Exo | DTS 14-bit 解析 | 待处理 | `docs/E3-1b-exo-dts-14bit.md` | -| 8 | `E4-1` | Exo | 字幕字节与边界安全 | 待处理 | `docs/E4-1-exo-subtitle-byte-safety.md` | -| 9 | `E4-J1` | Exo | Cue 数据契约 | 待处理 | `docs/E4-J1-exo-cue-data-contract.md` | -| 10 | `E6-1` | Exo | SMB/代理/缓存 correctness | 待处理 | `docs/E6-1-exo-smb-proxy-cache-correctness.md` | -| 11 | `E7-1` | Exo | ISO reader safety | 待处理 | `docs/E7-1-exo-iso-reader-safety.md` | -| 12 | `E7-2` | Exo | ISO multi-extent reader/API | 待处理;与 `C3` 联合阶段 | `docs/E7-2-exo-iso-multi-extent-api.md` | -| 13 | `P0` | MPV | native 基线、等价提交与运行验收 | Exo 阶段后处理 | `docs/P0-mpv-native-baseline.md` | -| 14 | `P1` | MPV | 格式与 shader correctness | 待处理 | `docs/P1-mpv-format-shader-correctness.md` | -| 15 | `P2-1` | MPV | Vulkan generic UV | 待处理 | `docs/P2-1-mpv-vulkan-generic-uv.md` | -| 16 | `P2-2` | MPV | DV7 metadata/codecpar/error 完整性 | 待处理 | `docs/P2-2-mpv-dv7-metadata-codecpar.md` | -| 17 | `P3` | MPV | AudioTrack 能力与直通 | 待处理 | `docs/P3-mpv-audiotrack.md` | -| 18 | `P4-1` | MPV | JNI shutdown/lifecycle | 待处理 | `docs/P4-1-mpv-jni-shutdown.md` | -| 19 | `C0-M` | 通用/MPV 搭载 | MPV 使用 FFmpeg 9.0.1 同源 revision 独立重建 | E1 验证后随 MPV 候选处理 | `docs/C0-M-mpv-ffmpeg-9.0.1.md` | -| 20 | `C2` | 通用 | FFmpeg DV7→P8.1 BSF | 暂缓;不自动启用 | `docs/C2-dv7-p81-bsf.md` | -| 21 | `C3` | 通用 | ISO multi-extent App resolver | 随 `E7-2` 联合评估/实施 | `docs/C3-iso-multi-extent-resolver.md` | +| 4 | `E-SP2` | Exo 性能 | 远程大 MKV 延后 Cues、首次 seek 按需建索引 | **已完成**:`2156c74749a575b747d2f043419a5d47b485c0cf` / `recovery/E-SP2-CHAINED-SEEKHEAD/20260829004352-2156c74749a5`;双产品 arm64、连续 seek 和实机验证通过 | [E-SP2-exo-remote-mkv-deferred-cues.md](E-SP2-exo-remote-mkv-deferred-cues.md) | +| 5 | `E-SP3` | Exo 性能/生命周期 | seek 预载隔离、HLS 预缓存崩溃防护和 seek 恢复门槛 | **已合入 `fongmi-sync`**:App `17f1a4cfe2547b8f3ddc61fab34212e77ae719ff`,Media3 `c9d3bd912b90ec0ca440c28455f3e6d9bba019ea` | [E-SP3-exo-seek-preload-isolation.md](E-SP3-exo-seek-preload-isolation.md) | +| 6 | `E2-1` | Exo | HDR/Dolby Vision parser safety | **已完成** | [E2-1-exo-hdr-parser-safety.md](E2-1-exo-hdr-parser-safety.md) | +| 6 | `E3-1a` | Exo | Pixel E-AC3 JOC capability guard | 已实施:`cda1ac8cf2f5d4d9c3beec68b0b520d6f7c218ec` / `recovery/E3-1a/20260826175658-cda1ac8cf2f5` | [E3-1a-exo-pixel-eac3-joc-guard.md](E3-1a-exo-pixel-eac3-joc-guard.md) | +| 7 | `E3-1b` | Exo | DTS 14-bit 解析 | 已实施:`27b85eeeed5ceb55e56a67ae3b5cf8ff64b8da40` / `recovery/E3-1b/20260826201735-27b85eeeed5c` | [E3-1b-exo-dts-14bit.md](E3-1b-exo-dts-14bit.md) | +| 8 | `E4-1` | Exo | 字幕字节与边界安全 | **已完成:A4-1a/A4-1b** | [E4-1-exo-subtitle-byte-safety.md](E4-1-exo-subtitle-byte-safety.md) | +| 9 | `E4-J1` | Exo | Cue 数据契约 | **已实施并验证**:`af78e3b7656d6a0f210d7344b3852f301690c417` / `recovery/E4-J1/20260827133106-af78e3b7656d`;默认不启用碰撞或新渲染行为 | [E4-J1-exo-cue-data-contract.md](E4-J1-exo-cue-data-contract.md) | +| 10 | `E6-1` | Exo | 有界缓存写入 correctness | **已实施并验证**:`0a8ed3b910679a08a7e41c735338c3804a2eb938` / `recovery/E6-1/20260827145043-0a8ed3b91067`;不引入并行预加载 | [E6-1-exo-smb-proxy-cache-correctness.md](E6-1-exo-smb-proxy-cache-correctness.md) | +| 11 | `E7-1` | Exo | ISO reader safety | **已实施并验证**:`491a7def30484b0936426bbc57b09f5b6435ae80` / `recovery/E7-1/20260827160011-491a7def3048`;仅移植 IsoDataReader 安全修复 | [E7-1-exo-iso-reader-safety.md](E7-1-exo-iso-reader-safety.md) | +| 12 | `E7-2` | Exo | ISO multi-extent reader/API | **已实施并编译验证**:`5f7d834bfdd00f215609df7b41c2ea7cadc2cd4f` / `recovery/E7-2-C3/20260827193629-5f7d834bfdd0`;按用户要求未跑测试/真实 split ISO | [E7-2-exo-iso-multi-extent-api.md](E7-2-exo-iso-multi-extent-api.md) | +| 13 | `P0` | MPV | native 基线、等价提交与运行验收 | **评估已完成:基线/ELF/资产校验通过;无代码,待 P1/P2 明确批准** | [P0-mpv-native-baseline.md](P0-mpv-native-baseline.md) | +| 14 | `P1` | MPV | 格式与 shader correctness | **已实施并验证**:`a5971e3814d3b0826a5702d607dd6d1675b2ce53` / `recovery/P1-MPV-FORMAT-SHADER-CORRECTNESS/20260828184107-a5971e3814d3`;用户多原盘回归通过 | [P1-mpv-format-shader-correctness.md](P1-mpv-format-shader-correctness.md) | +| 15 | `P2-1` | MPV | Vulkan generic UV | **已实施并验证**:`fe4184933fbb3a02bd1ff2ff794a277123c35bdc` / `recovery/P2-1-MPV-VULKAN-GENERIC-UV/20260829003632-fe4184933fbb`;双 ABI、ELF、APK 资产身份及 compute/fragment/legacy/stable/auto 真机路径通过 | [P2-1-mpv-vulkan-generic-uv.md](P2-1-mpv-vulkan-generic-uv.md) | +| 16 | `P2-5` | MPV | 非原生 DV5 自动选择 Vulkan/gpu-next | **已实施并验证**:V2453A 上自动切换至 `vulkan/gpu-next` + `hevc_mediacodec`,普通 HDR 新媒体项恢复 `opengl/gpu`;用户确认正常 | [P2-5-mpv-dv5-auto-vulkan.md](P2-5-mpv-dv5-auto-vulkan.md) | +| 17 | `P2-2` | MPV | DV7 metadata/codecpar/error 完整性 | **已实施并验证**:`ba47756d7e463abeb9377088b819a2520e150935` / `recovery/P2-2-MPV-DV7-METADATA-CODECPAR/20260829065811-ba47756d7e46`;仅吸收 metadata-missing、`par_out`、错误传播和 `INT_MAX`,保留本地 packet/Surface/EL 安全契约 | [P2-2-mpv-dv7-metadata-codecpar.md](P2-2-mpv-dv7-metadata-codecpar.md) | +| 18 | `P3` | MPV | AudioTrack 能力与直通 | **已完成**:`d82336bde585b62af43771284075a0a94a3d999e` / `recovery/P3/20260829094014-d82336bde585`;双 ABI、ELF、APK、API 35 手机端多声道 PCM fallback、pause/resume/seek 通过,HDMI/eARC/USB 原码直通留作硬件补验 | [P3-mpv-audiotrack.md](P3-mpv-audiotrack.md) | +| 19 | `P4-1` | MPV | JNI shutdown/lifecycle | **已完成**:`907bfca982a4b1d4d9ee0eeddd05d02226b8f9bb` / `recovery/P4-1-MPV-JNI-SHUTDOWN/20260829103212-907bfca982a4` | `docs/P4-1-mpv-jni-shutdown.md` | +| 20 | `C0-M` | 通用/MPV 搭载 | MPV 使用 FFmpeg 9.0.1 同源 revision 独立重建 | **已完成并关闭**:`9b7cf9cfbbeac00b0e5a342d4c6071c2c2d7a223` / `recovery/C0-M-MPV-FFMPEG-9.0.1/20260829122948-9b7cf9cfbbea`;双 ABI、ELF/资产、arm64 APK、多格式播放、快进、画中画和退出通过;退出期无 Surface 重初始化为升级前已存在的独立生命周期 bug | [C0-M-mpv-ffmpeg-9.0.1.md](C0-M-mpv-ffmpeg-9.0.1.md) | +| 21 | `C2` | 通用 | FFmpeg DV7→P8.1 BSF | **实施中(显式 MPV P8.1,默认行为不变)** | [C2-dv7-p81-bsf.md](C2-dv7-p81-bsf.md) | +| 22 | `C3` | 通用 | ISO multi-extent App resolver | **已随 `E7-2` 联合实施并通过 App 编译**:`5f7d834bfdd00f215609df7b41c2ea7cadc2cd4f` / `recovery/E7-2-C3/20260827193629-5f7d834bfdd0`;真实 split metadata 未验收 | [C3-iso-multi-extent-resolver.md](C3-iso-multi-extent-resolver.md) | +| 23 | `E9-3` | Exo | DV5 MediaCodec + Vulkan/libplacebo GPU 映射 | **已实现并通过目标设备验收**:DV5 色彩映射稳定,DV5 -> DV7/HDR10 Surface 生命周期切换正常;最终提交 `6a3ddd266a94a6b984099876631cc6260e77b776` | [E9-3-exo-dv5-vulkan-renderer.md](E9-3-exo-dv5-vulkan-renderer.md) | +| 24 | `P4-3` | MPV | 终止退出时抑制无 Surface 的 MediaCodec 重初始化 | **已实施并通过定向测试/真机验收**:`8250e2204f4054601202a3a3f2fe04f8766744ee` / `recovery/P4-3-MPV-SURFACE-TEARDOWN/20260829132806-8250e2204f40`;终止退出后不再创建一次性 decoder,PiP 返回和快速重开正常,不改 native/FFmpeg | [P4-3-mpv-surface-teardown.md](P4-3-mpv-surface-teardown.md) | +| 25 | `P4-4` | MPV | 自动播放意图与延迟 pause 回调隔离 | **已完成**:`e8a1582d74844df0292cb27c6c8259a3d5eb5dfa` / `recovery/P4-4-MPV-AUTOPLAY-PAUSE-RACE/20260829135715-e8a1582d7484`;V2453A/API 35 冷启动和两次快速媒体替换均保持自动播放,两个暖切换样本约 3 秒推进约 2.8 秒;不改 native/FFmpeg/渲染链 | [P4-4-mpv-autoplay-pause-race.md](P4-4-mpv-autoplay-pause-race.md) | -`C1` 是跨播放器真实输入验收维度,不单独形成代码任务或文档;它写入对应的 E/P 任务文档。当前下一项是 `E2-1`,开始前先创建其唯一文档并给出功能目标、收益、代价和是否建议合并的决策包。 +`C1` 是跨播放器真实输入验收维度,不单独形成代码任务或文档;它写入对应的 E/P 任务文档。`E-SP3` 已在 `fongmi-sync` 完成 App/Media3 合并,保留既有 `E4-J1`/`E6-1`/`E7-1`/`E7-2 + C3` 能力;`E9-3` 与已完成的 `P1` 现已共同进入集成树,后续按既定顺序处理 P2 阶段。 ## 目标与决策顺序 @@ -577,7 +581,7 @@ MMT/TLV(`054c8690e16b377eb1c6375c8751a44b8eb1d962`)、HLS discontinuity/live - MPV 目前通过 `mpv-dovi-profile7-hdr10-base-layer.patch` 的 demux 选项 `demuxer-dovi-profile7=hdr10` 清理 EL/RPU,再交给 MediaCodec base-layer decoder;FFmpeg bsf 可减少自定义 demux 代码,但还需要把 bsf 接入 MPV 的 load/demux 选项,并与本地 DV7 日志/失败回退保持一致。 - 该提交只处理 HEVC packet,不自动解决 Android 输出 sink、HDR metadata 宣告、P8.1 硬件能力或 RPU 无效时的用户策略;不能因为“转换功能存在”就删除 Exo/MPV 现有 fallback。 -**建议:** C2 先保留为实验分支候选,不随 C0 默认启用。若后续决定统一 Exo/MPV DV7 转换,优先在 MPV B8 原型中用同一测试片比较“FFmpeg bsf”与现有 WebHTV patch 的输出、seek、错误和 HDR10 metadata,再考虑把 Exo 也切换到共用语义。 +**实施记录:** C2 已按用户批准在 MPV 独立阶段完成窄适配:保留原生 DV7 优先,仅提供默认“升级 P8.1”和“降级 HDR10”两态;P8.1 能力不成立、转换失败或运行时失败时自动回退 HDR10。来源为 FFmpeg `177f090e0503b7e013922ca903bde14b1c375f18`、MPV `cca559b41ceb0bb7731cf6ef2e1f33276cd30c42`、mpv-android `eabfaf9501fc08fb726953a9328da43ae4154d35`,任务记录见 `docs/C2-dv7-p81-bsf.md`。两个 ABI 资产校验、Mobile/Leanback arm64 Debug 构建和策略单测已通过;电视端 P7 FEL 自动 P8.1 播放曾因主线程同步读取 `current-tracks/sub2/id` 卡死,已在任务文档记录并进入窄修复验证。实现提交为 `ae337b81e44657d85050bee3a9f92a780fb418ab`,文档 checkpoint 提交为 `408182daae91dc3d7486092dd223135f9419cc05`,对应恢复 tag 为 `recovery/C2-DV7-P81-BSF/20260829210209-408182daae91`。Exo 仍保持独立实现,不切换为共用 FFmpeg BSF。 ### 6.6 FFmpeg 阶段验证矩阵与回滚边界 @@ -4121,7 +4125,7 @@ E3 只构建 Media3 AAR 和 App APK,不更新 nextlib/MPV FFmpeg。E3-1a、E3- | 子阶段 | 代码动作 | 建议 | 验收/回滚 | | --- | --- | --- | --- | | E4-0 基线/覆盖 | `ccc11523...`、`e8573d8c...`、`7feb0801...` 已覆盖;冻结 ASS/TTML/PGS/DVB 截图与 cue dump | 无代码 | 若基线不可复现,停止后续 E4 | -| E4-1 字节安全 | 从 `d82fb7b9...` 取有效 length/bytesRead、文本 MIME 白名单和非 UTF TTML declaration;safe factory/extraction 灰度后置 | **建议合并 1a/1b** | decoder/extractor AAR 独立回滚;bitmap raw path 不变 | +| E4-1 字节安全 | 从 `d82fb7b9...` 取有效 length/bytesRead、文本 MIME 白名单和非 UTF TTML declaration;safe factory/extraction 灰度后置 | **已实施 1a/1b**:`9018f2b5c2b132644cde3841f33fe306209d2499`,tag `recovery/E4-1/20260827074736-9018f2b5c2b1` | decoder/extractor AAR 独立回滚;bitmap raw path 不变;1c/1d 仍待独立批准 | | E4-J1 Cue 契约 | `6794d75b...` + `3c2cbe8a...` 的 `collisionAvoidance`、`textRegionHeight`、LetterSpacingSpan、Bundle/equals/hashCode | **建议先建数据契约** | common/UI 数据模型独立回滚,默认不启用碰撞 | | E4-J2 viewport | `92b1570a...`、`6794d75b...`、`3c2cbe8a...`、`aaddc2b9...` 的 viewport/region/bitmap scale 适配 | **截图后条件合并** | PlayerView/SubtitleView UI 回滚,不回滚 parser 字段 | | E4-2 ASS | `6794d75b...` 的 layer/collision/margin;关闭或 feature-gate fork `applyStacking()` | **条件合并** | Normal/Reverse、绝对定位、留黑边、字号;禁止双 stacking | @@ -4389,14 +4393,14 @@ E9 的共同特点是会新增一套资产生产者、数千行状态机或当 | 需要明确产品策略 | E2-3;E3-3;E5 的 CEA/DRM/广告策略;E6-3;E7-6;E8-1/4 | 结果不是纯 bugfix,可能改变用户选择、网络行为、资源占用或输出路径 | | 当前跳过/独立架构线 | E6-4;E9-1/2/3/4/5/6;E8 overlay | 会引入第二资产生产者、大量新状态机、未闭环格式或重复 UI | -若只追求第一轮低风险增量,建议发布顺序是:**E1 → E2-1 → E3-1a → E3-1b → E4-1/J1 → E6-1 → E7-1**。每一步先发布独立测试 AAR/APK并保存样片、日志与哈希,再进入下一步;不要为了减少构建次数把它们压成一个无法归因的 Media3 大版本。 +若只追求第一轮低风险增量,建议发布顺序是:**E1 → E2-1 → E3-1a → E3-1b → E4-1/J1 → E6-1 → E7-1**。E4-1 的 1a/1b 已由提交 `9018f2b5c2b132644cde3841f33fe306209d2499` 实施并以 tag `recovery/E4-1/20260827074736-9018f2b5c2b1` 锚定;1c/1d 和 J1 仍是独立阶段。每一步先发布独立测试 AAR/APK并保存样片、日志与哈希,再进入下一步;不要为了减少构建次数把它们压成一个无法归因的 Media3 大版本。 ### 41.15 恢复锚点 - Exo 可决策实施总表已完成:E0--E9、完整 commit 归属、必须保留的本地实现、通用项搭载、产物边界、验收和独立回滚均已记录。 - `media` #1--82 已在 41.13 各分配一个主要阶段;没有提交因“已覆盖”而从审计记录消失。 - 第一轮建议顺序已固定为 E1 → E2-1 → E3-1a → E3-1b → E4-1/J1 → E6-1 → E7-1;其余按样片、截图或产品策略决策。 -- 下一检查点整理 MPV 可决策实施总表:合并 mpv-android B1--B3、libplacebo B4、mpv B5--B11、FFmpeg C0/C1/C2 和 WebHTV 本地 native patch,形成少量成套 rebuild 批次。 +- E4-1 实现提交及恢复 tag 已完成;下一步整理 MPV 可决策实施总表:合并 mpv-android B1--B3、libplacebo B4、mpv B5--B11、FFmpeg C0/C1/C2 和 WebHTV 本地 native patch,形成少量成套 rebuild 批次。 ## 检查点 42:2026-08-21 MPV 可决策实施批次总表 @@ -4856,3 +4860,67 @@ C3 的触发来源主要是 media `990abc2368fd74779f525ee345734470659f3d53`(` - MPV:需要修正本地输出策略;问题与上游 FFmpeg C2 是否合并无关,先修 App gate,再做 native 回归。 - Exo:根因已定位为“P8.1 静态能力误判 + 非真正 HDR10 fallback”;在 A/B 前不改网络超时、不擅自回滚 A1-2。 - 本检查点没有新的代码 commit/tag;后续代码实施必须重新建立阶段基线并按本文件记录原子 commit 与恢复 tag。 + +## 检查点 47:2026-08-29 P2-2 DV7 metadata/codecpar 实施验收 + +- P2-2 已按批准的窄适配完成:仅修改现有 DV7 HDR10 base-layer fallback 的 metadata-missing 检测、BSF 错误传播、`par_out`→codecpar 同步、`dv_el_present=false` 和 `INT_MAX` 边界;没有升级 lock、FFmpeg/libplacebo/mpv-android、JNI 或 Android EL 策略。 +- 证据:完整双 ABI native build/install 通过;`scripts/verify_mpv_native_assets.sh --require-elf` 对 `arm64-v8a`/`armeabi-v7a` 通过;Mobile arm64 Debug APK 构建通过且 APK 内 MPV assets 与工作区一致;USB 设备 vivo `V2453A`(`10CF6H1D2L0009S`)安装并启动成功;用户确认 DV7 及邻接播放验证通过。 +- 保护:两份 `libplayer.so` 字节不变;`AGENTS.md` 和构建生成的 `app/.cxx/` 不属于任务提交范围;回滚锚点为 `recovery/P2-2-MPV-DV7-METADATA-CODECPAR/baseline-20260829-0342`。 +- 当前状态:本检查点的实施验收已由检查点 48 完成 commit/tag 闭环;C2 仍暂缓,下一 MPV 阶段按队列评估 P3。 + +## 检查点 48:2026-08-29 P2-2 commit/tag 收尾完成 + +- P2-2 原子实施提交:`ba47756d7e463abeb9377088b819a2520e150935`。 +- 恢复 tag:`recovery/P2-2-MPV-DV7-METADATA-CODECPAR/20260829065811-ba47756d7e46`,在提交成功后立即创建,tag 阶段耗时 0 秒。 +- 通过证据:双 ABI native build/install、`verify_mpv_native_assets.sh --require-elf`、Mobile arm64 Debug APK `8c3f1d569d5b325d1e577a5a77d196c800c167159d76f313adc2c3bb02049a4c`、APK asset identity、USB V2453A 安装/启动,以及用户确认的 DV7 与邻接播放验证。 +- 任务状态:P2-2 已完成并关闭;不改变任何 lock、FFmpeg/libplacebo/mpv-android revision、JNI API、`libplayer.so` 或 Android EL 策略。下一 MPV 阶段为 P3,需单独评估/批准。 + +## 检查点 49:2026-08-29 P3 AudioTrack 实施与当前设备验收 + +- P3-2 已按批准的窄适配完成:保留锁定树的 carrier rate、本地全 API TrueHD 7.1 workaround 和 PCM fallback,只为 Android 12+ 的 DTS-HD MA 8-channel carrier 增加 7.1 mask,并让 App probe 与 native 使用一致的 rate/mask 条件。 +- 构建证据:Java 定向单测、完整 patch-stack `--prepare-only`、双 ABI native build/install、`verify_mpv_native_assets.sh --require-elf` 和 Mobile arm64 Debug APK 均通过;APK SHA-256 为 `ad57a1d453281f21921f5898724966aae61aab5c8574537c7729afbc82da39b8`。 +- 资产证据:`libmpv.so` SHA-256 为 `04cfe3ae40118ec77b988323791925b67014b7dda33fdbe54848db8ff219c9a5`(arm64)和 `d13da6308db9c6d1757a8c71928284efd83e9de82a14e5465293fc297ab2cc75`(armv7);两个 `libplayer.so` Git blob 与基线 HEAD 一致,lock/JNI/Exo/FFmpeg/libplacebo/mpv-android revision 均未改变。 +- 实机证据:vivo `V2453A`、Android 15/API 35 上,DTS-HD MA 5.1/7.1、TrueHD 7.1、E-AC3/Atmos 7.1.4、AC3 5.1 和 LPCM 7.1 均进入播放;pause/resume 和 seek 保持对应 AudioTrack 会话,最终活动轨道 underruns 为 0,App PID 未变化,未出现 crash/ANR/native fatal/AudioTrack init failure。 +- 限制:当前输出设备是手机扬声器,只能证明多声道 PCM fallback 与生命周期稳定;DTS-HD HRA 实机、API 29/30、HDMI/ARC/eARC/USB 原码直通、AVR 格式显示和 route hotplug 仍需对应设备,不能由本轮结果代替。 +- 当前状态:P3 已达到当前可用设备的发布门槛,等待 task guard 原子提交和 annotated recovery tag;详细记录与回滚边界见 [P3-mpv-audiotrack.md](P3-mpv-audiotrack.md)。 + +## 检查点 50:2026-08-29 P3 commit/tag 收尾完成 + +- P3 原子实施提交:`d82336bde585b62af43771284075a0a94a3d999e`。 +- 恢复 tag:`recovery/P3/20260829094014-d82336bde585`,由 task guard 在提交成功后立即创建,tag 阶段耗时 0 秒。 +- 提交范围仅包含 P3 的 Java capability probe/单测、MPV AudioTrack patch、双 ABI `libmpv.so`、构建/验证契约和对应文档;`AGENTS.md` 保持为用户既有未提交改动,`libplayer.so`、locks、Exo、FFmpeg、libplacebo、mpv-android revision 均未改变。 +- 当前状态:P3 已完成并关闭。手机扬声器路由上的 PCM fallback 与生命周期验证通过;HDMI/ARC/eARC/USB 接收器上的 DTS-HD HRA/MA、TrueHD 原码显示和 route hotplug 仅作为后续硬件证据补充,不重新打开或扩大 P3 代码范围。 + +## 检查点 51:2026-08-30 C2 转换 P8.1 零输出与上游复核 + +- 当前电视证据表明 C2 的失败顺序是 MediaCodec 零输出/释放在先、Java 主线程同步属性阻塞在后;`reader-pts`、`chapter-list` 和 `current-tracks` 只会放大 native 失败并阻止定时回退,不能作为码流根因。 +- 离线 packet 对照已否定重复 RPU 与 RPU NAL 顺序假设:P7 原始区间和转换 P8.1 每个 packet 均只有一个 RPU,转换输出已删除 EL;正常原生 P8.1 与转换 P8.1 的 RPU 都位于 VCL 之后。详细样片、数量和日志路径见 [C2-dv7-p81-bsf.md](C2-dv7-p81-bsf.md)。 +- `FongMi/FFmpeg` 的重落基提交 `86b827daa9401f781f8660ea511a2cae0baa2833` 与锁定 `177f090e0503b7e013922ca903bde14b1c375f18` patch-id 相同;当前头 `5e6ba5e987284d8ecb6dc25d2d3fd45d309f3fdd` 仅公开 RPU parser,没有本故障修复,处置为“不升级、不移植”。 +- `FongMi/mpv` 的 `c318236b8882af860f16f936225430ad053a2179` 处理缺失独立 EL stream 的 pairing,`e8673660ab7ee5d4ea8f93e4bf3a6e170ab2a19a` 处理 GPU peak-detection metadata;`FongMi/mpv-android` 的 `e1a1f75106afefa6fb3ec9aa6c9ca081155486dd` 只导出 renderer SDK。三项均不覆盖 C2 转换流到 Dolby MediaCodec 的零输出,处置为“本故障忽略,按各自任务另行评估”。 +- 最新 MPV trace `p-dg4unu-1` 显示自动模式实际为 `surface/mediacodec_embed`,不是 OpenGL GPU;`FILE_LOADED` 后 MediaCodec 先进入 `Uninitialized` 并无法 dequeue output,约 3 秒后 `reader-pts` 才开始长时间阻塞。P8.1 info 日志已请求,但 Java 筛选遗漏 `Dolby Vision profile`,而本应放行的 `MediaCodec started successfully` 没有出现。 +- C2 下一步只放行一次 P8.1 Dolby profile 初始化诊断,采集最终 profile 与厂商 codec 结果;在该证据前不修改锁定版本、BSF、CSD、硬解、Surface、Vulkan/OpenGL 或回退策略。 + +## 检查点 52:2026-08-30 C2 厂商 Dolby decoder 释放顺序确认 + +- 最新有效 trace `p-dhezv2-1` 已确认转换结果被识别为 Dolby Vision profile 8,且 `c2.mtk.dvhe.st.decoder` 启动成功;厂商 decoder 在无首帧时主动进入 `Released`,随后才出现 output dequeue 失败和主线程 `reader-pts` 长时间阻塞。 +- 因此错误 renderer、错误 MIME/profile/codec 和 Java 同步查询均不再作为码流首因。完整证据与时间线见 [C2-dv7-p81-bsf.md](C2-dv7-p81-bsf.md)。 +- 下一单元只验证转换输出残留的 `AV_PKT_DATA_HEVC_CONF`:该 side data 表示已被删除的增强层配置,FFmpeg 自带 `dovi_split` 在输出端会明确删除。验证不得同时改变 RPU、extradata、packet、Surface、GPU、解码器选择或回退策略;若电视仍无首帧,则否定该假设并转向 FEL RPU 重写兼容性。 + +## 检查点 53:2026-08-30 dev2 beta 覆盖与 fongmi-sync 合并 + +- 用户目标:以 `origin/beta` 最新头 `8c515e4cce1e0e4596e3e0884a3ab8a37ed117a0` 覆盖 `dev2` 工作基线,再合并 `fish2018/webhtv:fongmi-sync` 当前头 `4489ca9ecc91c2c30fd23610cb0342aa1224717b`。 +- 恢复锚点:旧 `dev2` 提交链保存在本地分支 `backup/dev2-before-beta-overwrite-20260830`,beta 基线保存在 `backup/dev2-beta-baseline-20260830`;既有 E7-2 工作继续保留在原有 `stash@{0}`、`stash@{1}`、`stash@{2}`,未应用到本次合并。 +- 合并状态:已执行 `git merge --no-commit --no-ff fish2018/fongmi-sync`;8 个内容冲突已完成组合解析,保留 beta 的缓存/FFmpeg/音频历史/seek/telemetry 逻辑和 fongmi-sync 的 DV7/P8.1、Vulkan、Surface teardown、Exo DV5 renderer 及最新治理记录;暂存树为 238 个文件、37231 行新增、812 行删除,无未合并路径或冲突标记。 +- 验证:`git diff --cached --check`、全仓冲突标记检查和 task guard 检查已通过;Gradle 任务列表探测曾在 120 秒后超时,尚未替代 Java 编译结论。 +- 回滚:放弃未提交合并可回到 `backup/dev2-beta-baseline-20260830`;旧 dev2 工作链回到 `backup/dev2-before-beta-overwrite-20260830`;本地 stash 不删除。 +- 验证更新:`:app:compileMobileArm64_v8aDebugJavaWithJavac` 已通过,结果为 `BUILD SUCCESSFUL`;仅有仓库已有的 32 位 `armeabi-v7a` native library warning。 +- 下一动作:运行一次 `:app:assembleMobileArm64_v8aDebug` native/CMake 联合验证;通过后创建 dev2 合并提交和本地恢复 tag,不推送远端。 + +## 检查点 54:2026-08-30 dev2 合并 Java 编译通过 + +- 完成:在未提交的 `dev2 <- beta + fish2018/fongmi-sync` 合并树上运行 `:app:compileMobileArm64_v8aDebugJavaWithJavac`,退出码为 0,Gradle 报告 `BUILD SUCCESSFUL in 1m 38s`。 +- 结果:合并后的 Java/API/资源生成链通过;CXX5202 仅提示 `armeabi-v7a` 32 位 native library,与本次 Java 编译失败无关。 +- 验证更新:`:app:assembleMobileArm64_v8aDebug` 已通过,退出码为 0,Gradle 报告 `BUILD SUCCESSFUL in 4m 51s`;同样仅有 CXX5202 32 位 native library warning。 +- 回滚锚点:`backup/dev2-beta-baseline-20260830`、`backup/dev2-before-beta-overwrite-20260830`;合并源 `4489ca9ecc91c2c30fd23610cb0342aa1224717b` 保持不变。 +- 未决:尚未创建合并提交。 +- 下一动作:创建 dev2 两父合并提交并创建 `recovery/dev2-beta-fongmi-sync-20260830/` 本地 annotated tag,不推送。 diff --git a/scripts/build_media_deps.sh b/scripts/build_media_deps.sh index b01d9f69c8..5cb9face1e 100755 --- a/scripts/build_media_deps.sh +++ b/scripts/build_media_deps.sh @@ -231,22 +231,44 @@ apply_media_patches() { local patch_dir="$THIRD_PARTY_DIR/patches" local patch_file [[ -d "$patch_dir" ]] || return 0 - # Deferred Cues depends on the existing Matroska/DV and playback-fix hunks, so - # apply it last instead of relying on filesystem glob order. + # Keep dependency and release order explicit instead of relying on filesystem glob order. local patches=( "$patch_dir/media3-danmaku-live.patch" "$patch_dir/media3-dolby-vision-matroska.patch" "$patch_dir/media3-upstream-playback-fixes-2026-08.patch" + "$patch_dir/media3-exo-hdr-parser-safety.patch" "$patch_dir/media3-deferred-cues.patch" + "$patch_dir/media3-exo-eac3-joc-pixel-guard.patch" + "$patch_dir/media3-exo-dts-14bit-frame-size.patch" + "$patch_dir/media3-exo-subtitle-byte-safety.patch" + "$patch_dir/media3-exo-cue-data-contract.patch" + "$patch_dir/media3-exo-bounded-cache-writer.patch" + "$patch_dir/media3-exo-iso-reader-safety.patch" + "$patch_dir/media3-exo-iso-multi-extent.patch" + "$patch_dir/media3-precache-hls-safety.patch" ) for patch_file in "${patches[@]}"; do [[ -f "$patch_file" ]] || continue echo "Applying Media3 patch $(basename "$patch_file")" - git -C "$MEDIA_DIR" apply --check "$patch_file" - git -C "$MEDIA_DIR" apply "$patch_file" + apply_media_patch_lf "$patch_file" "$MEDIA_DIR" --unidiff-zero done } +apply_media_patch_lf() { + local patch_file="$1" + local target_dir="$2" + shift 2 + local apply_args=("$@") + # git apply on Windows cannot parse CRLF-formatted patches whose context + # lines contain a bare CR; GNU patch strips trailing CRs automatically. + if git -C "$target_dir" apply --check "${apply_args[@]}" "$patch_file" 2>/dev/null; then + git -C "$target_dir" apply "${apply_args[@]}" "$patch_file" + else + patch -p1 --dry-run -d "$target_dir" < "$patch_file" >/dev/null 2>&1 \ + && patch -p1 -d "$target_dir" < "$patch_file" + fi +} + apply_nextlib_patches() { local patch_file local patches=( @@ -259,8 +281,7 @@ apply_nextlib_patches() { exit 1 fi echo "Applying nextlib patch $(basename "$patch_file")" - git -C "$NEXTLIB_DIR" apply --check "$patch_file" - git -C "$NEXTLIB_DIR" apply "$patch_file" + apply_media_patch_lf "$patch_file" "$NEXTLIB_DIR" done } @@ -274,8 +295,7 @@ apply_media_build_mirrors() { exit 1 fi echo "Applying temporary Media3 Gradle Aliyun mirrors" - git -C "$MEDIA_DIR" apply --check "$patch_file" - git -C "$MEDIA_DIR" apply "$patch_file" + apply_media_patch_lf "$patch_file" "$MEDIA_DIR" } prepare_android_env() { diff --git a/scripts/build_mpv_native.sh b/scripts/build_mpv_native.sh index 3422536838..8a669b2e90 100755 --- a/scripts/build_mpv_native.sh +++ b/scripts/build_mpv_native.sh @@ -7,6 +7,7 @@ OVERRIDE_DIR="$ROOT/third_party/mpv-native-overrides" MPV_DISC_PATCH="$ROOT/third_party/patches/mpv-stream-cb-disc-controls.patch" MPV_DOVI_SURFACE_PATCH="$ROOT/third_party/patches/mpv-android-dovi-el-surface.patch" MPV_DOVI_HDR10_BL_PATCH="$ROOT/third_party/patches/mpv-dovi-profile7-hdr10-base-layer.patch" +MPV_DOVI_P81_PATCH="$ROOT/third_party/patches/mpv-dovi-profile7-p81.patch" MPV_AUDIO_TRUEHD_PATCH="$ROOT/third_party/patches/mpv-audiotrack-truehd-channel-mask.patch" MPV_OPTIONAL_OSD_PATCH="$ROOT/third_party/patches/mpv-mediacodec-embed-optional-osd.patch" MPV_MEDIACODEC_TIMED_RELEASE_PATCH="$ROOT/third_party/patches/mpv-mediacodec-embed-timed-release.patch" @@ -15,9 +16,14 @@ MPV_VULKAN_CONVERSION_PATCH="$ROOT/third_party/patches/mpv-android-vulkan-conver MPV_VULKAN_SMART_PATCH="$ROOT/third_party/patches/mpv-android-vulkan-smart-backend.patch" MPV_VULKAN_LEGACY_PATCH="$ROOT/third_party/patches/mpv-android-vulkan-legacy-backend.patch" MPV_AIMAGEREADER_STABLE_PATCH="$ROOT/third_party/patches/mpv-aimagereader-stable-flow.patch" +MPV_P2_GENERIC_UV_PATCH="$ROOT/third_party/patches/mpv-p2-generic-uv.patch" MPV_AIMAGEREADER_STABLE_SOURCE="$OVERRIDE_DIR/aimagereader-stable/video/out/hwdec/hwdec_aimagereader_vk_stable.c" MPV_AIMAGEREADER_STABLE_SHADER="$OVERRIDE_DIR/aimagereader-stable/video/out/hwdec/hwdec_aimagereader_vk_stable.comp" MPV_MATROSKA_PATCH="$ROOT/third_party/patches/mpv-matroska-segment-end.patch" +MPV_P1_PACKED_RGB10_PATCH="$ROOT/third_party/patches/mpv-p1-packed-rgb10.patch" +MPV_P1_EBML_DEFAULTS_PATCH="$ROOT/third_party/patches/mpv-p1-ebml-defaults.patch" +MPV_P1_HLS_EDITION_PATCH="$ROOT/third_party/patches/mpv-p1-hls-edition.patch" +LIBPLACEBO_P1_ALPHA_PATCH="$ROOT/third_party/patches/libplacebo-p1-alpha.patch" FFMPEG_PROXY_RANGE_PATCH="$ROOT/third_party/patches/ffmpeg-webhtv-proxy-range.patch" FFMPEG_MEDIACODEC_STARVATION_PATCH="$ROOT/third_party/patches/ffmpeg-mediacodec-port-starvation.patch" WORK_DIR="${MPV_NATIVE_WORK_DIR:-$ROOT/build/mpv-native}" @@ -389,6 +395,32 @@ cmake_path.write_text(cmake_text, encoding="utf-8") PY } +generate_mpv_shader_header() { + local stage="$1" + local source="$2" + local header="$3" + local symbol="$4" + local generated_dir="$WORK_DIR/generated-shaders" + local stem="${header##*/}" + local spv="$generated_dir/$stem.spv" + local initializer="$generated_dir/$stem.inc" + + mkdir -p "$generated_dir" + "$GLSLC" -fshader-stage="$stage" --target-env=vulkan1.2 -O \ + -o "$spv" "$source" + "$SPIRV_VAL" --target-env vulkan1.2 "$spv" + "$GLSLC" -fshader-stage="$stage" --target-env=vulkan1.2 -O -mfmt=c \ + -o "$initializer" "$source" + { + printf '// Generated from %s with:\n' "${source##*/}" + printf '// glslc -fshader-stage=%s --target-env=vulkan1.2 -O -mfmt=c\n' \ + "$stage" + printf 'static const uint32_t %s[] = ' "$symbol" + cat "$initializer" + printf ';\n' + } >"$header" +} + prepare_sources() { local deps="$BUILDSCRIPTS/deps" mkdir -p "$deps" @@ -429,6 +461,9 @@ prepare_sources() { printf '%s\n' "$NDK_VERSION" >"$shaderc_marker" fi checkout_repo libplacebo "$LIBPLACEBO_REPO" "$LIBPLACEBO_COMMIT" "$deps/libplacebo" "$LIBPLACEBO_SUBMODULES" + [ -f "$LIBPLACEBO_P1_ALPHA_PATCH" ] || die "missing libplacebo alpha correctness patch: $LIBPLACEBO_P1_ALPHA_PATCH" + git -C "$deps/libplacebo" apply --check "$LIBPLACEBO_P1_ALPHA_PATCH" + git -C "$deps/libplacebo" apply "$LIBPLACEBO_P1_ALPHA_PATCH" if [ "$ENABLE_LIBCURL" -eq 1 ]; then extract_archive nghttp2 "$NGHTTP2_URL" "$NGHTTP2_SHA256" "$deps/nghttp2" extract_archive curl "$CURL_URL" "$CURL_SHA256" "$deps/curl" @@ -483,12 +518,37 @@ prepare_sources() { [ -f "$MPV_DOVI_HDR10_BL_PATCH" ] || die "missing MPV Dolby Vision Profile 7 HDR10 base-layer patch: $MPV_DOVI_HDR10_BL_PATCH" git -C "$deps/mpv" apply --check --recount "$MPV_DOVI_HDR10_BL_PATCH" git -C "$deps/mpv" apply --recount "$MPV_DOVI_HDR10_BL_PATCH" - [ -f "$MPV_AUDIO_TRUEHD_PATCH" ] || die "missing MPV AudioTrack TrueHD channel-mask patch: $MPV_AUDIO_TRUEHD_PATCH" + [ -f "$MPV_DOVI_P81_PATCH" ] || die "missing MPV Dolby Vision Profile 7 P8.1 patch: $MPV_DOVI_P81_PATCH" + git -C "$deps/mpv" apply --check --recount "$MPV_DOVI_P81_PATCH" + git -C "$deps/mpv" apply --recount "$MPV_DOVI_P81_PATCH" + grep -Fq 'av_bsf_get_by_name(filter_name)' "$deps/mpv/demux/dovi_split.c" || \ + die "MPV Dolby Vision Profile 7 P8.1 BSF selection is absent" + grep -Fq 'DV7 P8.1 conversion: using FFmpeg dovi_rpu BSF.' "$deps/mpv/demux/dovi_split.c" || \ + die "MPV Dolby Vision Profile 7 P8.1 conversion marker is absent" + grep -Fq 'DV7 P8.1 conversion: removed stale enhancement-layer configuration.' "$deps/mpv/demux/dovi_split.c" || \ + die "MPV Dolby Vision Profile 7 P8.1 stale enhancement-layer configuration guard is absent" + grep -Fq '(!s->base_only && !s->convert_p81)' "$deps/mpv/demux/dovi_split.c" || \ + die "MPV Dolby Vision Profile 7 P8.1 base-packet filter guard is absent" + grep -Fq '(!bl->codec->dv_el_present && !base_only && !convert_p81)' "$deps/mpv/demux/dovi_split.c" || \ + die "MPV Dolby Vision Profile 7 metadata-missing splitter guard is absent" + grep -Fq 'MPSWAP(AVCodecParameters, *bl->codec->lav_codecpar, *filtered)' "$deps/mpv/demux/dovi_split.c" || \ + die "MPV Dolby Vision Profile 7 filtered codec parameters are not synchronized" + grep -Fq 'bl->codec->dv_el_present = false' "$deps/mpv/demux/dovi_split.c" || \ + die "MPV Dolby Vision Profile 7 enhancement-layer metadata is not cleared" + grep -Fq 'bl_dp->len > INT_MAX' "$deps/mpv/demux/dovi_split.c" || \ + die "MPV Dolby Vision Profile 7 packet-size guard is absent" + [ -f "$MPV_AUDIO_TRUEHD_PATCH" ] || die "missing MPV AudioTrack codec-aware channel-mask patch: $MPV_AUDIO_TRUEHD_PATCH" git -C "$deps/mpv" apply --check "$MPV_AUDIO_TRUEHD_PATCH" git -C "$deps/mpv" apply "$MPV_AUDIO_TRUEHD_PATCH" + grep -Fq 'ENTRY(BuildVersion)' "$deps/mpv/audio/out/ao_audiotrack.c" || \ + die "MPV AudioTrack Android API mapping is absent" + grep -Fq 'BuildVersion.SDK_INT >= ANDROID_API_LEVEL_S &&' "$deps/mpv/audio/out/ao_audiotrack.c" || \ + die "MPV AudioTrack Android 12 carrier gate is absent" + grep -Fq 'ao->channels.num == 8' "$deps/mpv/audio/out/ao_audiotrack.c" || \ + die "MPV AudioTrack 8-channel carrier gate is absent" [ -f "$MPV_MEDIACODEC_TIMED_RELEASE_PATCH" ] || die "missing MPV MediaCodec timed-release patch: $MPV_MEDIACODEC_TIMED_RELEASE_PATCH" - git -C "$deps/mpv" apply --check "$MPV_MEDIACODEC_TIMED_RELEASE_PATCH" - git -C "$deps/mpv" apply "$MPV_MEDIACODEC_TIMED_RELEASE_PATCH" + git -C "$deps/mpv" apply --check --recount "$MPV_MEDIACODEC_TIMED_RELEASE_PATCH" + git -C "$deps/mpv" apply --recount "$MPV_MEDIACODEC_TIMED_RELEASE_PATCH" [ -f "$MPV_OPTIONAL_OSD_PATCH" ] || die "missing MPV optional direct-output OSD patch: $MPV_OPTIONAL_OSD_PATCH" git -C "$deps/mpv" apply --check "$MPV_OPTIONAL_OSD_PATCH" git -C "$deps/mpv" apply "$MPV_OPTIONAL_OSD_PATCH" @@ -507,9 +567,31 @@ prepare_sources() { [ -f "$MPV_AIMAGEREADER_STABLE_PATCH" ] || die "missing MPV stable AImageReader flow patch: $MPV_AIMAGEREADER_STABLE_PATCH" git -C "$deps/mpv" apply --check "$MPV_AIMAGEREADER_STABLE_PATCH" git -C "$deps/mpv" apply "$MPV_AIMAGEREADER_STABLE_PATCH" + [ -f "$MPV_P2_GENERIC_UV_PATCH" ] || die "missing MPV P2 generic UV patch: $MPV_P2_GENERIC_UV_PATCH" + git -C "$deps/mpv" apply --check "$MPV_P2_GENERIC_UV_PATCH" + git -C "$deps/mpv" apply "$MPV_P2_GENERIC_UV_PATCH" + generate_mpv_shader_header compute \ + "$deps/mpv/video/out/hwdec/hwdec_aimagereader.comp" \ + "$deps/mpv/video/out/hwdec/hwdec_aimagereader_comp.h" \ + aimagereader_comp_spv + generate_mpv_shader_header fragment \ + "$deps/mpv/video/out/hwdec/hwdec_aimagereader.frag" \ + "$deps/mpv/video/out/hwdec/hwdec_aimagereader_frag.h" \ + aimagereader_frag_spv + python3 "$ROOT/scripts/verify_mpv_vulkan_shader_contract.py" \ + --mpv-source "$deps/mpv" [ -f "$MPV_MATROSKA_PATCH" ] || die "missing MPV Matroska segment patch: $MPV_MATROSKA_PATCH" git -C "$deps/mpv" apply --check "$MPV_MATROSKA_PATCH" git -C "$deps/mpv" apply "$MPV_MATROSKA_PATCH" + [ -f "$MPV_P1_PACKED_RGB10_PATCH" ] || die "missing MPV packed RGB10 patch: $MPV_P1_PACKED_RGB10_PATCH" + git -C "$deps/mpv" apply --check "$MPV_P1_PACKED_RGB10_PATCH" + git -C "$deps/mpv" apply "$MPV_P1_PACKED_RGB10_PATCH" + [ -f "$MPV_P1_EBML_DEFAULTS_PATCH" ] || die "missing MPV EBML defaults patch: $MPV_P1_EBML_DEFAULTS_PATCH" + git -C "$deps/mpv" apply --check "$MPV_P1_EBML_DEFAULTS_PATCH" + git -C "$deps/mpv" apply "$MPV_P1_EBML_DEFAULTS_PATCH" + [ -f "$MPV_P1_HLS_EDITION_PATCH" ] || die "missing MPV HLS edition patch: $MPV_P1_HLS_EDITION_PATCH" + git -C "$deps/mpv" apply --check "$MPV_P1_HLS_EDITION_PATCH" + git -C "$deps/mpv" apply "$MPV_P1_HLS_EDITION_PATCH" } patch_dynamic_names() { @@ -589,17 +671,22 @@ verify_directory() { grep -Fq "video output has no queue-safe EL decoder" <<<"$version_strings" || die "MPV Android Dolby Vision EL capability guard missing from $directory/libmpv.so" grep -Fq "DV7 HDR10 fallback: using MediaCodec base-layer decoder" <<<"$version_strings" || die "MPV Dolby Vision Profile 7 HDR10 direct base-layer fallback missing from $directory/libmpv.so" grep -Fq "DV7 HDR10 fallback: stripping EL/RPU before decoder." <<<"$version_strings" || die "MPV Dolby Vision Profile 7 demux base-layer filter missing from $directory/libmpv.so" + grep -Fq "DV7 HDR10 fallback: synchronized decoder parameters to the HDR10 base layer." <<<"$version_strings" || die "MPV Dolby Vision Profile 7 filtered codec-parameter sync missing from $directory/libmpv.so" grep -Fq "DV7 HDR10 fallback: failed to produce base-layer packet." <<<"$version_strings" || die "MPV Dolby Vision Profile 7 filter failure guard missing from $directory/libmpv.so" + grep -Fq "DV7 P8.1 conversion: using FFmpeg dovi_rpu BSF." <<<"$version_strings" || die "MPV Dolby Vision Profile 7 P8.1 conversion missing from $directory/libmpv.so" + grep -Fq "DV7 P8.1 conversion: removed stale enhancement-layer configuration." <<<"$version_strings" || die "MPV Dolby Vision Profile 7 P8.1 stale enhancement-layer configuration guard missing from $directory/libmpv.so" if grep -Fq "Using device native output sample rate for passthrough compatibility" <<<"$version_strings"; then die "obsolete MPV AudioTrack passthrough native-rate patch present in $directory/libmpv.so" fi grep -Fq "Using 7.1 IEC61937 carrier mask for TrueHD" <<<"$version_strings" || die "MPV AudioTrack TrueHD channel-mask patch missing from $directory/libmpv.so" + grep -Fq "Using 7.1 IEC61937 carrier mask for Android 12+ 8-channel stream" <<<"$version_strings" || die "MPV AudioTrack DTS-HD MA channel-mask path missing from $directory/libmpv.so" grep -Fq "WebHTV direct output accepts an optional Android OSD Surface" <<<"$version_strings" || die "MPV optional direct-output OSD patch missing from $directory/libmpv.so" grep -Fq "WebHTV timestamped MediaCodec output enabled" <<<"$version_strings" || die "MPV MediaCodec timestamped-release patch missing from $directory/libmpv.so" grep -Fq "MediaCodec VO drop timing" <<<"$version_strings" || die "MPV MediaCodec output timing diagnostics missing from $directory/libmpv.so" grep -Fq "WebHTV Vulkan auto backend prefers direct AHardwareBuffer sampling" <<<"$version_strings" || die "MPV Android Vulkan smart backend patch missing from $directory/libmpv.so" grep -Fq "WebHTV Vulkan auto uses a queue-safe four-output bounded-fence pool" <<<"$version_strings" || die "MPV Android Vulkan queue-safe conversion pool missing from $directory/libmpv.so" grep -Fq "CPU-precomputed UV transform" <<<"$version_strings" || die "MPV Android Vulkan low-power coordinate transform missing from $directory/libmpv.so" + grep -Fq "Generic Vulkan conversion uses CPU-precomputed UV transform" <<<"$version_strings" || die "MPV Android Vulkan generic coordinate transform missing from $directory/libmpv.so" grep -Fq "Stable Vulkan conversion preserves Dolby Vision raw YUV component mapping" <<<"$version_strings" || die "MPV Android Vulkan stable Dolby Vision mapping missing from $directory/libmpv.so" grep -Fq "WebHTV Vulkan keeps AImage until the conversion fence completes" <<<"$version_strings" || die "MPV Android Vulkan stable AImage lifetime patch missing from $directory/libmpv.so" grep -Fq "WebHTV AImageReader uses stable release/acquire flow" <<<"$version_strings" || die "MPV Android stable AImageReader release/acquire patch missing from $directory/libmpv.so" diff --git a/scripts/verify_mpv_native_assets.sh b/scripts/verify_mpv_native_assets.sh index e08e44c706..972b4e6baf 100755 --- a/scripts/verify_mpv_native_assets.sh +++ b/scripts/verify_mpv_native_assets.sh @@ -194,13 +194,17 @@ verify_abi() { contains_string "$directory/libmpv.so" "video output has no queue-safe EL decoder" contains_string "$directory/libmpv.so" "DV7 HDR10 fallback: using MediaCodec base-layer decoder" contains_string "$directory/libmpv.so" "DV7 HDR10 fallback: stripping EL/RPU before decoder." + contains_string "$directory/libmpv.so" "DV7 HDR10 fallback: synchronized decoder parameters to the HDR10 base layer." contains_string "$directory/libmpv.so" "DV7 HDR10 fallback: failed to produce base-layer packet." + contains_string "$directory/libmpv.so" "DV7 P8.1 conversion: removed stale enhancement-layer configuration." reject_string "$directory/libmpv.so" "DV7 HDR10 fallback: preserving decoder input and stripping Dolby Vision frame metadata." reject_string "$directory/libmpv.so" "Using device native output sample rate for passthrough compatibility" contains_string "$directory/libmpv.so" "Using 7.1 IEC61937 carrier mask for TrueHD" + contains_string "$directory/libmpv.so" "Using 7.1 IEC61937 carrier mask for Android 12+ 8-channel stream" contains_string "$directory/libmpv.so" "WebHTV Vulkan auto backend prefers direct AHardwareBuffer sampling" contains_string "$directory/libmpv.so" "WebHTV Vulkan auto uses a queue-safe four-output bounded-fence pool" contains_string "$directory/libmpv.so" "CPU-precomputed UV transform" + contains_string "$directory/libmpv.so" "Generic Vulkan conversion uses CPU-precomputed UV transform" contains_string "$directory/libmpv.so" "Stable Vulkan conversion preserves Dolby Vision raw YUV component mapping" contains_string "$directory/libmpv.so" "WebHTV Vulkan keeps AImage until the conversion fence completes" contains_string "$directory/libmpv.so" "WebHTV AImageReader uses stable release/acquire flow" diff --git a/scripts/verify_mpv_vulkan_shader_contract.py b/scripts/verify_mpv_vulkan_shader_contract.py index 38c585cea9..f558368a40 100644 --- a/scripts/verify_mpv_vulkan_shader_contract.py +++ b/scripts/verify_mpv_vulkan_shader_contract.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 +import argparse from pathlib import Path import re @@ -8,6 +9,7 @@ ROOT = Path(__file__).resolve().parent.parent SOURCE = ROOT / "third_party/mpv-native-overrides/aimagereader-stable/video/out/hwdec/hwdec_aimagereader_vk_stable.c" SHADER = ROOT / "third_party/mpv-native-overrides/aimagereader-stable/video/out/hwdec/hwdec_aimagereader_vk_stable.comp" STALE_HEADER = ROOT / "third_party/mpv-native-overrides/aimagereader-stable/video/out/hwdec/hwdec_aimagereader_vk_stable_comp.h" +P2_PATCH = ROOT / "third_party/patches/mpv-p2-generic-uv.patch" def require(pattern: str, text: str, description: str) -> re.Match[str]: @@ -17,47 +19,137 @@ def require(pattern: str, text: str, description: str) -> re.Match[str]: return match -source = SOURCE.read_text(encoding="utf-8") -shader = SHADER.read_text(encoding="utf-8") +def require_tokens(text: str, tokens: tuple[str, ...], description: str) -> None: + for token in tokens: + if token not in text: + raise SystemExit(f"{description} is missing: {token}") -shader_group = require( - r"layout\s*\(\s*local_size_x\s*=\s*(\d+)\s*,\s*local_size_y\s*=\s*(\d+)\s*\)\s*in\s*;", - shader, - "stable Vulkan shader workgroup declaration", -) -source_x = int(require(r"^#define\s+STABLE_WORKGROUP_X\s+(\d+)\s*$", source, "STABLE_WORKGROUP_X").group(1)) -source_y = int(require(r"^#define\s+STABLE_WORKGROUP_Y\s+(\d+)\s*$", source, "STABLE_WORKGROUP_Y").group(1)) -shader_x, shader_y = map(int, shader_group.groups()) -if (source_x, source_y) != (shader_x, shader_y): - raise SystemExit( - "stable Vulkan dispatch/shader mismatch: " - f"C={source_x}x{source_y}, shader={shader_x}x{shader_y}" + +def verify_stable() -> None: + source = SOURCE.read_text(encoding="utf-8") + shader = SHADER.read_text(encoding="utf-8") + shader_group = require( + r"layout\s*\(\s*local_size_x\s*=\s*(\d+)\s*,\s*local_size_y\s*=\s*(\d+)\s*\)\s*in\s*;", + shader, + "stable Vulkan shader workgroup declaration", ) -if source_x * source_y > 128: - raise SystemExit( - "stable Vulkan shader exceeds the 128-invocation Vulkan core baseline: " - f"{source_x}x{source_y}" + source_x = int(require( + r"^#define\s+STABLE_WORKGROUP_X\s+(\d+)\s*$", + source, + "STABLE_WORKGROUP_X", + ).group(1)) + source_y = int(require( + r"^#define\s+STABLE_WORKGROUP_Y\s+(\d+)\s*$", + source, + "STABLE_WORKGROUP_Y", + ).group(1)) + shader_x, shader_y = map(int, shader_group.groups()) + if (source_x, source_y) != (shader_x, shader_y): + raise SystemExit( + "stable Vulkan dispatch/shader mismatch: " + f"C={source_x}x{source_y}, shader={shader_x}x{shader_y}" + ) + if source_x * source_y > 128: + raise SystemExit( + "stable Vulkan shader exceeds the 128-invocation Vulkan core baseline: " + f"{source_x}x{source_y}" + ) + require_tokens(shader, ( + "vec2 uv_offset;", + "vec2 uv_scale;", + "ivec2 output_size;", + "params.uv_offset", + "params.uv_scale", + ), "stable Vulkan shader") + require_tokens(source, ( + "float uv_offset[2];", + "float uv_scale[2];", + "int32_t output_size[2];", + "aimagereader_vk_stable_comp.inc", + "CPU-precomputed UV transform", + ), "stable Vulkan source") + if STALE_HEADER.exists(): + raise SystemExit(f"unused stale shader header must not exist: {STALE_HEADER}") + print( + "Verified stable Vulkan shader contract: " + f"{source_x}x{source_y}, CPU-precomputed UV transform" ) -for token in ( - "vec2 uv_offset;", - "vec2 uv_scale;", - "ivec2 output_size;", - "params.uv_offset", - "params.uv_scale", -): - if token not in shader: - raise SystemExit(f"stable Vulkan shader is missing optimized coordinate token: {token}") -for token in ( - "float uv_offset[2];", - "float uv_scale[2];", - "int32_t output_size[2];", - "aimagereader_vk_stable_comp.inc", - "CPU-precomputed UV transform", -): - if token not in source: - raise SystemExit(f"stable Vulkan source is missing shader contract token: {token}") -if STALE_HEADER.exists(): - raise SystemExit(f"unused stale shader header must not exist: {STALE_HEADER}") -print(f"Verified stable Vulkan shader contract: {source_x}x{source_y}, CPU-precomputed UV transform") +def verify_p2_patch_scope() -> None: + patch = P2_PATCH.read_text(encoding="utf-8") + paths = tuple( + match.group(1) + for match in re.finditer(r"^diff --git a/(\S+) b/(\S+)$", patch, re.MULTILINE) + if match.group(1) == match.group(2) + ) + expected = ( + "video/out/hwdec/hwdec_aimagereader.comp", + "video/out/hwdec/hwdec_aimagereader.frag", + "video/out/hwdec/hwdec_aimagereader_vk_convert.c", + ) + if paths != expected: + raise SystemExit(f"P2 generic UV patch scope changed: {paths!r}") + require_tokens(patch, ( + "+ vec2 uv_offset;", + "+ vec2 uv_scale;", + "+ float uv_offset[2];", + "+ float uv_scale[2];", + "+_Static_assert(sizeof(struct conversion_push_constants) == 24,", + "+ \"Generic Vulkan conversion uses CPU-precomputed UV transform\\n\");", + ), "P2 generic UV patch") + print("Verified P2 generic UV patch scope: 3 source files") + + +def verify_generic(mpv_source: Path) -> None: + hwdec = mpv_source / "video/out/hwdec" + compute = (hwdec / "hwdec_aimagereader.comp").read_text(encoding="utf-8") + fragment = (hwdec / "hwdec_aimagereader.frag").read_text(encoding="utf-8") + source = (hwdec / "hwdec_aimagereader_vk_convert.c").read_text(encoding="utf-8") + compute_header = (hwdec / "hwdec_aimagereader_comp.h").read_text(encoding="utf-8") + fragment_header = (hwdec / "hwdec_aimagereader_frag.h").read_text(encoding="utf-8") + + for name, shader in (("compute", compute), ("fragment", fragment)): + require_tokens(shader, ( + "vec2 uv_offset;", + "vec2 uv_scale;", + "ivec2 output_size;", + "params.uv_offset", + "params.uv_scale", + ), f"generic Vulkan {name} shader") + for stale in ("ivec2 crop_offset;", "ivec2 crop_size;", "ivec2 source_size;"): + if stale in shader: + raise SystemExit(f"generic Vulkan {name} shader retains stale token: {stale}") + + require_tokens(source, ( + "float uv_offset[2];", + "float uv_scale[2];", + "int32_t output_size[2];", + "_Static_assert(sizeof(struct conversion_push_constants) == 24,", + "(float)((double)crop->left / source.desc.width)", + "((double)source.output_width * source.desc.width)", + "log_conversion_geometry(p, &geometry);", + "Generic Vulkan conversion uses CPU-precomputed UV transform", + "ANDROID_VULKAN_AIMAGEREADER_BACKEND_LEGACY", + "p->release_sync_fd = false;", + "WebHTV Vulkan keeps AImage until the conversion fence completes", + ), "generic Vulkan conversion source") + require_tokens(compute_header, ( + "Generated from hwdec_aimagereader.comp", + "static const uint32_t aimagereader_comp_spv[] = {", + ), "generic Vulkan compute header") + require_tokens(fragment_header, ( + "Generated from hwdec_aimagereader.frag", + "static const uint32_t aimagereader_frag_spv[] = {", + ), "generic Vulkan fragment header") + print("Verified generic Vulkan shader contract: CPU-precomputed UV transform") + + +parser = argparse.ArgumentParser() +parser.add_argument("--mpv-source", type=Path) +args = parser.parse_args() + +verify_stable() +verify_p2_patch_scope() +if args.mpv_source: + verify_generic(args.mpv_source) diff --git a/third_party/exo-dv5-native/MANIFEST.sha256 b/third_party/exo-dv5-native/MANIFEST.sha256 new file mode 100644 index 0000000000..ed0bc81ac2 --- /dev/null +++ b/third_party/exo-dv5-native/MANIFEST.sha256 @@ -0,0 +1,8 @@ +4155b0efd1cce217131d85622bbc49ef447639e9064e204ea2fd98de478d65b1 prebuilt/arm64-v8a/libplacebo.a +eb7aaddb1b210b797f22c3932a0ef3c9bd73a807fa50459310ffa4e52c03c221 prebuilt/arm64-v8a/libshaderc.a +74768014c18ebda433a8555bacbc04fb66ff651c2135a37997ae329181d36060 prebuilt/arm64-v8a/libdovi.a +c24570d237173699b511acdb95fe2d5a975180170970136293e0fc6cd1042167 prebuilt/armeabi-v7a/libplacebo.a +2bc27f79cc2bb9710a21c259dfbb572b04680beeaff802a55f3e1c08d948ff1f prebuilt/armeabi-v7a/libshaderc.a +fb2083995dbf302a83b2963e9f7922ccfed35a5b323b6e18aaaed9364386d9e1 prebuilt/armeabi-v7a/libdovi.a +dd6dbfce53464310e9f5ab92cbc50bc40a55507810405cff4522c5cbcc6d33ad include/libdovi/rpu_parser.h +f35d4515dd8d81c7996af2b20e9605561d1af0c21bc12ba7cc4fa4c60aed2178 licenses/LICENSE.libdovi diff --git a/third_party/exo-dv5-native/README.md b/third_party/exo-dv5-native/README.md new file mode 100644 index 0000000000..1801453ae9 --- /dev/null +++ b/third_party/exo-dv5-native/README.md @@ -0,0 +1,14 @@ +# Exo DV5 native dependencies + +This directory owns the native dependency closure for the independent Exo +DV5 renderer. Build and runtime code must use these repository-relative files +and must not reference another WebHTV workspace. + +- libplacebo: 7.375.0 / API 375, source commit + `b694a21bf2dc176c1e98b8a13c6421a0de5f3da5`. +- shaderc: Android NDK r29 (`29.0.14206865`) staged source, built with + `APP_PLATFORM=android-24`, `APP_STL=c++_static`, once per ABI. +- ABIs: `arm64-v8a` and `armeabi-v7a`; archives are not interchangeable. + +`MANIFEST.sha256` is the authoritative artifact integrity list. The copied +libplacebo LGPL license and the Android toolchain notice are under `licenses/`. diff --git a/third_party/exo-dv5-native/include/libdovi/rpu_parser.h b/third_party/exo-dv5-native/include/libdovi/rpu_parser.h new file mode 100644 index 0000000000..430af1ee9a --- /dev/null +++ b/third_party/exo-dv5-native/include/libdovi/rpu_parser.h @@ -0,0 +1,741 @@ +// SPDX-License-Identifier: MIT + +#ifndef DOVI_H +#define DOVI_H + +#include +#include +#include +#include + +#define DoviNUM_COMPONENTS 3 + +/** + * Opaque Dolby Vision RPU. + * + * Use dovi_rpu_free to free. + * It should be freed regardless of whether or not an error occurred. + */ +typedef struct DoviRpuOpaque DoviRpuOpaque; + +/** + * Struct representing a data buffer + */ +typedef struct { + /** + * Pointer to the data buffer + */ + const uint8_t *data; + /** + * Data buffer size + */ + size_t len; +} DoviData; + +/** + * C struct for rpu_data_header() + */ +typedef struct { + /** + * Profile guessed from the values in the header + */ + uint8_t guessed_profile; + /** + * Enhancement layer type (FEL or MEL) if the RPU is profile 7 + * null pointer if not profile 7 + */ + const char *el_type; + /** + * Deprecated since 3.2.0 + * The field is not actually part of the RPU header + */ + uint8_t rpu_nal_prefix; + uint8_t rpu_type; + uint16_t rpu_format; + uint8_t vdr_rpu_profile; + uint8_t vdr_rpu_level; + bool vdr_seq_info_present_flag; + bool chroma_resampling_explicit_filter_flag; + uint8_t coefficient_data_type; + uint64_t coefficient_log2_denom; + uint8_t vdr_rpu_normalized_idc; + bool bl_video_full_range_flag; + uint64_t bl_bit_depth_minus8; + uint64_t el_bit_depth_minus8; + uint64_t vdr_bit_depth_minus8; + bool spatial_resampling_filter_flag; + uint8_t reserved_zero_3bits; + bool el_spatial_resampling_filter_flag; + bool disable_residual_flag; + bool vdr_dm_metadata_present_flag; + bool use_prev_vdr_rpu_flag; + uint64_t prev_vdr_rpu_id; +} DoviRpuDataHeader; + +/** + * Struct representing a data buffer + */ +typedef struct { + /** + * Pointer to the data buffer. Can be null if length is zero. + */ + const uint16_t *data; + /** + * Data buffer size + */ + size_t len; +} DoviU16Data; + +/** + * Struct representing a data buffer + */ +typedef struct { + /** + * Pointer to the data buffer. Can be null if length is zero. + */ + const uint64_t *data; + /** + * Data buffer size + */ + size_t len; +} DoviU64Data; + +/** + * Struct representing a data buffer + */ +typedef struct { + /** + * Pointer to the data buffer + */ + const int64_t *data; + /** + * Data buffer size + */ + size_t len; +} DoviI64Data; + +/** + * Struct representing a 2D data buffer + */ +typedef struct { + /** + * Pointer to the list of Data structs + */ + const DoviI64Data *const *list; + /** + * List length + */ + size_t len; +} DoviI64Data2D; + +/** + * Struct representing a 2D data buffer + */ +typedef struct { + /** + * Pointer to the list of Data structs + */ + const DoviU64Data *const *list; + /** + * List length + */ + size_t len; +} DoviU64Data2D; + +typedef struct { + DoviU64Data poly_order_minus1; + DoviData linear_interp_flag; + DoviI64Data2D poly_coef_int; + DoviU64Data2D poly_coef; +} DoviPolynomialCurve; + +/** + * Struct representing a 3D data buffer + */ +typedef struct { + /** + * Pointer to the list of Data2D structs + */ + const DoviI64Data2D *const *list; + /** + * List length + */ + size_t len; +} DoviI64Data3D; + +/** + * Struct representing a 3D data buffer + */ +typedef struct { + /** + * Pointer to the list of Data2D structs + */ + const DoviU64Data2D *const *list; + /** + * List length + */ + size_t len; +} DoviU64Data3D; + +typedef struct { + DoviData mmr_order_minus1; + DoviI64Data mmr_constant_int; + DoviU64Data mmr_constant; + DoviI64Data3D mmr_coef_int; + DoviU64Data3D mmr_coef; +} DoviMMRCurve; + +typedef struct { + /** + * [2, 9] + */ + uint64_t num_pivots_minus2; + DoviU16Data pivots; + /** + * Consistent for a component + * Luma (component 0): Polynomial = 0 + * Chroma (components 1 and 2): MMR = 1 + */ + uint8_t mapping_idc; + /** + * mapping_idc = 0, null pointer otherwise + */ + const DoviPolynomialCurve *polynomial; + /** + * mapping_idc = 1, null pointer otherwise + */ + const DoviMMRCurve *mmr; +} DoviReshapingCurve; + +/** + * C struct for rpu_data_nlq() + */ +typedef struct { + uint16_t nlq_offset[DoviNUM_COMPONENTS]; + uint64_t vdr_in_max_int[DoviNUM_COMPONENTS]; + uint64_t vdr_in_max[DoviNUM_COMPONENTS]; + uint64_t linear_deadzone_slope_int[DoviNUM_COMPONENTS]; + uint64_t linear_deadzone_slope[DoviNUM_COMPONENTS]; + uint64_t linear_deadzone_threshold_int[DoviNUM_COMPONENTS]; + uint64_t linear_deadzone_threshold[DoviNUM_COMPONENTS]; +} DoviRpuDataNlq; + +/** + * C struct for rpu_data_mapping() + */ +typedef struct { + uint64_t vdr_rpu_id; + uint64_t mapping_color_space; + uint64_t mapping_chroma_format_idc; + uint64_t num_x_partitions_minus1; + uint64_t num_y_partitions_minus1; + DoviReshapingCurve curves[DoviNUM_COMPONENTS]; + /** + * Set to -1 to represent Option::None + */ + int32_t nlq_method_idc; + /** + * Set to -1 to represent Option::None + */ + int32_t nlq_num_pivots_minus2; + /** + * Length of zero when not present. Only present in profile 4 and 7. + */ + DoviU16Data nlq_pred_pivot_value; + /** + * Pointer to `RpuDataNlq` struct, null if not dual layer profile + */ + const DoviRpuDataNlq *nlq; +} DoviRpuDataMapping; + +/** + * Statistical analysis of the frame: min, max, avg brightness. + */ +typedef struct { + uint16_t min_pq; + uint16_t max_pq; + uint16_t avg_pq; +} DoviExtMetadataBlockLevel1; + +/** + * Creative intent trim passes per target display peak brightness + */ +typedef struct { + uint16_t target_max_pq; + uint16_t trim_slope; + uint16_t trim_offset; + uint16_t trim_power; + uint16_t trim_chroma_weight; + uint16_t trim_saturation_gain; + int16_t ms_weight; +} DoviExtMetadataBlockLevel2; + +typedef struct { + /** + * Pointer to the list of ExtMetadataBlockLevel2 structs + */ + const DoviExtMetadataBlockLevel2 *const *list; + /** + * List length + */ + size_t len; +} DoviLevel2BlockList; + +/** + * Level 1 offsets. + */ +typedef struct { + uint16_t min_pq_offset; + uint16_t max_pq_offset; + uint16_t avg_pq_offset; +} DoviExtMetadataBlockLevel3; + +/** + * Something about temporal stability + */ +typedef struct { + uint16_t anchor_pq; + uint16_t anchor_power; +} DoviExtMetadataBlockLevel4; + +/** + * Active area of the picture (letterbox, aspect ratio) + */ +typedef struct { + uint16_t active_area_left_offset; + uint16_t active_area_right_offset; + uint16_t active_area_top_offset; + uint16_t active_area_bottom_offset; +} DoviExtMetadataBlockLevel5; + +/** + * ST2086/HDR10 metadata fallback + */ +typedef struct { + uint16_t max_display_mastering_luminance; + uint16_t min_display_mastering_luminance; + uint16_t max_content_light_level; + uint16_t max_frame_average_light_level; +} DoviExtMetadataBlockLevel6; + +/** + * Creative intent trim passes per target display peak brightness + * For CM v4.0, L8 metadata only is present and used to compute L2 + * + * This block can have varying byte lengths: 10, 12, 13, 19, 25 + * Depending on the length, the fields parsed default to zero and may not be set. + * Up to (including): + * - 10: ms_weight + * - 12: target_mid_contrast + * - 13: clip_trim + * - 19: saturation_vector_field[0-5] + * - 25: hue_vector_field[0-5] + */ +typedef struct { + uint64_t length; + uint8_t target_display_index; + uint16_t trim_slope; + uint16_t trim_offset; + uint16_t trim_power; + uint16_t trim_chroma_weight; + uint16_t trim_saturation_gain; + uint16_t ms_weight; + uint16_t target_mid_contrast; + uint16_t clip_trim; + uint8_t saturation_vector_field0; + uint8_t saturation_vector_field1; + uint8_t saturation_vector_field2; + uint8_t saturation_vector_field3; + uint8_t saturation_vector_field4; + uint8_t saturation_vector_field5; + uint8_t hue_vector_field0; + uint8_t hue_vector_field1; + uint8_t hue_vector_field2; + uint8_t hue_vector_field3; + uint8_t hue_vector_field4; + uint8_t hue_vector_field5; +} DoviExtMetadataBlockLevel8; + +typedef struct { + /** + * Pointer to the list of ExtMetadataBlockLevel8 structs + */ + const DoviExtMetadataBlockLevel8 *const *list; + /** + * List length + */ + size_t len; +} DoviLevel8BlockList; + +/** + * Source/mastering display color primaries + * + * This block can have varying byte lengths: 1 or 17 + * Depending on the length, the fields parsed default to zero and may not be set. + * Up to (including): + * - 1: source_primary_index + * - 17: source_primary_{red,green,blue,white}_{x,y} + */ +typedef struct { + uint64_t length; + uint8_t source_primary_index; + uint16_t source_primary_red_x; + uint16_t source_primary_red_y; + uint16_t source_primary_green_x; + uint16_t source_primary_green_y; + uint16_t source_primary_blue_x; + uint16_t source_primary_blue_y; + uint16_t source_primary_white_x; + uint16_t source_primary_white_y; +} DoviExtMetadataBlockLevel9; + +/** + * Custom target display information + * + * This block can have varying byte lengths: 5 or 21 + * Depending on the length, the fields parsed default to zero and may not be set. + * Up to (including): + * - 5: target_primary_index + * - 21: target_primary_{red,green,blue,white}_{x,y} + */ +typedef struct { + uint64_t length; + uint8_t target_display_index; + uint16_t target_max_pq; + uint16_t target_min_pq; + uint8_t target_primary_index; + uint16_t target_primary_red_x; + uint16_t target_primary_red_y; + uint16_t target_primary_green_x; + uint16_t target_primary_green_y; + uint16_t target_primary_blue_x; + uint16_t target_primary_blue_y; + uint16_t target_primary_white_x; + uint16_t target_primary_white_y; +} DoviExtMetadataBlockLevel10; + +typedef struct { + /** + * Pointer to the list of ExtMetadataBlockLevel10 structs + */ + const DoviExtMetadataBlockLevel10 *const *list; + /** + * List length + */ + size_t len; +} DoviLevel10BlockList; + +/** + * Content type metadata level + */ +typedef struct { + uint8_t content_type; + uint8_t whitepoint; + bool reference_mode_flag; + uint8_t reserved_byte2; + uint8_t reserved_byte3; +} DoviExtMetadataBlockLevel11; + +/** + * Metadata level present in CM v4.0 + */ +typedef struct { + uint8_t dm_mode; + uint8_t dm_version_index; +} DoviExtMetadataBlockLevel254; + +/** + * Metadata level optionally present in CM v2.9. + * Different display modes (calibration/verify/bypass), debugging + */ +typedef struct { + uint8_t dm_run_mode; + uint8_t dm_run_version; + uint8_t dm_debug0; + uint8_t dm_debug1; + uint8_t dm_debug2; + uint8_t dm_debug3; +} DoviExtMetadataBlockLevel255; + +/** + * C struct for the list of ext_metadata_block() + */ +typedef struct { + /** + * Number of metadata blocks + */ + uint64_t num_ext_blocks; + const DoviExtMetadataBlockLevel1 *level1; + DoviLevel2BlockList level2; + const DoviExtMetadataBlockLevel3 *level3; + const DoviExtMetadataBlockLevel4 *level4; + const DoviExtMetadataBlockLevel5 *level5; + const DoviExtMetadataBlockLevel6 *level6; + DoviLevel8BlockList level8; + const DoviExtMetadataBlockLevel9 *level9; + DoviLevel10BlockList level10; + const DoviExtMetadataBlockLevel11 *level11; + const DoviExtMetadataBlockLevel254 *level254; + const DoviExtMetadataBlockLevel255 *level255; +} DoviDmData; + +/** + * C struct for vdr_dm_data() + */ +typedef struct { + bool compressed; + uint64_t affected_dm_metadata_id; + uint64_t current_dm_metadata_id; + uint64_t scene_refresh_flag; + int16_t ycc_to_rgb_coef0; + int16_t ycc_to_rgb_coef1; + int16_t ycc_to_rgb_coef2; + int16_t ycc_to_rgb_coef3; + int16_t ycc_to_rgb_coef4; + int16_t ycc_to_rgb_coef5; + int16_t ycc_to_rgb_coef6; + int16_t ycc_to_rgb_coef7; + int16_t ycc_to_rgb_coef8; + uint32_t ycc_to_rgb_offset0; + uint32_t ycc_to_rgb_offset1; + uint32_t ycc_to_rgb_offset2; + int16_t rgb_to_lms_coef0; + int16_t rgb_to_lms_coef1; + int16_t rgb_to_lms_coef2; + int16_t rgb_to_lms_coef3; + int16_t rgb_to_lms_coef4; + int16_t rgb_to_lms_coef5; + int16_t rgb_to_lms_coef6; + int16_t rgb_to_lms_coef7; + int16_t rgb_to_lms_coef8; + uint16_t signal_eotf; + uint16_t signal_eotf_param0; + uint16_t signal_eotf_param1; + uint32_t signal_eotf_param2; + uint8_t signal_bit_depth; + uint8_t signal_color_space; + uint8_t signal_chroma_format; + uint8_t signal_full_range_flag; + uint16_t source_min_pq; + uint16_t source_max_pq; + uint16_t source_diagonal; + DoviDmData dm_data; +} DoviVdrDmData; + +/** + * Heap allocated list of valid RPU pointers + */ +typedef struct { + DoviRpuOpaque *const *list; + size_t len; + const char *error; +} DoviRpuOpaqueList; + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +/** + * # Safety + * The pointer to the data must be valid. + * + * Parse a Dolby Vision RPU from unescaped byte buffer. + * Adds an error if the parsing fails. + */ +DoviRpuOpaque *dovi_parse_rpu(const uint8_t *buf, size_t len); + +/** + * # Safety + * The pointer to the data must be valid. + * + * Parse a Dolby Vision from a AV1 ITU-T T.35 metadata OBU byte buffer. + * Adds an error if the parsing fails. + */ +DoviRpuOpaque *dovi_parse_itu_t35_dovi_metadata_obu(const uint8_t *buf, size_t len); + +/** + * # Safety + * The pointer to the data must be valid. + * + * Parse a Dolby Vision from a (possibly) escaped HEVC UNSPEC 62 NAL unit byte buffer. + * Adds an error if the parsing fails. + */ +DoviRpuOpaque *dovi_parse_unspec62_nalu(const uint8_t *buf, size_t len); + +/** + * # Safety + * The pointer to the opaque struct must be valid. + * Avoid using on opaque pointers obtained through `dovi_parse_rpu_bin_file`. + * + * Free the RpuOpaque + */ +void dovi_rpu_free(DoviRpuOpaque *ptr); + +/** + * # Safety + * The pointer to the opaque struct must be valid. + * + * Get the last logged error for the RpuOpaque operations. + * + * On invalid parsing, an error is added. + * The user should manually verify if there is an error, as the parsing does not return an error code. + */ +const char *dovi_rpu_get_error(const DoviRpuOpaque *ptr); + +/** + * # Safety + * The data pointer should exist, and be allocated by Rust. + * + * Free a Data buffer + */ +void dovi_data_free(const DoviData *data); + +/** + * # Safety + * The struct pointer must be valid. + * + * Writes the encoded RPU as a byte buffer. + * If an error occurs in the writing, it is logged to RpuOpaque.error + */ +const DoviData *dovi_write_rpu(DoviRpuOpaque *ptr); + +/** + * # Safety + * The struct pointer must be valid. + * + * Writes the encoded RPU, escapes the bytes for HEVC and prepends the buffer with 0x7C01. + * If an error occurs in the writing, it is logged to RpuOpaque.error + */ +const DoviData *dovi_write_unspec62_nalu(DoviRpuOpaque *ptr); + +/** + * # Safety + * The struct pointer must be valid. + * The mode must be between 0 and 4. + * + * Converts the RPU to be compatible with a different Dolby Vision profile. + * Possible modes: + * - 0: Don't modify the RPU + * - 1: Converts the RPU to be MEL compatible + * - 2: Converts the RPU to be profile 8.1 compatible. Both luma and chroma mapping curves are set to no-op. + * This mode handles source profiles 5, 7 and 8. + * - 3: Converts to static profile 8.4 + * - 4: Converts to profile 8.1 preserving luma and chroma mapping. Old mode 2 behaviour. + * + * If an error occurs, it is logged to RpuOpaque.error. + * Returns 0 if successful, -1 otherwise. + */ +int32_t dovi_convert_rpu_with_mode(DoviRpuOpaque *ptr, + uint8_t mode); + +/** + * # Safety + * The pointer to the opaque struct must be valid. + * + * Get the DoVi RPU header struct. + */ +const DoviRpuDataHeader *dovi_rpu_get_header(const DoviRpuOpaque *ptr); + +/** + * # Safety + * The pointer to the struct must be valid. + * + * Frees the memory used by the RPU header. + */ +void dovi_rpu_free_header(const DoviRpuDataHeader *ptr); + +/** + * # Safety + * The pointer to the opaque struct must be valid. + * + * Get the DoVi RpuDataMapping struct. + */ +const DoviRpuDataMapping *dovi_rpu_get_data_mapping(const DoviRpuOpaque *ptr); + +/** + * # Safety + * The pointer to the struct must be valid. + * + * Frees the memory used by the RpuDataMapping. + */ +void dovi_rpu_free_data_mapping(const DoviRpuDataMapping *ptr); + +/** + * # Safety + * The pointer to the opaque struct must be valid. + * + * Get the DoVi VdrDmData struct. + */ +const DoviVdrDmData *dovi_rpu_get_vdr_dm_data(const DoviRpuOpaque *ptr); + +/** + * # Safety + * The pointer to the struct must be valid. + * + * Frees the memory used by the VdrDmData struct. + */ +void dovi_rpu_free_vdr_dm_data(const DoviVdrDmData *ptr); + +/** + * # Safety + * The pointer to the file path must be valid. + * + * Parses an existing RPU binary file. + * + * Returns the heap allocated `DoviRpuList` as a pointer. + * The returned pointer may be null, or the list could be empty if an error occurred. + */ +const DoviRpuOpaqueList *dovi_parse_rpu_bin_file(const char *path); + +/** + * # Safety + * The pointer to the struct must be valid. + * + * Frees the memory used by the DoviRpuOpaqueList struct. + */ +void dovi_rpu_list_free(const DoviRpuOpaqueList *ptr); + +/** + * # Safety + * The struct pointer must be valid. + * + * Sets the L5 metadata active area offsets. + * If there is no L5 block present, it is created with the offsets. + */ +int32_t dovi_rpu_set_active_area_offsets(DoviRpuOpaque *ptr, + uint16_t left, + uint16_t right, + uint16_t top, + uint16_t bottom); + +/** + * # Safety + * The struct pointer must be valid. + * + * Converts the existing reshaping/mapping to become no-op. + */ +int32_t dovi_rpu_remove_mapping(DoviRpuOpaque *ptr); + +/** + * # Safety + * The struct pointer must be valid. + * + * Writes the encoded RPU as `itu_t_t35_payload_bytes` for AV1 ITU-T T.35 metadata OBU + * If an error occurs in the writing, it is logged to RpuOpaque.error + */ +const DoviData *dovi_write_av1_rpu_metadata_obu_t35_payload(DoviRpuOpaque *ptr); + +/** + * # Safety + * The struct pointer must be valid. + * + * Writes the encoded RPU a complete AV1 `metadata_itut_t35()` OBU + * If an error occurs in the writing, it is logged to RpuOpaque.error + */ +const DoviData *dovi_write_av1_rpu_metadata_obu_t35_complete(DoviRpuOpaque *ptr); + +#ifdef __cplusplus +} // extern "C" +#endif // __cplusplus + +#endif /* DOVI_H */ diff --git a/third_party/exo-dv5-native/include/libplacebo/cache.h b/third_party/exo-dv5-native/include/libplacebo/cache.h new file mode 100644 index 0000000000..9dd72d3fad --- /dev/null +++ b/third_party/exo-dv5-native/include/libplacebo/cache.h @@ -0,0 +1,228 @@ +/* + * This file is part of libplacebo. + * + * libplacebo is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libplacebo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with libplacebo. If not, see . + */ + +#ifndef LIBPLACEBO_CACHE_H_ +#define LIBPLACEBO_CACHE_H_ + +#include +#include +#include + +#include +#include +#include + +PL_API_BEGIN + +typedef struct pl_cache_obj { + // Cache object key. This will uniquely identify this cached object. + uint64_t key; + + // Cache data pointer and length. 0-length cached objects are invalid + // and will be silently dropped. You can explicitly remove a cached + // object by overwriting it with a length 0 object. + void *data; + size_t size; + + // Free callback, to free memory associated with `data`. (Optional) + // Will be called when the object is either explicitly deleted, culled + // due to hitting size limits, or on pl_cache_destroy(). + void (*free)(void *data); +} pl_cache_obj; + +struct pl_cache_params { + // Optional `pl_log` that is used for logging internal events related + // to the cache, such as insertions, saving and loading. + pl_log log; + + // Size limits. If 0, no limit is imposed. + // + // Note: libplacebo will never detect or invalidate stale cache entries, so + // setting an upper size limit is strongly recommended + size_t max_object_size; + size_t max_total_size; + + // Optional external callback to call after a cached object is modified + // (including deletion and (re-)insertion). Note that this is not called on + // objects which are merely pruned from the cache due to `max_total_size`, + // so users must rely on some external mechanism to prune stale entries or + // enforce size limits. + // + // Note: `pl_cache_load` does not trigger this callback. + // Note: Ownership of `obj` does *not* pass to the caller. + // Note: This function must be thread safe. + void (*set)(void *priv, pl_cache_obj obj); + + // Optional external callback to call on a cache miss. Ownership of the + // returned object passes to the `pl_cache`. Objects returned by this + // callback *should* have a valid `free` callback, unless lifetime can be + // externally managed and guaranteed to outlive the `pl_cache`. + // + // Note: This function must be thread safe. + pl_cache_obj (*get)(void *priv, uint64_t key); + + // External context for get/set. + void *priv; +}; + +#define pl_cache_params(...) (&(struct pl_cache_params) { __VA_ARGS__ }) +PL_API extern const struct pl_cache_params pl_cache_default_params; + +// Thread-safety: Safe +// +// Note: In any context in which `pl_cache` is used, users may also pass NULL +// to disable caching. In other words, NULL is a valid `pl_cache`. +typedef const struct pl_cache_t { + struct pl_cache_params params; +} *pl_cache; + +// Create a new cache. This function will never fail. +PL_API pl_cache pl_cache_create(const struct pl_cache_params *params); + +// Destroy a `pl_cache` object, including all underlying objects. +PL_API void pl_cache_destroy(pl_cache *cache); + +// Explicitly clear all objects in the cache without destroying it. This is +// similar to `pl_cache_destroy`, but the cache remains valid afterwards. +// +// Note: Objects destroyed in this way *not* propagated to the `set` callback. +PL_API void pl_cache_reset(pl_cache cache); + +// Return the current internal number of objects and total size (bytes) +PL_API int pl_cache_objects(pl_cache cache); +PL_API size_t pl_cache_size(pl_cache cache); + +// Return a lightweight, order-independent hash of all objects currently stored +// in the `pl_cache`. Can be used to avoid re-saving unmodified caches. +PL_API uint64_t pl_cache_signature(pl_cache cache); + +// --- Cache saving and loading APIs + +// Serialize the internal state of a `pl_cache` into an abstract cache +// object that can be e.g. saved to disk and loaded again later. Returns the +// number of objects saved. +// +// Note: Using `save/load` is largely redundant with using `insert/lookup` +// callbacks, and the user should decide whether to use the explicit API or the +// callback-based API. +PL_API int pl_cache_save_ex(pl_cache cache, + void (*write)(void *priv, size_t size, const void *ptr), + void *priv); + +// Load the result of a previous `pl_cache_save` call. Any duplicate entries in +// the `pl_cache` will be overwritten. Returns the number of objects loaded, or +// a negative number on serious error (e.g. corrupt header) +// +// Note: This does not trigger the `update` callback. +PL_API int pl_cache_load_ex(pl_cache cache, + bool (*read)(void *priv, size_t size, void *ptr), + void *priv); + +// --- Convenience wrappers around pl_cache_save/load_ex + +// Writes data directly to a pointer. Returns the number of bytes that *would* +// have been written, so this can be used on a size 0 buffer to get the required +// total size. +PL_API size_t pl_cache_save(pl_cache cache, uint8_t *data, size_t size); + +// Reads data directly from a pointer. This still reads from `data`, so it does +// not avoid a copy. +PL_API int pl_cache_load(pl_cache cache, const uint8_t *data, size_t size); + +// Writes/loads data to/from a FILE stream at the current position. +#define pl_cache_save_file(c, file) pl_cache_save_ex(c, pl_write_file_cb, file) +#define pl_cache_load_file(c, file) pl_cache_load_ex(c, pl_read_file_cb, file) + +static inline void pl_write_file_cb(void *priv, size_t size, const void *ptr) +{ + (void) fwrite(ptr, 1, size, (FILE *) priv); +} + +static inline bool pl_read_file_cb(void *priv, size_t size, void *ptr) +{ + return fread(ptr, 1, size, (FILE *) priv) == size; +} + +// --- Standard callbacks for caching to a files inside a directory. + +// Write the cache object to a file. The filename is generated by combining +// `path` with a 16-digit lowercase hex string for the ID. Note that if +// `path` does not end with a directory separator, the filename will be +// effectively prefixed by the last path component. All directories must +// already exist. +// +// If `obj` has size 0, the file will instead be removed. +// +// Note: The files written by this callback use the same internal format as +// `pl_cache_save_file`, and could thus also be loaded directly using +// `pl_cache_load`. +PL_API void pl_cache_set_file(void *path, pl_cache_obj obj); + +// Retrieve a cache object from a file inside `dir`. See `pl_cache_set_dir`. +// +// If the cached file is missing, truncated or otherwise corrupt, it is +// instead removed (if needed) and {0} is returned. +PL_API pl_cache_obj pl_cache_get_file(void *path, uint64_t key); + +#define pl_cache_set_dir pl_cache_set_file +#define pl_cache_get_dir pl_cache_get_file + +// --- Object modification API. Mostly intended for internal use. + +// Insert a new cached object into a `pl_cache`. Returns whether successful. +// Overwrites any existing cached object with that signature, so this can be +// used to e.g. delete objects as well (set their size to 0). On success, +// ownership of `obj` passes to the `pl_cache`. +// +// Note: If `object.free` is NULL, this will perform an internal memdup. To +// bypass this (e.g. when directly adding externally managed memory), you can +// set the `free` callback to an explicit noop function. +// +// Note: `obj->data/free` will be reset to NULL on successful insertion. +PL_API bool pl_cache_try_set(pl_cache cache, pl_cache_obj *obj); + +// Variant of `pl_cache_try_set` that simply frees `obj` on failure. +PL_API void pl_cache_set(pl_cache cache, pl_cache_obj *obj); + +// Looks up `obj->key` in the object cache. If successful, `obj->data` is +// set to memory owned by the caller, which must be either explicitly +// re-inserted, or explicitly freed (using obj->free). +// +// Note: On failure, `obj->data/size/free` are reset to NULL. +PL_API bool pl_cache_get(pl_cache cache, pl_cache_obj *obj); + +// Run a callback on every object currently stored in `cache`. +// +// Note: Running any `pl_cache_*` function on `cache` from this callback is +// undefined behavior. +PL_API void pl_cache_iterate(pl_cache cache, + void (*cb)(void *priv, pl_cache_obj obj), + void *priv); + +// Utility wrapper to free a `pl_cache_obj` if necessary (and sanitize it) +static inline void pl_cache_obj_free(pl_cache_obj *obj) +{ + if (obj->free) + obj->free(obj->data); + obj->data = NULL; + obj->free = NULL; + obj->size = 0; +} + +PL_API_END + +#endif // LIBPLACEBO_CACHE_H_ diff --git a/third_party/exo-dv5-native/include/libplacebo/colorspace.h b/third_party/exo-dv5-native/include/libplacebo/colorspace.h new file mode 100644 index 0000000000..64c925e985 --- /dev/null +++ b/third_party/exo-dv5-native/include/libplacebo/colorspace.h @@ -0,0 +1,780 @@ +/* + * This file is part of libplacebo. + * + * libplacebo is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libplacebo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with libplacebo. If not, see . + */ + +#ifndef LIBPLACEBO_COLORSPACE_H_ +#define LIBPLACEBO_COLORSPACE_H_ + +#include +#include +#include + +#include + +PL_API_BEGIN + +// The underlying color representation (e.g. RGB, XYZ or YCbCr) +enum pl_color_system { + PL_COLOR_SYSTEM_UNKNOWN = 0, + // YCbCr-like color systems: + PL_COLOR_SYSTEM_BT_601, // ITU-R Rec. BT.601 (SD) + PL_COLOR_SYSTEM_BT_709, // ITU-R Rec. BT.709 (HD) + PL_COLOR_SYSTEM_SMPTE_240M, // SMPTE-240M + PL_COLOR_SYSTEM_BT_2020_NC, // ITU-R Rec. BT.2020 (non-constant luminance) + PL_COLOR_SYSTEM_BT_2020_C, // ITU-R Rec. BT.2020 (constant luminance) + PL_COLOR_SYSTEM_BT_2100_PQ, // ITU-R Rec. BT.2100 ICtCp PQ variant + PL_COLOR_SYSTEM_BT_2100_HLG, // ITU-R Rec. BT.2100 ICtCp HLG variant + PL_COLOR_SYSTEM_DOLBYVISION, // Dolby Vision (see pl_dovi_metadata) + PL_COLOR_SYSTEM_YCGCO, // YCgCo (derived from RGB) + PL_COLOR_SYSTEM_YCGCO_RE, // YCgCo-R, even addition of bits + PL_COLOR_SYSTEM_YCGCO_RO, // YCgCo-R, odd addition of bits + // Other color systems: + PL_COLOR_SYSTEM_RGB, // Red, Green and Blue + PL_COLOR_SYSTEM_XYZ, // Digital Cinema Distribution Master (XYZ) + PL_COLOR_SYSTEM_COUNT +}; + +PL_API bool pl_color_system_is_ycbcr_like(enum pl_color_system sys); + +// Returns the human-readable, friendly name of the color system. +PL_API const char *pl_color_system_name(enum pl_color_system sys); +PL_API extern const char *const pl_color_system_names[PL_COLOR_SYSTEM_COUNT]; + +// Returns true for color systems that are linear transformations of the RGB +// equivalent, i.e. are simple matrix multiplications. For color systems with +// this property, `pl_color_repr_decode` is sufficient for conversion to RGB. +PL_API bool pl_color_system_is_linear(enum pl_color_system sys); + +// Guesses the best YCbCr-like colorspace based on a image given resolution. +// This only picks conservative values. (In particular, BT.2020 is never +// auto-guessed, even for 4K resolution content) +PL_API enum pl_color_system pl_color_system_guess_ycbcr(int width, int height); + +// Friendly names for the canonical channel names and order. +enum pl_channel { + PL_CHANNEL_NONE = -1, + PL_CHANNEL_A = 3, // alpha + // RGB system + PL_CHANNEL_R = 0, + PL_CHANNEL_G = 1, + PL_CHANNEL_B = 2, + // YCbCr-like systems + PL_CHANNEL_Y = 0, + PL_CHANNEL_CB = 1, + PL_CHANNEL_CR = 2, + // Aliases for Cb/Cr + PL_CHANNEL_U = 1, + PL_CHANNEL_V = 2 + // There are deliberately no names for the XYZ system to avoid + // confusion due to PL_CHANNEL_Y. +}; + +// The numerical range of the representation (where applicable). +enum pl_color_levels { + PL_COLOR_LEVELS_UNKNOWN = 0, + PL_COLOR_LEVELS_LIMITED, // Limited/TV range, e.g. 16-235 + PL_COLOR_LEVELS_FULL, // Full/PC range, e.g. 0-255 + PL_COLOR_LEVELS_COUNT, + + // Compatibility aliases + PL_COLOR_LEVELS_TV = PL_COLOR_LEVELS_LIMITED, + PL_COLOR_LEVELS_PC = PL_COLOR_LEVELS_FULL, +}; + +// The alpha representation mode. +enum pl_alpha_mode { + PL_ALPHA_UNKNOWN = 0, + PL_ALPHA_INDEPENDENT, // alpha channel is separate from the video + PL_ALPHA_PREMULTIPLIED, // alpha channel is multiplied into the colors + PL_ALPHA_NONE, // alpha channel explicitly ignored (or absent) + PL_ALPHA_MODE_COUNT, +}; + +// The underlying bit-wise representation of a color sample. For example, +// a 10-bit TV-range YCbCr value uploaded to a 16 bit texture would have +// sample_depth=16 color_depth=10 bit_shift=0. +// +// For another example, a 12-bit XYZ full range sample shifted to 16-bits with +// the lower 4 bits all set to 0 would have sample_depth=16 color_depth=12 +// bit_shift=4. (libavcodec likes outputting this type of `xyz12`) +// +// To explain the meaning of `sample_depth` further; the consideration factor +// here is the fact that GPU sampling will normalized the sampled color to the +// range 0.0 - 1.0 in a manner dependent on the number of bits in the texture +// format. So if you upload a 10-bit YCbCr value unpadded as 16-bit color +// samples, all of the sampled values will be extremely close to 0.0. In such a +// case, `pl_color_repr_normalize` would return a high scaling factor, which +// would pull the color up to their 16-bit range. +struct pl_bit_encoding { + int sample_depth; // the number of bits the color is stored/sampled as + int color_depth; // the effective number of bits of the color information + int bit_shift; // a representational bit shift applied to the color +}; + +// Returns whether two bit encodings are exactly identical. +PL_API bool pl_bit_encoding_equal(const struct pl_bit_encoding *b1, + const struct pl_bit_encoding *b2); + +// Parsed metadata from the Dolby Vision RPU +struct pl_dovi_metadata { + // Colorspace transformation metadata + float nonlinear_offset[3]; // input offset ("ycc_to_rgb_offset") + pl_matrix3x3 nonlinear; // before PQ, also called "ycc_to_rgb" + pl_matrix3x3 linear; // after PQ, also called "rgb_to_lms" + + // Reshape data, grouped by component + struct pl_reshape_data { + uint8_t num_pivots; + float pivots[9]; // normalized to [0.0, 1.0] based on BL bit depth + uint8_t method[8]; // 0 = polynomial, 1 = MMR + // Note: these must be normalized (divide by coefficient_log2_denom) + float poly_coeffs[8][3]; // x^0, x^1, x^2, unused must be 0 + uint8_t mmr_order[8]; // 1, 2 or 3 + float mmr_constant[8]; + float mmr_coeffs[8][3 /* order */][7]; + } comp[3]; + + // Non-linear inverse quantization (NLQ) parameters for FEL composition. + // Used only when an enhancement layer is used. Ignored for MEL and non-FEL + // profile 7 streams. When `nlq_active` is false the rest of these fields are + // unused and only BL-only reshape is performed. + // + // LINEAR_DZ dequantization: + // residual = sign(el_centered) * + // (|el_centered| * deadzone_slope + deadzone_threshold) + // The (2^eld - 1) factor is pre-folded into `deadzone_slope` and the + // -0.5*S half-pixel correction (from the spec's (2|rr|-1) rounding) is + // absorbed into `deadzone_threshold`. + bool nlq_active; + struct pl_dovi_nlq_data { + float offset; // normalized to [0.0, 1.0] based on EL bit depth + float deadzone_slope; // (2^el_bit_depth - 1) * S / 2^coef_log2_denom + float deadzone_threshold; // (T - S/2) / 2^coef_log2_denom + } nlq[3]; +}; + +// Struct describing the underlying color system and representation. This +// information is needed to convert an encoded color to a normalized RGB triple +// in the range 0-1. +struct pl_color_repr { + enum pl_color_system sys; + enum pl_color_levels levels; + enum pl_alpha_mode alpha; + struct pl_bit_encoding bits; // or {0} if unknown + + // Metadata for PL_COLOR_SYSTEM_DOLBYVISION. Note that, for the sake of + // efficiency, this is treated purely as an opaque reference - functions + // like pl_color_repr_equal will merely do a pointer equality test. + // + // The only functions that actually dereference it in any way are + // pl_color_repr_decode, pl_shader_decode_color and pl_render_image(_mix). + const struct pl_dovi_metadata *dovi; +}; + +// Some common color representations. It's worth pointing out that all of these +// presets leave `alpha` and `bits` as unknown - that is, only the system and +// levels are predefined +PL_API extern const struct pl_color_repr pl_color_repr_unknown; +PL_API extern const struct pl_color_repr pl_color_repr_rgb; +PL_API extern const struct pl_color_repr pl_color_repr_sdtv; +PL_API extern const struct pl_color_repr pl_color_repr_hdtv; // also Blu-ray +PL_API extern const struct pl_color_repr pl_color_repr_uhdtv; // SDR, NCL system +PL_API extern const struct pl_color_repr pl_color_repr_jpeg; + +// Returns whether two colorspace representations are exactly identical. +PL_API bool pl_color_repr_equal(const struct pl_color_repr *c1, + const struct pl_color_repr *c2); + +// Replaces unknown values in the first struct by those of the second struct. +PL_API void pl_color_repr_merge(struct pl_color_repr *orig, + const struct pl_color_repr *update); + +// This function normalizes the color representation such that +// color_depth=sample_depth and bit_shift=0; and returns the scaling factor +// that must be multiplied into the color value to accomplish this, assuming +// it has already been sampled by the GPU. If unknown, the color and sample +// depth will both be inferred as 8 bits for the purposes of this conversion. +PL_API float pl_color_repr_normalize(struct pl_color_repr *repr); + +// Guesses the best color levels based on the specified color levels and +// falling back to using the color system instead. YCbCr-like systems are +// assumed to be TV range, otherwise this defaults to PC range. +PL_API enum pl_color_levels pl_color_levels_guess(const struct pl_color_repr *repr); + +// The colorspace's primaries (gamut) +enum pl_color_primaries { + PL_COLOR_PRIM_UNKNOWN = 0, + // Standard gamut: + PL_COLOR_PRIM_BT_601_525, // ITU-R Rec. BT.601 (525-line = NTSC, SMPTE-C) + PL_COLOR_PRIM_BT_601_625, // ITU-R Rec. BT.601 (625-line = PAL, SECAM) + PL_COLOR_PRIM_BT_709, // ITU-R Rec. BT.709 (HD), also sRGB + PL_COLOR_PRIM_BT_470M, // ITU-R Rec. BT.470 M + PL_COLOR_PRIM_EBU_3213, // EBU Tech. 3213-E / JEDEC P22 phosphors + // Wide gamut: + PL_COLOR_PRIM_BT_2020, // ITU-R Rec. BT.2020 (UltraHD) + PL_COLOR_PRIM_APPLE, // Apple RGB + PL_COLOR_PRIM_ADOBE, // Adobe RGB (1998) + PL_COLOR_PRIM_PRO_PHOTO, // ProPhoto RGB (ROMM) + PL_COLOR_PRIM_CIE_1931, // CIE 1931 RGB primaries + PL_COLOR_PRIM_DCI_P3, // DCI-P3 (Digital Cinema) + PL_COLOR_PRIM_DISPLAY_P3, // DCI-P3 (Digital Cinema) with D65 white point + PL_COLOR_PRIM_V_GAMUT, // Panasonic V-Gamut (VARICAM) + PL_COLOR_PRIM_S_GAMUT, // Sony S-Gamut + PL_COLOR_PRIM_FILM_C, // Traditional film primaries with Illuminant C + PL_COLOR_PRIM_ACES_AP0, // ACES Primaries #0 (ultra wide) + PL_COLOR_PRIM_ACES_AP1, // ACES Primaries #1 + PL_COLOR_PRIM_COUNT +}; + +PL_API bool pl_color_primaries_is_wide_gamut(enum pl_color_primaries prim); + +// Returns the human-readable, friendly name of the color primaries. +PL_API const char *pl_color_primaries_name(enum pl_color_primaries prim); +PL_API extern const char *const pl_color_primaries_names[PL_COLOR_PRIM_COUNT]; + +// Guesses the best primaries based on a resolution. This always guesses +// conservatively, i.e. it will never return a wide gamut color space even if +// the resolution is 4K. +PL_API enum pl_color_primaries pl_color_primaries_guess(int width, int height); + +// The colorspace's transfer function (gamma / EOTF) +enum pl_color_transfer { + PL_COLOR_TRC_UNKNOWN = 0, + // Standard dynamic range: + PL_COLOR_TRC_BT_1886, // ITU-R Rec. BT.1886 (CRT emulation + OOTF) + PL_COLOR_TRC_SRGB, // IEC 61966-2-4 sRGB (CRT emulation) + PL_COLOR_TRC_LINEAR, // Linear light content + PL_COLOR_TRC_GAMMA18, // Pure power gamma 1.8 + PL_COLOR_TRC_GAMMA20, // Pure power gamma 2.0 + PL_COLOR_TRC_GAMMA22, // Pure power gamma 2.2 + PL_COLOR_TRC_GAMMA24, // Pure power gamma 2.4 + PL_COLOR_TRC_GAMMA26, // Pure power gamma 2.6 + PL_COLOR_TRC_GAMMA28, // Pure power gamma 2.8 + PL_COLOR_TRC_PRO_PHOTO, // ProPhoto RGB (ROMM) + PL_COLOR_TRC_ST428, // Digital Cinema Distribution Master (XYZ) + // High dynamic range: + PL_COLOR_TRC_PQ, // ITU-R BT.2100 PQ (perceptual quantizer), aka SMPTE ST2048 + PL_COLOR_TRC_HLG, // ITU-R BT.2100 HLG (hybrid log-gamma), aka ARIB STD-B67 + PL_COLOR_TRC_V_LOG, // Panasonic V-Log (VARICAM) + PL_COLOR_TRC_S_LOG1, // Sony S-Log1 + PL_COLOR_TRC_S_LOG2, // Sony S-Log2 + PL_COLOR_TRC_SCRGB, // IEC 61966-2-2 scRGB (extended linear BT.709) + PL_COLOR_TRC_COUNT +}; + +// Returns the human-readable, friendly name of the color transfer. +PL_API const char *pl_color_transfer_name(enum pl_color_transfer trc); +PL_API extern const char *const pl_color_transfer_names[PL_COLOR_TRC_COUNT]; + +// Returns the nominal peak of a given transfer function, relative to the +// reference white. This refers to the highest encodable signal level. +// Always equal to 1.0 for SDR curves. +// +// Note: For HLG in particular, which is scene-referred, this returns the +// highest nominal peak in scene-referred space (3.77), which may be different +// from the actual peak in display space after application of the HLG OOTF. +PL_API float pl_color_transfer_nominal_peak(enum pl_color_transfer trc); + +static inline bool pl_color_transfer_is_hdr(enum pl_color_transfer trc) +{ + return pl_color_transfer_nominal_peak(trc) > 1.0; +} + +// This defines the display-space standard reference white level (in cd/m^2) +// that is assumed for SDR content, for use when mapping between HDR and SDR in +// display space. See ITU-R Report BT.2408 for more information. +#define PL_COLOR_SDR_WHITE 203.0f + +// This defines the reference white level for scRGB (IEC 61966-2-2), in cd/m^2. +// In scRGB, a linear signal value of 1.0 corresponds to exactly 80 cd/m^2. +// Signal values above 1.0 represent HDR luminance; values below 0.0 represent +// out-of-gamut colors. This constant is used to convert between libplacebo's +// internal NORM scale (1.0 = PL_COLOR_SDR_WHITE) and scRGB output values. +#define PL_COLOR_SCRGB_WHITE 80.0f + +// This defines the assumed contrast level of an unknown SDR display. This +// will be used to determine the black point in the absence of any tagged +// minimum luminance, relative to the tagged maximum luminance (or +// PL_COLOR_SDR_WHITE in the absence of all tagging) +#define PL_COLOR_SDR_CONTRAST 1000.0f + +// This defines the default black point assumed for "infinite contrast" HDR +// displays. This is not exactly 0.0 because a value of 0.0 is interpreted +// as "unknown / missing metadata" inside struct pl_hdr_metadata, and also +// to avoid numerical issues in a variety of tone mapping functions. +// Essentially, a black level below this number is functionally meaningless +// inside libplacebo, and will be clamped to this value regardless. +// +// The value used here (1e-6) is about one 13-bit PQ step above absolute zero, +// which is a small fraction of the human JND at this brightness level, and also +// about 3 bits above the floating point machine epsilon. +#define PL_COLOR_HDR_BLACK 1e-6f + +// This defines the assumed peak brightness of a HLG display with no HDR10 +// metadata. This is set to the brightness of a "nominal" HLG reference display. +#define PL_COLOR_HLG_PEAK 1000.0f + +// Represents a single CIE xy coordinate (e.g. CIE Yxy with Y = 1.0) +struct pl_cie_xy { + float x, y; +}; + +// Creates a pl_cie_xyz from raw XYZ values +static inline struct pl_cie_xy pl_cie_from_XYZ(float X, float Y, float Z) +{ + float k = 1.0f / (X + Y + Z); + struct pl_cie_xy xy = { k * X, k * Y }; + return xy; +} + +// Recovers (X / Y) from a CIE xy value. +static inline float pl_cie_X(struct pl_cie_xy xy) +{ + return xy.x / xy.y; +} + +// Recovers (Z / Y) from a CIE xy value. +static inline float pl_cie_Z(struct pl_cie_xy xy) +{ + return (1 - xy.x - xy.y) / xy.y; +} + +static inline bool pl_cie_xy_equal(const struct pl_cie_xy *a, + const struct pl_cie_xy *b) +{ + return a->x == b->x && a->y == b->y; +} + +// Computes the CIE xy chromaticity coordinates of a CIE D-series illuminant +// with the given correlated color temperature. +// +// `temperature` must be between 2500 K and 25000 K, inclusive. +PL_API struct pl_cie_xy pl_daylight_from_temp(float temperature); + +// Computes the CIE xy chromaticity coordinates of a blackbody radiator. This +// will always return points roughly on the Planckian locus. +// +// `temperature` must be between 1667 K and 25000 K, inclusive. +PL_API struct pl_cie_xy pl_blackbody_from_temp(float temperature); + +// Computes a blend of the daylight and blackbody temperatures, to allow +// supporting a larger value range. This returns the daylight illuminant +// above 4000K, but transitions to a blackbody below that. +// +// `temperature` must be between 1667 K and 25000 K, inclusive. +PL_API struct pl_cie_xy pl_white_from_temp(float temperature); + +// Represents the raw physical primaries corresponding to a color space. +struct pl_raw_primaries { + struct pl_cie_xy red, green, blue, white; +}; + +// Returns whether two raw primaries are exactly identical. +PL_API bool pl_raw_primaries_equal(const struct pl_raw_primaries *a, + const struct pl_raw_primaries *b); + +// Returns whether two raw primaries are approximately equal +PL_API bool pl_raw_primaries_similar(const struct pl_raw_primaries *a, + const struct pl_raw_primaries *b); + +// Replaces unknown values in the first struct by those of the second struct. +PL_API void pl_raw_primaries_merge(struct pl_raw_primaries *orig, + const struct pl_raw_primaries *update); + +// Returns the raw primaries for a given color space. +PL_API const struct pl_raw_primaries *pl_raw_primaries_get(enum pl_color_primaries prim); + +enum pl_hdr_scaling { + PL_HDR_NORM = 0, // 0.0 is absolute black, 1.0 is PL_COLOR_SDR_WHITE + PL_HDR_SQRT, // sqrt() of PL_HDR_NORM values + PL_HDR_NITS, // absolute brightness in raw cd/m² + PL_HDR_PQ, // absolute brightness in PQ (0.0 to 1.0) + PL_HDR_SCALING_COUNT, +}; + +// Generic helper for performing HDR scale conversions. +PL_API float pl_hdr_rescale(enum pl_hdr_scaling from, enum pl_hdr_scaling to, float x); + +enum pl_hdr_metadata_type { + PL_HDR_METADATA_ANY = 0, + PL_HDR_METADATA_NONE, + PL_HDR_METADATA_HDR10, // HDR10 static mastering display metadata + PL_HDR_METADATA_HDR10PLUS, // HDR10+ dynamic metadata + PL_HDR_METADATA_CIE_Y, // CIE Y derived dynamic luminance metadata + PL_HDR_METADATA_TYPE_COUNT, +}; + +// Bezier curve for HDR metadata +struct pl_hdr_bezier { + float target_luma; // target luminance (cd/m²) for this OOTF + float knee_x, knee_y; // cross-over knee point (0-1) + float anchors[15]; // intermediate bezier curve control points (0-1) + uint8_t num_anchors; +}; + +// Represents raw HDR metadata as defined by SMPTE 2086 / CTA 861.3, which is +// often attached to HDR sources and can be forwarded to HDR-capable displays, +// or used to guide the libplacebo built-in tone mapping. Values left as 0 +// are treated as unknown by libplacebo. +// +// Note: This means that a value of `min_luma == 0.0` gets treated as "minimum +// luminance not known", which in practice may end up inferring a default +// contrast of 1000:1 for SDR transfer functions. To avoid this, the user should +// set these fields to a low positive value, e.g. PL_COLOR_HDR_BLACK, to signal +// a "zero" black point (i.e. infinite contrast display). +struct pl_hdr_metadata { + // --- PL_HDR_METADATA_HDR10 + // Mastering display metadata. + struct pl_raw_primaries prim; // mastering display primaries + float min_luma, max_luma; // min/max luminance (in cd/m²) + + // Content light level. `max_cll` is used as a fallback when mastering + // display max luminance metadata is unavailable. + float max_cll; // max content light level (in cd/m²) + float max_fall; // max frame average light level (in cd/m²) + + // --- PL_HDR_METADATA_HDR10PLUS + float scene_max[3]; // maxSCL in cd/m² per component (RGB) + float scene_avg; // average of maxRGB in cd/m² + struct pl_hdr_bezier ootf; // reference OOTF (optional) + + // --- PL_HDR_METADATA_CIE_Y + float max_pq_y; // maximum PQ luminance (in PQ, 0-1) + float avg_pq_y; // averaged PQ luminance (in PQ, 0-1) +}; + +PL_API extern const struct pl_hdr_metadata pl_hdr_metadata_empty; // equal to {0} +PL_API extern const struct pl_hdr_metadata pl_hdr_metadata_hdr10; // generic HDR10 display + +// Returns whether two sets of HDR metadata are exactly identical. +PL_API bool pl_hdr_metadata_equal(const struct pl_hdr_metadata *a, + const struct pl_hdr_metadata *b); + +// Replaces unknown values in the first struct by those of the second struct. +PL_API void pl_hdr_metadata_merge(struct pl_hdr_metadata *orig, + const struct pl_hdr_metadata *update); + +// Returns `true` if `data` contains a complete set of a given metadata type. +// Note: for PL_HDR_METADATA_HDR10, only `min_luma` and `max_luma` are +// considered - CLL/FALL and primaries are irrelevant for HDR tone-mapping. +PL_API bool pl_hdr_metadata_contains(const struct pl_hdr_metadata *data, + enum pl_hdr_metadata_type type); + +// Rendering intent for colorspace transformations. These constants match the +// ICC specification (Table 23) +enum pl_rendering_intent { + PL_INTENT_AUTO = -1, // not a valid ICC intent, but used to auto-infer + PL_INTENT_PERCEPTUAL = 0, + PL_INTENT_RELATIVE_COLORIMETRIC = 1, + PL_INTENT_SATURATION = 2, + PL_INTENT_ABSOLUTE_COLORIMETRIC = 3 +}; + +// Struct describing a physical color space. This information is needed to +// turn a normalized RGB triple into its physical meaning, as well as to convert +// between color spaces. +struct pl_color_space { + enum pl_color_primaries primaries; + enum pl_color_transfer transfer; + + // HDR metadata for this color space, if present. (Optional) + struct pl_hdr_metadata hdr; +}; + +#define pl_color_space(...) (&(struct pl_color_space) { __VA_ARGS__ }) + +// Returns whether or not a color space is considered as effectively HDR. +// This is true when the effective signal peak is greater than the SDR +// reference white (1.0), taking into account `csp->hdr`. +PL_API bool pl_color_space_is_hdr(const struct pl_color_space *csp); + +// Returns whether or not a color space is "black scaled", in which case 0.0 is +// the true black point. This is true for SDR signals other than BT.1886, as +// well as for HLG. +PL_API bool pl_color_space_is_black_scaled(const struct pl_color_space *csp); + +// Linearize/delinearize input color, given a specified color space. In essence, +// this corresponds to the ITU-R EOTF and its inverse (not the OETF). +// The linear color will be scaled so that 1.0 is the diffuse white. The +// non-linear color will be scaled so that 1.0 is the maximum representable +// value. +// +// Note: This is a no-op if csp->transfer == PL_COLOR_TRC_LINEAR. +PL_API void pl_color_linearize(const struct pl_color_space *csp, float color[3]); +PL_API void pl_color_delinearize(const struct pl_color_space *csp, float color[3]); + +struct pl_nominal_luma_params { + // The color space to infer luminance from + const struct pl_color_space *color; + + // Which type of metadata to draw values from + enum pl_hdr_metadata_type metadata; + + // This field controls the scaling of `out_*` + enum pl_hdr_scaling scaling; + + // Fields to write the detected nominal luminance to. (Optional) + // + // For SDR displays, this will default to a contrast level of 1000:1 unless + // indicated otherwise in the `min/max_luma` static HDR10 metadata fields. + float *out_min; + float *out_max; + + // Field to write the detected average luminance to, or 0.0 in the absence + // of dynamic metadata. (Optional) + float *out_avg; +}; + +#define pl_nominal_luma_params(...) \ + (&(struct pl_nominal_luma_params) { __VA_ARGS__ }) + +// Returns the effective luminance described by a pl_color_space. +PL_API void pl_color_space_nominal_luma_ex(const struct pl_nominal_luma_params *params); + +// Replaces unknown values in the first struct by those of the second struct. +PL_API void pl_color_space_merge(struct pl_color_space *orig, + const struct pl_color_space *update); + +// Returns whether two colorspaces are exactly identical. +PL_API bool pl_color_space_equal(const struct pl_color_space *c1, + const struct pl_color_space *c2); + +// Go through a color-space and explicitly default all unknown fields to +// reasonable values. After this function is called, none of the values will be +// PL_COLOR_*_UNKNOWN or 0.0, except for the dynamic HDR metadata fields. +PL_API void pl_color_space_infer(struct pl_color_space *space); + +// Like `pl_color_space_infer`, but takes default values from the reference +// color space (excluding certain special cases like HDR or wide gamut). +PL_API void pl_color_space_infer_ref(struct pl_color_space *space, + const struct pl_color_space *ref); + +// Infer both the source and destination gamut simultaneously, and also adjust +// values for optimal display. This is mostly the same as +// `pl_color_space_infer(src)` followed by `pl_color_space_infer_ref`, but also +// takes into account the SDR contrast levels and PQ black points. This is +// basically the logic used by `pl_shader_color_map` and `pl_renderer` to +// decide the output color space in a conservative way and compute the final +// end-to-end color transformation that needs to be done. +PL_API void pl_color_space_infer_map(struct pl_color_space *src, + struct pl_color_space *dst); + +// Some common color spaces. Note: These don't necessarily have all fields +// filled, in particular `hdr` is left unset. +PL_API extern const struct pl_color_space pl_color_space_unknown; +PL_API extern const struct pl_color_space pl_color_space_srgb; +PL_API extern const struct pl_color_space pl_color_space_bt709; +PL_API extern const struct pl_color_space pl_color_space_hdr10; +PL_API extern const struct pl_color_space pl_color_space_bt2020_hlg; +PL_API extern const struct pl_color_space pl_color_space_monitor; // typical display + +// This represents metadata about extra operations to perform during colorspace +// conversion, which correspond to artistic adjustments of the color. +struct pl_color_adjustment { + // Brightness boost. 0.0 = neutral, 1.0 = solid white, -1.0 = solid black + float brightness; + // Contrast boost. 1.0 = neutral, 0.0 = solid black + float contrast; + // Saturation gain. 1.0 = neutral, 0.0 = grayscale + float saturation; + // Hue shift, corresponding to a rotation around the [U, V] subvector, in + // radians. 0.0 = neutral + float hue; + // Gamma adjustment. 1.0 = neutral, 0.0 = solid black + float gamma; + // Color temperature shift. 0.0 = 6500 K, -1.0 = 3000 K, 1.0 = 10000 K + float temperature; +}; + +#define PL_COLOR_ADJUSTMENT_NEUTRAL \ + .contrast = 1.0, \ + .saturation = 1.0, \ + .gamma = 1.0, + +#define pl_color_adjustment(...) (&(struct pl_color_adjustment) { PL_COLOR_ADJUSTMENT_NEUTRAL __VA_ARGS__ }) +PL_API extern const struct pl_color_adjustment pl_color_adjustment_neutral; + +// Represents the chroma placement with respect to the luma samples. This is +// only relevant for YCbCr-like colorspaces with chroma subsampling. +enum pl_chroma_location { + PL_CHROMA_UNKNOWN = 0, + PL_CHROMA_LEFT, // MPEG2/4, H.264 + PL_CHROMA_CENTER, // MPEG1, JPEG + PL_CHROMA_TOP_LEFT, + PL_CHROMA_TOP_CENTER, + PL_CHROMA_BOTTOM_LEFT, + PL_CHROMA_BOTTOM_CENTER, + PL_CHROMA_COUNT, +}; + +// Fills *x and *y with the offset in luma pixels corresponding to a given +// chroma location. +// +// Note: PL_CHROMA_UNKNOWN defaults to PL_CHROMA_LEFT +PL_API void pl_chroma_location_offset(enum pl_chroma_location loc, float *x, float *y); + +// Returns an RGB->XYZ conversion matrix for a given set of primaries. +// Multiplying this into the RGB color transforms it to CIE XYZ, centered +// around the color space's white point. +PL_API pl_matrix3x3 pl_get_rgb2xyz_matrix(const struct pl_raw_primaries *prim); + +// Similar to pl_get_rgb2xyz_matrix, but gives the inverse transformation. +PL_API pl_matrix3x3 pl_get_xyz2rgb_matrix(const struct pl_raw_primaries *prim); + +// Returns a primary adaptation matrix, which converts from one set of +// primaries to another. This is an RGB->RGB transformation. For rendering +// intents other than PL_INTENT_ABSOLUTE_COLORIMETRIC, the white point is +// adapted using the Bradford matrix. +PL_API pl_matrix3x3 pl_get_color_mapping_matrix(const struct pl_raw_primaries *src, + const struct pl_raw_primaries *dst, + enum pl_rendering_intent intent); + +// Return a chromatic adaptation matrix, which converts from one white point to +// another, using the CAT16 matrix. This is an RGB->RGB transformation. +PL_API pl_matrix3x3 pl_get_adaptation_matrix(struct pl_cie_xy src, struct pl_cie_xy dst); + +// Returns true if 'b' is entirely contained in 'a'. Useful for figuring out if +// colorimetric clipping will occur or not. +PL_API bool pl_primaries_superset(const struct pl_raw_primaries *a, + const struct pl_raw_primaries *b); + +// Returns true if `prim` forms a nominally valid set of primaries. This does +// not check whether or not these primaries are actually physically realisable, +// merely that they satisfy the requirements for colorspace math (to avoid NaN). +PL_API bool pl_primaries_valid(const struct pl_raw_primaries *prim); + +// Returns true if two primaries are 'compatible', which is the case if +// they preserve the relationship between primaries (red=red, green=green, +// blue=blue). In other words, this is false for synthetic primaries that have +// channels misordered from the convention (e.g. for some test ICC profiles). +PL_API bool pl_primaries_compatible(const struct pl_raw_primaries *a, + const struct pl_raw_primaries *b); + +// Clip points in the first gamut (src) to be fully contained inside the second +// gamut (dst). Only works on compatible primaries (pl_primaries_compatible). +PL_API struct pl_raw_primaries +pl_primaries_clip(const struct pl_raw_primaries *src, + const struct pl_raw_primaries *dst); + +// Primary-dependent RGB->LMS matrix for the IPTPQc4 color system. This is +// derived from the HPE XYZ->LMS matrix with 4% crosstalk added. +PL_API pl_matrix3x3 pl_ipt_rgb2lms(const struct pl_raw_primaries *prim); +PL_API pl_matrix3x3 pl_ipt_lms2rgb(const struct pl_raw_primaries *prim); + +// Primary-independent L'M'S' -> IPT matrix for the IPTPQc4 color system, and +// its inverse. This is identical to the Ebner & Fairchild (1998) IPT matrix. +PL_API extern const pl_matrix3x3 pl_ipt_lms2ipt; +PL_API extern const pl_matrix3x3 pl_ipt_ipt2lms; + +// Cone types involved in human vision +enum pl_cone { + PL_CONE_L = 1 << 0, + PL_CONE_M = 1 << 1, + PL_CONE_S = 1 << 2, + + // Convenience aliases + PL_CONE_NONE = 0, + PL_CONE_LM = PL_CONE_L | PL_CONE_M, + PL_CONE_MS = PL_CONE_M | PL_CONE_S, + PL_CONE_LS = PL_CONE_L | PL_CONE_S, + PL_CONE_LMS = PL_CONE_L | PL_CONE_M | PL_CONE_S, +}; + +// Structure describing parameters for simulating color blindness +struct pl_cone_params { + enum pl_cone cones; // Which cones are *affected* by the vision model + float strength; // Coefficient for how strong the defect is + // (1.0 = Unaffected, 0.0 = Full blindness) +}; + +#define pl_cone_params(...) (&(struct pl_cone_params) { __VA_ARGS__ }) + +// Built-in color blindness models +PL_API extern const struct pl_cone_params pl_vision_normal; // No distortion (92%) +PL_API extern const struct pl_cone_params pl_vision_protanomaly; // Red deficiency (0.66%) +PL_API extern const struct pl_cone_params pl_vision_protanopia; // Red absence (0.59%) +PL_API extern const struct pl_cone_params pl_vision_deuteranomaly; // Green deficiency (2.7%) +PL_API extern const struct pl_cone_params pl_vision_deuteranopia; // Green absence (0.56%) +PL_API extern const struct pl_cone_params pl_vision_tritanomaly; // Blue deficiency (0.01%) +PL_API extern const struct pl_cone_params pl_vision_tritanopia; // Blue absence (0.016%) +PL_API extern const struct pl_cone_params pl_vision_monochromacy; // Blue cones only (<0.001%) +PL_API extern const struct pl_cone_params pl_vision_achromatopsia; // Rods only (<0.0001%) + +// Returns a cone adaptation matrix. Applying this to an RGB color in the given +// color space will apply the given cone adaptation coefficients for simulating +// a type of color blindness. +// +// For the color blindness models which don't entail complete loss of a cone, +// you can partially counteract the effect by using a similar model with the +// `strength` set to its inverse. For example, to partially counteract +// deuteranomaly, you could generate a cone matrix for PL_CONE_M with the +// strength 2.0 (or some other number above 1.0). +PL_API pl_matrix3x3 pl_get_cone_matrix(const struct pl_cone_params *params, + const struct pl_raw_primaries *prim); + +// Returns a color decoding matrix for a given combination of source color +// representation and adjustment parameters. This mutates `repr` to reflect the +// change. If `params` is NULL, it defaults to &pl_color_adjustment_neutral. +// +// This function always performs a conversion to RGB. To convert to other +// colorspaces (e.g. between YUV systems), obtain a second YUV->RGB matrix +// and invert it using `pl_transform3x3_invert`. +// +// Note: For BT.2020 constant-luminance, this outputs chroma information in the +// range [-0.5, 0.5]. Since the CL system conversion is non-linear, further +// processing must be done by the caller. The channel order is CrYCb. +// +// Note: For BT.2100 ICtCp, this outputs in the color space L'M'S'. Further +// non-linear processing must be done by the caller. +// +// Note: XYZ system is expected to be in DCDM X'Y'Z' encoding (ST 428-1), in +// practice this means normalizing by (48.0 / 52.37) factor and applying 2.6 gamma +PL_API pl_transform3x3 pl_color_repr_decode(struct pl_color_repr *repr, + const struct pl_color_adjustment *params); + +// Common struct to describe an ICC profile +struct pl_icc_profile { + // Points to the in-memory representation of the ICC profile. This is + // allowed to be NULL, in which case the `pl_icc_profile` represents "no + // profile”. + const void *data; + size_t len; + + // If a profile is set, this signature must uniquely identify it (including + // across restarts, for caching), ideally using a checksum of the profile + // contents. The user is free to choose the method of determining this + // signature, but note the existence of the + // `pl_icc_profile_compute_signature` helper. + uint64_t signature; +}; + +#define pl_icc_profile(...) &(struct pl_icc_profile) { __VA_ARGS__ } + +// This doesn't do a comparison of the actual contents, only of the signature. +PL_API bool pl_icc_profile_equal(const struct pl_icc_profile *p1, + const struct pl_icc_profile *p2); + +// Sets `signature` to a hash of `profile->data`, if non-NULL. Provided as a +// convenience function for the sake of users ingesting arbitrary ICC profiles +// from sources where they can't reliably detect profile changes. +// +// Note: This is based on a very fast hash, and will compute a signature for +// even large (10 MB) ICC profiles in, typically, a fraction of a millisecond. +PL_API void pl_icc_profile_compute_signature(struct pl_icc_profile *profile); + +PL_API_END + +#endif // LIBPLACEBO_COLORSPACE_H_ diff --git a/third_party/exo-dv5-native/include/libplacebo/common.h b/third_party/exo-dv5-native/include/libplacebo/common.h new file mode 100644 index 0000000000..806730cfc3 --- /dev/null +++ b/third_party/exo-dv5-native/include/libplacebo/common.h @@ -0,0 +1,244 @@ +/* + * This file is part of libplacebo. + * + * libplacebo is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libplacebo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with libplacebo. If not, see . + */ + +#ifndef LIBPLACEBO_COMMON_H_ +#define LIBPLACEBO_COMMON_H_ + +#include + +#include + +PL_API_BEGIN + +// Some common utility types. These are overloaded to support 2D, 3D and +// integer/float variants. +typedef struct pl_rect2d { + int x0, y0; + int x1, y1; +} pl_rect2d; + +typedef struct pl_rect3d { + int x0, y0, z0; + int x1, y1, z1; +} pl_rect3d; + +typedef struct pl_rect2df { + float x0, y0; + float x1, y1; +} pl_rect2df; + +typedef struct pl_rect3df { + float x0, y0, z0; + float x1, y1, z1; +} pl_rect3df; + +// These macros will work for any of the above pl_rect variants (with enough +// dimensions). Careful: double-evaluation hazard +#define pl_rect_w(r) ((r).x1 - (r).x0) +#define pl_rect_h(r) ((r).y1 - (r).y0) +#define pl_rect_d(r) ((r).z1 - (r).z0) + +#define pl_rect2d_eq(a, b) \ + ((a).x0 == (b).x0 && (a).x1 == (b).x1 && \ + (a).y0 == (b).y0 && (a).y1 == (b).y1) + +#define pl_rect3d_eq(a, b) \ + ((a).x0 == (b).x0 && (a).x1 == (b).x1 && \ + (a).y0 == (b).y0 && (a).y1 == (b).y1 && \ + (a).z0 == (b).z0 && (a).z1 == (b).z1) + +// "Normalize" a rectangle: This ensures d1 >= d0 for all dimensions. +PL_API void pl_rect2d_normalize(pl_rect2d *rc); +PL_API void pl_rect3d_normalize(pl_rect3d *rc); + +PL_API void pl_rect2df_normalize(pl_rect2df *rc); +PL_API void pl_rect3df_normalize(pl_rect3df *rc); + +// Return the rounded form of a rect. +PL_API pl_rect2d pl_rect2df_round(const pl_rect2df *rc); +PL_API pl_rect3d pl_rect3df_round(const pl_rect3df *rc); + +// Represents a row-major matrix, i.e. the following matrix +// [ a11 a12 a13 ] +// [ a21 a22 a23 ] +// [ a31 a32 a33 ] +// is represented in C like this: +// { { a11, a12, a13 }, +// { a21, a22, a23 }, +// { a31, a32, a33 } }; +typedef struct pl_matrix3x3 { + float m[3][3]; +} pl_matrix3x3; + +PL_API extern const pl_matrix3x3 pl_matrix3x3_identity; + +// Applies a matrix to a float vector in-place. +PL_API void pl_matrix3x3_apply(const pl_matrix3x3 *mat, float vec[3]); + +// Applies a matrix to a pl_rect3df +PL_API void pl_matrix3x3_apply_rc(const pl_matrix3x3 *mat, pl_rect3df *rc); + +// Scales a color matrix by a linear factor. +PL_API void pl_matrix3x3_scale(pl_matrix3x3 *mat, float scale); + +// Inverts a matrix. Only use where precision is not that important. +PL_API void pl_matrix3x3_invert(pl_matrix3x3 *mat); + +// Composes/multiplies two matrices. Multiples B into A, i.e. +// A := A * B +PL_API void pl_matrix3x3_mul(pl_matrix3x3 *a, const pl_matrix3x3 *b); + +// Flipped version of `pl_matrix3x3_mul`. +// B := A * B +PL_API void pl_matrix3x3_rmul(const pl_matrix3x3 *a, pl_matrix3x3 *b); + +// Represents an affine transformation, which is basically a 3x3 matrix +// together with a column vector to add onto the output. +typedef struct pl_transform3x3 { + pl_matrix3x3 mat; + float c[3]; +} pl_transform3x3; + +PL_API extern const pl_transform3x3 pl_transform3x3_identity; + +// Applies a transform to a float vector in-place. +PL_API void pl_transform3x3_apply(const pl_transform3x3 *t, float vec[3]); + +// Applies a transform to a pl_rect3df +PL_API void pl_transform3x3_apply_rc(const pl_transform3x3 *t, pl_rect3df *rc); + +// Scales the output of a transform by a linear factor. Since an affine +// transformation is non-linear, this does not commute. If you want to scale +// the *input* of a transform, use pl_matrix3x3_scale on `t.mat`. +PL_API void pl_transform3x3_scale(pl_transform3x3 *t, float scale); + +// Inverts a transform. Only use where precision is not that important. +PL_API void pl_transform3x3_invert(pl_transform3x3 *t); + +// 2D analog of the above structs. Since these are featured less prominently, +// we omit some of the other helper functions. +typedef struct pl_matrix2x2 { + float m[2][2]; +} pl_matrix2x2; + +PL_API extern const pl_matrix2x2 pl_matrix2x2_identity; +PL_API pl_matrix2x2 pl_matrix2x2_rotation(float angle); + +PL_API void pl_matrix2x2_apply(const pl_matrix2x2 *mat, float vec[2]); +PL_API void pl_matrix2x2_apply_rc(const pl_matrix2x2 *mat, pl_rect2df *rc); + +PL_API void pl_matrix2x2_mul(pl_matrix2x2 *a, const pl_matrix2x2 *b); +PL_API void pl_matrix2x2_rmul(const pl_matrix2x2 *a, pl_matrix2x2 *b); + +PL_API void pl_matrix2x2_scale(pl_matrix2x2 *mat, float scale); +PL_API void pl_matrix2x2_invert(pl_matrix2x2 *mat); + +typedef struct pl_transform2x2 { + pl_matrix2x2 mat; + float c[2]; +} pl_transform2x2; + +PL_API extern const pl_transform2x2 pl_transform2x2_identity; + +PL_API void pl_transform2x2_apply(const pl_transform2x2 *t, float vec[2]); +PL_API void pl_transform2x2_apply_rc(const pl_transform2x2 *t, pl_rect2df *rc); + +PL_API void pl_transform2x2_mul(pl_transform2x2 *a, const pl_transform2x2 *b); +PL_API void pl_transform2x2_rmul(const pl_transform2x2 *a, pl_transform2x2 *b); + +PL_API void pl_transform2x2_scale(pl_transform2x2 *t, float scale); +PL_API void pl_transform2x2_invert(pl_transform2x2 *t); + +// Compute new bounding box of a transformation (as applied to a given rect). +PL_API pl_rect2df pl_transform2x2_bounds(const pl_transform2x2 *t, + const pl_rect2df *rc); + +// Helper functions for dealing with aspect ratios and stretched/scaled rects. + +// Return the (absolute) aspect ratio (width/height) of a given pl_rect2df. +// This will always be a positive number, even if `rc` is flipped. +PL_API float pl_rect2df_aspect(const pl_rect2df *rc); + +// Set the aspect of a `rc` to a given aspect ratio with an extra 'panscan' +// factor choosing the balance between shrinking and growing the `rc` to meet +// this aspect ratio. +// +// Notes: +// - If `panscan` is 0.0, this function will only ever shrink the `rc`. +// - If `panscan` is 1.0, this function will only ever grow the `rc`. +// - If `panscan` is 0.5, this function is area-preserving. +PL_API void pl_rect2df_aspect_set(pl_rect2df *rc, float aspect, float panscan); + +// Set one rect's aspect to that of another +#define pl_rect2df_aspect_copy(rc, src, panscan) \ + pl_rect2df_aspect_set((rc), pl_rect2df_aspect(src), (panscan)) + +// 'Fit' one rect inside another. `rc` will be set to the same size and aspect +// ratio as `src`, but with the size limited to fit inside the original `rc`. +// Like `pl_rect2df_aspect_set`, `panscan` controls the pan&scan factor. +PL_API void pl_rect2df_aspect_fit(pl_rect2df *rc, const pl_rect2df *src, float panscan); + +// Scale rect in each direction while keeping it centered. +PL_API void pl_rect2df_stretch(pl_rect2df *rc, float stretch_x, float stretch_y); + +// Offset rect by an arbitrary offset factor. If the corresponding dimension +// of a rect is flipped, so too is the applied offset. +PL_API void pl_rect2df_offset(pl_rect2df *rc, float offset_x, float offset_y); + +// Scale a rect uniformly in both dimensions. +#define pl_rect2df_zoom(rc, zoom) pl_rect2df_stretch((rc), (zoom), (zoom)) + +// Rotation in degrees clockwise +typedef int pl_rotation; +enum { + PL_ROTATION_0 = 0, + PL_ROTATION_90 = 1, + PL_ROTATION_180 = 2, + PL_ROTATION_270 = 3, + PL_ROTATION_360 = 4, // equivalent to PL_ROTATION_0 + + // Note: Values outside the range [0,4) are legal, including negatives. +}; + +// Constrains to the interval [PL_ROTATION_0, PL_ROTATION_360). +static inline pl_rotation pl_rotation_normalize(pl_rotation rot) +{ + return (rot % PL_ROTATION_360 + PL_ROTATION_360) % PL_ROTATION_360; +} + +// Rotates the coordinate system of a `pl_rect2d(f)` in a certain direction. +// For example, calling this with PL_ROTATION_90 will correspond to rotating +// the coordinate system 90° to the right (so the x axis becomes the y axis). +// +// The resulting rect is re-normalized in the same coordinate system. +PL_API void pl_rect2df_rotate(pl_rect2df *rc, pl_rotation rot); + +// Returns the aspect ratio in a rotated frame of reference. +static inline float pl_aspect_rotate(float aspect, pl_rotation rot) +{ + return (rot % PL_ROTATION_180) ? 1.0 / aspect : aspect; +} + +#define pl_rect2df_aspect_set_rot(rc, aspect, rot, panscan) \ + pl_rect2df_aspect_set((rc), pl_aspect_rotate((aspect), (rot)), (panscan)) + +#define pl_rect2df_aspect_copy_rot(rc, src, panscan, rot) \ + pl_rect2df_aspect_set_rot((rc), pl_rect2df_aspect(src), (rot), (panscan)) + +PL_API_END + +#endif // LIBPLACEBO_COMMON_H_ diff --git a/third_party/exo-dv5-native/include/libplacebo/config.h b/third_party/exo-dv5-native/include/libplacebo/config.h new file mode 100644 index 0000000000..ac7c530e2b --- /dev/null +++ b/third_party/exo-dv5-native/include/libplacebo/config.h @@ -0,0 +1,113 @@ +/* + * This file is part of libplacebo. + * + * libplacebo is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libplacebo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with libplacebo. If not, see . + */ + +#ifndef LIBPLACEBO_CONFIG_H_ +#define LIBPLACEBO_CONFIG_H_ + +// Increased any time the library changes in a fundamental/major way. +#define PL_MAJOR_VER 7 + +// Increased any time the API changes. (Note: Does not reset when PL_MAJOR_VER +// is increased) +#define PL_API_VER 375 + +// Increased any time a fix is made to a given API version. +#define PL_FIX_VER (pl_fix_ver()) + +// Friendly name (`git describe`) for the overall version of the library +#define PL_VERSION (pl_version()) + +// Feature tests. These aren't described in further detail, but may be useful +// for programmers wanting to programmatically check for feature support +// in their compiled libplacebo versions. +#undef PL_HAVE_D3D11 +#define PL_HAVE_DOVI 1 +#define PL_HAVE_GL_PROC_ADDR 1 +#undef PL_HAVE_GLSLANG +#undef PL_HAVE_LCMS +#undef PL_HAVE_LIBDOVI +#define PL_HAVE_OPENGL 1 +#define PL_HAVE_SHADERC 1 +#define PL_HAVE_VK_PROC_ADDR 1 +#define PL_HAVE_VULKAN 1 +#undef PL_HAVE_XXHASH + + +// Extra compiler-specific stuff +#ifndef PL_DEPRECATED_IN +# if defined(_MSC_VER) +# define PL_DEPRECATED_IN(VER) +# else +# define PL_DEPRECATED_IN(VER) __attribute__((deprecated)) +# endif +#endif + +#ifndef __has_feature +#define __has_feature(x) 0 +#endif + +#ifndef PL_DEPRECATED_ENUM_IN +# if (defined(__GNUC__) && (__GNUC__ >= 6)) || __has_feature(enumerator_attributes) +# define PL_DEPRECATED_ENUM_IN(VER) PL_DEPRECATED_IN(VER) +# else +# define PL_DEPRECATED_ENUM_IN(VER) +# endif +#endif + +#if defined(_WIN32) || defined(__CYGWIN__) +# ifdef PL_EXPORT +# define PL_API __declspec(dllexport) +# else +# ifndef PL_STATIC +# define PL_API __declspec(dllimport) +# else +# define PL_API +# endif +# endif +#else +# define PL_API __attribute__ ((visibility ("default"))) +#endif + +// C++ compatibility +#ifdef __cplusplus +# define PL_API_BEGIN extern "C" { +# define PL_API_END } +#else +# define PL_API_BEGIN +# define PL_API_END +#endif + +#ifndef __cplusplus +// Disable this warning because libplacebo's params macros override fields +# pragma GCC diagnostic ignored "-Woverride-init" +#endif + +// Extra helper macros +#define PL_TOSTRING_INNER(x) #x +#define PL_TOSTRING(x) PL_TOSTRING_INNER(x) + +// Deprecated macro for back-compatibility +#define PL_STRUCT(name) struct name##_t + +PL_API_BEGIN + +PL_API int pl_fix_ver(void); +PL_API const char *pl_version(void); + +PL_API_END + +#endif // LIBPLACEBO_CONFIG_H_ diff --git a/third_party/exo-dv5-native/include/libplacebo/dispatch.h b/third_party/exo-dv5-native/include/libplacebo/dispatch.h new file mode 100644 index 0000000000..141055c2bf --- /dev/null +++ b/third_party/exo-dv5-native/include/libplacebo/dispatch.h @@ -0,0 +1,239 @@ +/* + * This file is part of libplacebo. + * + * libplacebo is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libplacebo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with libplacebo. If not, see . + */ + +#ifndef LIBPLACEBO_DISPATCH_H_ +#define LIBPLACEBO_DISPATCH_H_ + +#include +#include + +PL_API_BEGIN + +// Thread-safety: Safe +typedef struct pl_dispatch_t *pl_dispatch; + +// Creates a new shader dispatch object. This object provides a translation +// layer between generated shaders (pl_shader) and the ra context such that it +// can be used to execute shaders. This dispatch object will also provide +// shader caching (for efficient re-use). +PL_API pl_dispatch pl_dispatch_create(pl_log log, pl_gpu gpu); +PL_API void pl_dispatch_destroy(pl_dispatch *dp); + +// Reset/increments the internal counters of the pl_dispatch. This must be +// called whenever the user is going to begin with a new frame, in order to +// perform garbage collection and advance the state of the internal PRNG. +// +// Note that shaders generated by `pl_dispatch` are therefore entirely +// deterministic, as long as the sequence of calls (and inputs to the shader) +// are the same. +PL_API void pl_dispatch_reset_frame(pl_dispatch dp); + +// Returns a blank pl_shader object, suitable for recording rendering commands. +// For more information, see the header documentation in `shaders/*.h`. +PL_API pl_shader pl_dispatch_begin(pl_dispatch dp); + +// Struct passed to `info_callback`. Only valid until that function returns. +struct pl_dispatch_info { + // Information about the shader for this shader execution, as well as a + // 64-bit signature uniquely identifying it. + pl_shader_info shader; + uint64_t signature; + + // A list of execution times for this pass, in nanoseconds. May be empty. + uint64_t samples[256]; + int num_samples; + + // As a convenience, this contains the last, average and peak of the above + // list of samples. If `num_samples` is 0, these values are also 0. + uint64_t last; + uint64_t peak; + uint64_t average; +}; + +// Helper function to make a copy of `pl_dispatch_info`, while overriding +// (and dereferencing) whatever was previously stored there. +static inline void pl_dispatch_info_move(struct pl_dispatch_info *dst, + const struct pl_dispatch_info *src) +{ + pl_shader_info_deref(&dst->shader); + *dst = *src; + dst->shader = pl_shader_info_ref(src->shader); +} + +// Set up a dispatch callback for this `pl_dispatch` object. The given callback +// will be run for every successfully dispatched shader. Call this again with +// `cb == NULL` to disable. +PL_API void pl_dispatch_callback(pl_dispatch dp, void *priv, + void (*cb)(void *priv, + const struct pl_dispatch_info *)); + +struct pl_dispatch_params { + // The shader to execute. The pl_dispatch will take over ownership + // of this shader, and return it back to the internal pool. + // + // This shader must have a compatible signature, i.e. inputs + // `PL_SHADER_SIG_NONE` and outputs `PL_SHADER_SIG_COLOR`. + pl_shader *shader; + + // The texture to render to. This must have params compatible with the + // shader, i.e. `target->params.renderable` for fragment shaders and + // `target->params.storable` for compute shaders. + // + // Note: Even when not using compute shaders, users are advised to always + // set `target->params.storable` if permitted by the `pl_fmt`, since this + // allows the use of compute shaders instead of full-screen quads, which is + // faster on some platforms. + pl_tex target; + + // The target rect to render to. Optional, if left as {0}, then the + // entire texture will be rendered to. + pl_rect2d rect; + + // If set, enables and controls the blending for this pass. Optional. When + // using this with fragment shaders, `target->params.fmt->caps` must + // include `PL_FMT_CAP_BLENDABLE`. + const struct pl_blend_params *blend_params; + + // If set, records the execution time of this dispatch into the given + // timer object. Optional. + // + // Note: If this is set, `pl_dispatch` cannot internally measure the + // execution time of the shader, which means `pl_dispatch_info.samples` may + // be empty as a result. + pl_timer timer; +}; + +#define pl_dispatch_params(...) (&(struct pl_dispatch_params) { __VA_ARGS__ }) + +// Dispatch a generated shader (via the pl_shader mechanism). Returns whether +// or not the dispatch was successful. +PL_API bool pl_dispatch_finish(pl_dispatch dp, const struct pl_dispatch_params *params); + +struct pl_dispatch_compute_params { + // The shader to execute. This must be a compute shader with the input + // set to PL_SHADER_SIG_NONE. The output, if it has any, is ignored. + pl_shader *shader; + + // The number of work groups to dispatch in each dimension. If this is left + // as [0} and `width/height` are both set, the number of work groups will + // be inferred from the shader's `compute_group_sizes`. + int dispatch_size[3]; + + // If set, simulate vertex attributes (similar to `pl_dispatch_finish`) + // according to the given dimensions. The first two components of the + // thread's global ID will be interpreted as the X and Y locations. + // + // Optional, ignored if either component is left as 0. + int width, height; + + // If set, records the execution time of this dispatch into the given + // timer object. Optional. + // + // Note: If this is set, `pl_dispatch` cannot internally measure the + // execution time of the shader, which means `pl_dispatch_info.samples` may + // be empty as a result. + pl_timer timer; +}; + +#define pl_dispatch_compute_params(...) (&(struct pl_dispatch_compute_params) { __VA_ARGS__ }) + +// A variant of `pl_dispatch_finish`, this one only dispatches a compute shader +// while ignoring its output (if it has one). It's only useful for shaders +// which have otherwise observable side effects (such as updating state +// objects). +PL_API bool pl_dispatch_compute(pl_dispatch dp, const struct pl_dispatch_compute_params *params); + +enum pl_vertex_coords { + PL_COORDS_ABSOLUTE, // Absolute/integer `target` coordinates + PL_COORDS_RELATIVE, // Relative `target` coordinates in range [0, 1] + PL_COORDS_NORMALIZED, // GL-normalized coordinates in range [-1, 1] +}; + +struct pl_dispatch_vertex_params { + // The shader to execute. This must be a raster shader with the input set + // to `PL_SHADER_SIG_NONE` and the output set to `PL_SHADER_SIG_COLOR`. + // + // Additionally, the shader must not have any attached vertex attributes. + pl_shader *shader; + + // The texture to render to. Requires `target->params.renderable`. + pl_tex target; + + // The target rect to clip the rendering to. (Optional) + pl_rect2d scissors; + + // If set, enables and controls the blending for this pass. Optional. When + // enabled, `target->params.fmt->caps` must include `PL_FMT_CAP_BLENDABLE`. + const struct pl_blend_params *blend_params; + + // The description of the vertex format, including offsets. + // + // Note: `location` is ignored and can safely be left unset. + const struct pl_vertex_attrib *vertex_attribs; + int num_vertex_attribs; + size_t vertex_stride; + + // The index of the vertex position in `vertex_attribs`, as well as the + // interpretation of its contents. + int vertex_position_idx; + enum pl_vertex_coords vertex_coords; + bool vertex_flipped; // flip all vertex y coordinates + + // Type and number of vertices to render. + enum pl_prim_type vertex_type; + int vertex_count; + + // Vertex data. See `pl_pass_run_params.vertex_data`. + const void *vertex_data; + pl_buf vertex_buf; + size_t buf_offset; + + // Index data. See `pl_pass_run_params.index_data`. Optional. + const void *index_data; + enum pl_index_format index_fmt; + pl_buf index_buf; + size_t index_offset; + + // If set, records the execution time of this dispatch into the given + // timer object. Optional. + // + // Note: If this is set, `pl_dispatch` cannot internally measure the + // execution time of the shader, which means `pl_dispatch_info.samples` may + // be empty as a result. + pl_timer timer; +}; + +#define pl_dispatch_vertex_params(...) (&(struct pl_dispatch_vertex_params) { __VA_ARGS__ }) + +// Dispatch a generated shader using custom vertices, rather than using a quad +// generated by the dispatch. This allows the use of e.g. custom fragment +// shaders for things like rendering custom UI elements, or possibly doing +// advanced things like sampling from a cube map or spherical video. +PL_API bool pl_dispatch_vertex(pl_dispatch dp, const struct pl_dispatch_vertex_params *params); + +// Cancel an active shader without submitting anything. Useful, for example, +// if the shader was instead merged into a different shader. +PL_API void pl_dispatch_abort(pl_dispatch dp, pl_shader *sh); + +// Deprecated in favor of `pl_cache_save/pl_cache_load` on the `pl_cache` +// associated with the `pl_gpu` this dispatch is using. +PL_DEPRECATED_IN(v6.323) PL_API size_t pl_dispatch_save(pl_dispatch dp, uint8_t *out_cache); +PL_DEPRECATED_IN(v6.323) PL_API void pl_dispatch_load(pl_dispatch dp, const uint8_t *cache); + +PL_API_END + +#endif // LIBPLACEBO_DISPATCH_H diff --git a/third_party/exo-dv5-native/include/libplacebo/dither.h b/third_party/exo-dv5-native/include/libplacebo/dither.h new file mode 100644 index 0000000000..84f17c78ad --- /dev/null +++ b/third_party/exo-dv5-native/include/libplacebo/dither.h @@ -0,0 +1,82 @@ +/* + * This file is part of libplacebo. + * + * libplacebo is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libplacebo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with libplacebo. If not, see . + */ + +#ifndef LIBPLACEBO_DITHER_H_ +#define LIBPLACEBO_DITHER_H_ + +#include + +PL_API_BEGIN + +// Generates a deterministic NxN bayer (ordered) dither matrix, storing the +// result in `data`. `size` must be a power of two. The resulting matrix will +// be roughly uniformly distributed within the range [0,1). +PL_API void pl_generate_bayer_matrix(float *data, int size); + +// Generates a random NxN blue noise texture. storing the result in `data`. +// `size` must be a positive power of two no larger than 256. The resulting +// texture will be roughly uniformly distributed within the range [0,1). +// +// Note: This function is very, *very* slow for large sizes. Generating a +// dither matrix with size 256 can take several seconds on a modern processor. +PL_API void pl_generate_blue_noise(float *data, int size); + +// Defines the border of all error diffusion kernels +#define PL_EDF_MIN_DX (-2) +#define PL_EDF_MAX_DX (2) +#define PL_EDF_MAX_DY (2) + +struct pl_error_diffusion_kernel { + const char *name; // Short and concise identifier + const char *description; // Longer / friendly name + + // The minimum value such that a (y, x) -> (y, x + y * shift) mapping will + // make all error pushing operations affect next column (and after it) + // only. + // + // Higher shift values are significantly more computationally intensive. + int shift; + + // The diffusion factor for (y, x) is pattern[y][x - PL_EDF_MIN_DX] / divisor. + int pattern[PL_EDF_MAX_DY + 1][PL_EDF_MAX_DX - PL_EDF_MIN_DX + 1]; + int divisor; +}; + +// Algorithms with shift=1: +PL_API extern const struct pl_error_diffusion_kernel pl_error_diffusion_simple; +PL_API extern const struct pl_error_diffusion_kernel pl_error_diffusion_false_fs; +// Algorithms with shift=2: +PL_API extern const struct pl_error_diffusion_kernel pl_error_diffusion_sierra_lite; +PL_API extern const struct pl_error_diffusion_kernel pl_error_diffusion_floyd_steinberg; +PL_API extern const struct pl_error_diffusion_kernel pl_error_diffusion_atkinson; +// Algorithms with shift=3, probably too heavy for low end GPUs: +PL_API extern const struct pl_error_diffusion_kernel pl_error_diffusion_jarvis_judice_ninke; +PL_API extern const struct pl_error_diffusion_kernel pl_error_diffusion_stucki; +PL_API extern const struct pl_error_diffusion_kernel pl_error_diffusion_burkes; +PL_API extern const struct pl_error_diffusion_kernel pl_error_diffusion_sierra2; +PL_API extern const struct pl_error_diffusion_kernel pl_error_diffusion_sierra3; + +// A list of built-in error diffusion kernels, terminated by NULL +PL_API extern const struct pl_error_diffusion_kernel * const pl_error_diffusion_kernels[]; +PL_API extern const int pl_num_error_diffusion_kernels; // excluding trailing NULL + +// Find the error diffusion kernel with the given name, or NULL on failure. +PL_API const struct pl_error_diffusion_kernel *pl_find_error_diffusion_kernel(const char *name); + +PL_API_END + +#endif // LIBPLACEBO_DITHER_H_ diff --git a/third_party/exo-dv5-native/include/libplacebo/filters.h b/third_party/exo-dv5-native/include/libplacebo/filters.h new file mode 100644 index 0000000000..248f7bbb41 --- /dev/null +++ b/third_party/exo-dv5-native/include/libplacebo/filters.h @@ -0,0 +1,421 @@ +/* + * This file is part of libplacebo. + * + * libplacebo is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libplacebo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with libplacebo. If not, see . + */ + +#ifndef LIBPLACEBO_FILTER_KERNELS_H_ +#define LIBPLACEBO_FILTER_KERNELS_H_ + +#include +#include + +PL_API_BEGIN + +#define PL_FILTER_MAX_PARAMS 2 + +// Invocation parameters for a given kernel +struct pl_filter_ctx { + float radius; + float params[PL_FILTER_MAX_PARAMS]; +}; + +// Represents a single filter function, i.e. kernel or windowing function. +struct pl_filter_function { + // The cosmetic name associated with this filter function. + const char *name; + + // The radius of the filter function. For resizable filters, this gives + // the radius needed to represent a single filter lobe (tap). + float radius; + + // If true, the filter function is resizable (see pl_filter_config.radius) + bool resizable; + + // If true, the filter function is tunable (see pl_filter_config.params) + bool tunable[PL_FILTER_MAX_PARAMS]; + + // If the relevant parameter is tunable, this contains the default values. + float params[PL_FILTER_MAX_PARAMS]; + + // The underlying filter function itself: Computes the weight as a function + // of the offset. All filter functions must be normalized such that x=0 is + // the center point, and in particular weight(0) = 1.0. The functions may + // be undefined for values of x outside [0, radius]. + double (*weight)(const struct pl_filter_ctx *f, double x); + + // If true, this filter represents an opaque placeholder for a more + // sophisticated filter function which does not fit into the pl_filter + // framework. `weight()` will always return 0.0. + bool opaque; +}; + +// Deprecated function, merely checks a->weight == b->weight +PL_DEPRECATED_IN(v6.303) PL_API bool +pl_filter_function_eq(const struct pl_filter_function *a, + const struct pl_filter_function *b); + +// Box filter: Entirely 1.0 within the radius, entirely 0.0 outside of it. +// This is also sometimes called a Dirichlet window +PL_API extern const struct pl_filter_function pl_filter_function_box; + +// Triangle filter: Linear transitions from 1.0 at x=0 to 0.0 at x=radius. +// This is also sometimes called a Bartlett window. +PL_API extern const struct pl_filter_function pl_filter_function_triangle; + +// Cosine filter: Ordinary cosine function, single lobe. +PL_API extern const struct pl_filter_function pl_filter_function_cosine; + +// Hann function: Cosine filter named after Julius von Hann. Also commonly +// mislabeled as a "Hanning" function, due to its similarly to the Hamming +// function. +PL_API extern const struct pl_filter_function pl_filter_function_hann; + +// Hamming function: Cosine filter named after Richard Hamming. +PL_API extern const struct pl_filter_function pl_filter_function_hamming; + +// Welch filter: Polynomial function consisting of a single parabolic section. +PL_API extern const struct pl_filter_function pl_filter_function_welch; + +// Kaiser filter: Approximation of the DPSS window using Bessel functions. +// Also sometimes called a Kaiser-Bessel window. +// Parameter [0]: Shape (alpha). Determines the trade-off between the main lobe +// and the side lobes. +PL_API extern const struct pl_filter_function pl_filter_function_kaiser; + +// Blackman filter: Cosine filter named after Ralph Beebe Blackman. +// Parameter [0]: Scale (alpha). Influences the shape. The defaults result in +// zeros at the third and fourth sidelobes. +PL_API extern const struct pl_filter_function pl_filter_function_blackman; + +// Bohman filter: 2nd order Cosine filter. +PL_API extern const struct pl_filter_function pl_filter_function_bohman; + +// Gaussian function: Similar to the Gaussian distribution, this defines a +// bell curve function. +// Parameter [0]: Scale (t), increasing makes the result blurrier. +PL_API extern const struct pl_filter_function pl_filter_function_gaussian; + +// Quadratic function: 2nd order approximation of the gaussian function. Also +// sometimes called a "quadric" window. +PL_API extern const struct pl_filter_function pl_filter_function_quadratic; + +// Sinc function: Widely used for both kernels and windows, sinc(x) = sin(x)/x. +PL_API extern const struct pl_filter_function pl_filter_function_sinc; + +// Jinc function: Similar to sinc, but extended to the 2D domain. Widely +// used as the kernel of polar (EWA) filters. Also sometimes called a Sombrero +// function. +PL_API extern const struct pl_filter_function pl_filter_function_jinc; + +// Sphinx function: Similar to sinc and jinx, but extended to the 3D domain. +// The name is derived from "spherical" sinc. Can be used to filter 3D signals +// in theory. +PL_API extern const struct pl_filter_function pl_filter_function_sphinx; + +// B/C-tunable Spline function: This is a family of commonly used spline +// functions with two tunable parameters. Does not need to be windowed. +// Parameter [0]: "B" +// Parameter [1]: "C" +// Some popular variants of this function are: +// B = 1.0, C = 0.0: "base" Cubic (blurry) +// B = 0.0, C = 0.0: Hermite filter (blocky) +// B = 0.0, C = 0.5: Catmull-Rom filter (sharp) +// B = 1/3, C = 1/3: Mitchell-Netravali filter (soft, doesn't ring) +// B ≈ 0.37, C ≈ 0.31: Robidoux filter (used by ImageMagick) +// B ≈ 0.26, C ≈ 0.37: RobidouxSharp filter (sharper variant of Robidoux) +PL_API extern const struct pl_filter_function pl_filter_function_cubic; +PL_API extern const struct pl_filter_function pl_filter_function_hermite; + +// Deprecated aliases of pl_filter_function_cubic (see the table above) +PL_DEPRECATED_IN(v6.341) PL_API extern const struct pl_filter_function pl_filter_function_bicubic; +PL_DEPRECATED_IN(v6.341) PL_API extern const struct pl_filter_function pl_filter_function_bcspline; +PL_DEPRECATED_IN(v6.341) PL_API extern const struct pl_filter_function pl_filter_function_catmull_rom; +PL_DEPRECATED_IN(v6.341) PL_API extern const struct pl_filter_function pl_filter_function_mitchell; +PL_DEPRECATED_IN(v6.341) PL_API extern const struct pl_filter_function pl_filter_function_robidoux; +PL_DEPRECATED_IN(v6.341) PL_API extern const struct pl_filter_function pl_filter_function_robidouxsharp; + +// Cubic splines with 2/3/4 taps. Referred to as "spline16", "spline36", and +// "spline64" mainly for historical reasons, based on the number of pixels in +// their window when using them as 2D orthogonal filters. Do not need to be +// windowed. +PL_API extern const struct pl_filter_function pl_filter_function_spline16; +PL_API extern const struct pl_filter_function pl_filter_function_spline36; +PL_API extern const struct pl_filter_function pl_filter_function_spline64; + +// Special filter function for the built-in oversampling algorithm. This is an +// opaque filter with no meaningful representation. though it has one tunable +// parameter controlling the threshold at which to switch back to ordinary +// nearest neighbour sampling. (See `pl_shader_sample_oversample`) +PL_API extern const struct pl_filter_function pl_filter_function_oversample; + +// A list of built-in filter functions, terminated by NULL +// +// Note: May contain extra aliases for the above functions. +PL_API extern const struct pl_filter_function * const pl_filter_functions[]; +PL_API extern const int pl_num_filter_functions; // excluding trailing NULL + +// Find the filter function with the given name, or NULL on failure. +PL_API const struct pl_filter_function *pl_find_filter_function(const char *name); + +// Backwards compatibility with the older configuration API. Redundant with +// `pl_filter_function.name`. May be formally deprecated in the future. + +struct pl_filter_function_preset { + const char *name; + const struct pl_filter_function *function; +}; + +// A list of built-in filter function presets, terminated by {0} +PL_API extern const struct pl_filter_function_preset pl_filter_function_presets[]; +PL_API extern const int pl_num_filter_function_presets; // excluding trailing {0} + +// Find the filter function preset with the given name, or NULL on failure. +PL_API const struct pl_filter_function_preset *pl_find_filter_function_preset(const char *name); + +// Different usage domains for a filter +enum pl_filter_usage { + PL_FILTER_UPSCALING = (1 << 0), + PL_FILTER_DOWNSCALING = (1 << 1), + PL_FILTER_FRAME_MIXING = (1 << 2), + + PL_FILTER_SCALING = PL_FILTER_UPSCALING | PL_FILTER_DOWNSCALING, + PL_FILTER_ALL = PL_FILTER_SCALING | PL_FILTER_FRAME_MIXING, +}; + +// Represents a tuned combination of filter functions, plus parameters +struct pl_filter_config { + // The cosmetic name associated with this filter config. Optional for + // user-provided configs, but always set by built-in configurations. + const char *name; + + // Longer / friendly name. Always set for built-in configurations, + // except for names which are merely aliases of other filters. + const char *description; + + // Allowed and recommended usage domains (respectively) + // + // When it is desired to maintain a simpler user interface, it may be + // recommended to include only scalers whose recommended usage domains + // includes the relevant context in which it will be used. + enum pl_filter_usage allowed; + enum pl_filter_usage recommended; + + // The kernel function and (optionally) windowing function. + const struct pl_filter_function *kernel; + const struct pl_filter_function *window; + + // The radius. Ignored if !kernel->resizable. Optional, defaults to + // kernel->radius if unset. + float radius; + + // Parameters for the respective filter function. Ignored if not tunable. + float params[PL_FILTER_MAX_PARAMS]; + float wparams[PL_FILTER_MAX_PARAMS]; + + // Represents a clamping coefficient for negative weights. A value of 0.0 + // (the default) represents no clamping. A value of 1.0 represents full + // clamping, i.e. all negative weights will be clamped to 0. Values in + // between will be linearly scaled. + float clamp; + + // Additional blur coefficient. This effectively stretches the kernel, + // without changing the effective radius of the filter radius. Setting this + // to a value of 0.0 is equivalent to disabling it. Values significantly + // below 1.0 may seriously degrade the visual output, and should be used + // with care. + float blur; + + // Additional taper coefficient. This essentially flattens the function's + // center. The values within [-taper, taper] will return 1.0, with the + // actual function being squished into the remainder of [taper, radius]. + // Defaults to 0.0. + float taper; + + // If true, this filter is intended to be used as a polar/2D filter (EWA) + // instead of a separable/1D filter. Does not affect the actual sampling, + // but provides information about how the results are to be interpreted. + bool polar; + + // Antiringing strength. A value of 0.0 disables antiringing, and a value + // of 1.0 enables full-strength antiringing. Defaults to 0.0 if + // unspecified. + // + // Note: This is only included in `pl_filter_config` for convenience. Does + // not affect the actual filter sampling, but provides information to the + // downstream consumer of the `pl_filter`. + float antiring; +}; + +PL_API bool pl_filter_config_eq(const struct pl_filter_config *a, + const struct pl_filter_config *b); + +// Samples a given filter configuration at a given x coordinate, while +// respecting all parameters of the configuration. +PL_API double pl_filter_sample(const struct pl_filter_config *c, double x); + +// A list of built-in filter configurations. Since they are just combinations +// of the above filter functions, they are not described in much further +// detail. +PL_API extern const struct pl_filter_config pl_filter_spline16; // 2 taps +PL_API extern const struct pl_filter_config pl_filter_spline36; // 3 taps +PL_API extern const struct pl_filter_config pl_filter_spline64; // 4 taps +PL_API extern const struct pl_filter_config pl_filter_nearest; +PL_API extern const struct pl_filter_config pl_filter_box; +PL_API extern const struct pl_filter_config pl_filter_bilinear; +PL_API extern const struct pl_filter_config pl_filter_gaussian; +// Sinc family (all configured to 3 taps): +PL_API extern const struct pl_filter_config pl_filter_sinc; // unwindowed +PL_API extern const struct pl_filter_config pl_filter_lanczos; // sinc-sinc +PL_API extern const struct pl_filter_config pl_filter_ginseng; // sinc-jinc +PL_API extern const struct pl_filter_config pl_filter_ewa_jinc; // unwindowed +PL_API extern const struct pl_filter_config pl_filter_ewa_lanczos; // jinc-jinc +PL_API extern const struct pl_filter_config pl_filter_ewa_lanczossharp; +PL_API extern const struct pl_filter_config pl_filter_ewa_lanczos4sharpest; +PL_API extern const struct pl_filter_config pl_filter_ewa_ginseng; // jinc-sinc +PL_API extern const struct pl_filter_config pl_filter_ewa_hann; // jinc-hann +// Spline family +PL_API extern const struct pl_filter_config pl_filter_bicubic; +PL_API extern const struct pl_filter_config pl_filter_hermite; +PL_API extern const struct pl_filter_config pl_filter_catmull_rom; +PL_API extern const struct pl_filter_config pl_filter_mitchell; +PL_API extern const struct pl_filter_config pl_filter_mitchell_clamp; // clamp = 1.0 +PL_API extern const struct pl_filter_config pl_filter_robidoux; +PL_API extern const struct pl_filter_config pl_filter_robidouxsharp; +PL_API extern const struct pl_filter_config pl_filter_ewa_robidoux; +PL_API extern const struct pl_filter_config pl_filter_ewa_robidouxsharp; +// Special/opaque filters +PL_API extern const struct pl_filter_config pl_filter_oversample; + +// Backwards compatibility +#define pl_filter_triangle pl_filter_bilinear +#define pl_oversample_frame_mixer pl_filter_oversample + +// A list of built-in filter configs, terminated by NULL +PL_API extern const struct pl_filter_config * const pl_filter_configs[]; +PL_API extern const int pl_num_filter_configs; // excluding trailing NULL + +// Find the filter config with the given name, or NULL on failure. +// `usage` restricts the valid usage (based on `pl_filter_config.allowed`). +PL_API const struct pl_filter_config * +pl_find_filter_config(const char *name, enum pl_filter_usage usage); + +// Backward compatibility with the previous filter configuration API. Redundant +// with pl_filter_config.name/description. May be deprecated in the future. +struct pl_filter_preset { + const char *name; + const struct pl_filter_config *filter; + + // Longer / friendly name, or NULL for aliases + const char *description; +}; + +// A list of built-in filter presets, terminated by {0} +PL_API extern const struct pl_filter_preset pl_filter_presets[]; +PL_API extern const int pl_num_filter_presets; // excluding trailing {0} + +// Find the filter preset with the given name, or NULL on failure. +PL_API const struct pl_filter_preset *pl_find_filter_preset(const char *name); + +// Parameters for filter generation. +struct pl_filter_params { + // The particular filter configuration to be sampled. config.kernel must + // be set to a valid pl_filter_function. + struct pl_filter_config config; + + // The precision of the resulting LUT. A value of 64 should be fine for + // most practical purposes, but higher or lower values may be justified + // depending on the use case. This value must be set to something > 0. + int lut_entries; + + // --- Polar filers only (config.polar) + + // As a micro-optimization, all samples below this cutoff value will be + // ignored when updating the cutoff radius. Setting it to a value of 0.0 + // disables this optimization. + float cutoff; + + // --- Separable filters only (!config.polar) + + // Indicates the maximum row size that is supported by the calling code, or + // 0 for no limit. + int max_row_size; + + // Indicates the row stride alignment. For some use cases (e.g. uploading + // the weights as a texture), there are certain alignment requirements for + // each row. The chosen row_size will always be a multiple of this value. + // Specifying 0 indicates no alignment requirements. + int row_stride_align; + + // --- Deprecated options + PL_DEPRECATED_IN(v6.316) float filter_scale; // no effect, use `config.blur` instead +}; + +#define pl_filter_params(...) (&(struct pl_filter_params) { __VA_ARGS__ }) + +// Represents an initialized instance of a particular filter, with a +// precomputed LUT. The interpretation of the LUT depends on the type of the +// filter (polar or separable). +typedef const struct pl_filter_t { + // Deep copy of the parameters, for convenience. + struct pl_filter_params params; + + // Contains the true radius of the computed filter. This may be + // smaller than the configured radius depending on the exact filter + // parameters used. Mainly relevant for polar filters, since + // it affects the value range of *weights. + float radius; + + // Radius of the first zero crossing (main lobe size). + float radius_zero; + + // The computed look-up table (LUT). For polar filters, this is interpreted + // as a 1D array with dimensions [lut_entries] containing the raw filter + // samples on the scale [0, radius]. For separable (non-polar) filters, + // this is interpreted as a 2D array with dimensions + // [lut_entries][row_stride]. The inner rows contain the `row_size` samples + // to convolve with the corresponding input pixels. The outer coordinate is + // used to very the fractional offset (phase). So for example, if the + // sample position to reconstruct is directly aligned with the source + // texels, you would use the values from weights[0]. If the sample position + // to reconstruct is exactly half-way between two source texels (180° out + // of phase), you would use the values from weights[lut_entries/2]. + const float *weights; + + // --- Separable filters only (!params.config.polar) + + // The number of source texels to convolve over for each row. This value + // will never exceed the given `max_row_size`. If the filter ends up + // cut off because of this, the bool `insufficient` will be set to true. + int row_size; + bool insufficient; + + // The separation (in *weights) between each row of the filter. Always + // a multiple of params.row_stride_align. + int row_stride; + + // --- Deprecated / removed fields + PL_DEPRECATED_IN(v6.336) float radius_cutoff; // identical to `radius` +} *pl_filter; + +// Generate (compute) a filter instance based on a given filter configuration. +// The resulting pl_filter must be freed with `pl_filter_free` when no longer +// needed. Returns NULL if filter generation fails due to invalid parameters +// (i.e. missing a required parameter). +PL_API pl_filter pl_filter_generate(pl_log log, const struct pl_filter_params *params); +PL_API void pl_filter_free(pl_filter *filter); + +PL_API_END + +#endif // LIBPLACEBO_FILTER_KERNELS_H_ diff --git a/third_party/exo-dv5-native/include/libplacebo/gamut_mapping.h b/third_party/exo-dv5-native/include/libplacebo/gamut_mapping.h new file mode 100644 index 0000000000..6b2fb44ed5 --- /dev/null +++ b/third_party/exo-dv5-native/include/libplacebo/gamut_mapping.h @@ -0,0 +1,182 @@ +/* + * This file is part of libplacebo. + * + * libplacebo is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libplacebo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with libplacebo. If not, see . + */ + +#ifndef LIBPLACEBO_GAMUT_MAPPING_H_ +#define LIBPLACEBO_GAMUT_MAPPING_H_ + +#include +#include + +PL_API_BEGIN + +struct pl_gamut_map_params; +struct pl_gamut_map_function { + const char *name; // Identifier + const char *description; // Friendly / longer name + + // The gamut-mapping function itself. Iterates over all values in `lut`, + // and adapts them as needed. + void (*map)(float *lut, const struct pl_gamut_map_params *params); + + // Returns true if `map` supports both stretching and contracting the + // gamut. In this case, `map` is always executed, even if the output gamut + // is larger than the input gamut. + bool bidirectional; + + // Private data. Unused by libplacebo, but may be accessed by `map`. + void *priv; +}; + +struct pl_gamut_map_constants { + // (Relative) chromaticity protection zone for perceptual mapping [0,1] + float perceptual_deadzone; + + // Strength of the perceptual saturation mapping component [0,1] + float perceptual_strength; + + // I vs C curve gamma to use for colorimetric clipping [0,10] + float colorimetric_gamma; + + // Knee point to use for softclipping methods (perceptual, softclip) [0,1] + float softclip_knee; + + // Desaturation strength (for softclip only) [0,1] + float softclip_desat; +}; + +#define PL_GAMUT_MAP_CONSTANTS \ + .colorimetric_gamma = 1.80f, \ + .softclip_knee = 0.70f, \ + .softclip_desat = 0.35f, \ + .perceptual_deadzone = 0.30f, \ + .perceptual_strength = 0.80f, + +struct pl_gamut_map_params { + // If `function` is NULL, defaults to `pl_gamut_map_clip`. + const struct pl_gamut_map_function *function; + + // The desired input/output primaries. This affects the subjective color + // volume in which the desired mapping shall take place. + struct pl_raw_primaries input_gamut; + struct pl_raw_primaries output_gamut; + + // Minimum/maximum luminance (PQ) of the target display. Note that the same + // value applies to both the input and output, since it's assumed that tone + // mapping has already happened by this stage. This effectively defines the + // legal gamut boundary in RGB space. + // + // This also defines the I channel value range, for `pl_gamut_map_generate` + float min_luma; + float max_luma; + + // Common constants, should be initialized to PL_GAMUT_MAP_CONSTANTS if + // not intending to override them further. + struct pl_gamut_map_constants constants; + + // -- LUT generation options (for `pl_gamut_map_generate` only) + + // The size of the resulting LUT, per channel. + // + // Note: For quality, it's generally best to increase h > I > C + int lut_size_I; + int lut_size_C; + int lut_size_h; + + // The stride (in number of floats) between elements in the resulting LUT. + int lut_stride; + + // -- Removed parameters + PL_DEPRECATED_IN(v6.289) float chroma_margin; // non-functional +}; + +#define pl_gamut_map_params(...) (&(struct pl_gamut_map_params) { \ + .constants = { PL_GAMUT_MAP_CONSTANTS }, \ + __VA_ARGS__ \ +}) + +// Note: Only does pointer equality testing on `function` +PL_API bool pl_gamut_map_params_equal(const struct pl_gamut_map_params *a, + const struct pl_gamut_map_params *b); + +// Returns true if the given gamut mapping configuration effectively represents +// a no-op configuration. Gamut mapping can be skipped in this case. +PL_API bool pl_gamut_map_params_noop(const struct pl_gamut_map_params *params); + +// Generate a gamut-mapping LUT for a given configuration. LUT samples are +// stored as IPTPQc4 values, but the LUT itself is indexed by IChPQc4,spanning +// the effective range [min_luma, max_luma] × [0, 0.5] × [-pi,pi]. +// +// This ordering is designed to keep frequently co-occurring values close in +// memory, while permitting simple wrapping of the 'h' component. +PL_API void pl_gamut_map_generate(float *out, const struct pl_gamut_map_params *params); + +// Samples a gamut mapping function for a single IPTPQc4 value. The input +// values are updated in-place. +PL_API void pl_gamut_map_sample(float x[3], const struct pl_gamut_map_params *params); + +// Performs no gamut-mapping, just hard clips out-of-range colors per-channel. +PL_API extern const struct pl_gamut_map_function pl_gamut_map_clip; + +// Performs a perceptually balanced (saturation) gamut mapping, using a soft +// knee function to preserve in-gamut colors, followed by a final softclip +// operation. This works bidirectionally, meaning it can both compress and +// expand the gamut. Behaves similar to a blend of `saturation` and `softclip`. +PL_API extern const struct pl_gamut_map_function pl_gamut_map_perceptual; + +// Performs a perceptually balanced gamut mapping using a soft knee function to +// roll-off clipped regions, and a hue shifting function to preserve saturation. +PL_API extern const struct pl_gamut_map_function pl_gamut_map_softclip; + +// Performs relative colorimetric clipping, while maintaining an exponential +// relationship between brightness and chromaticity. +PL_API extern const struct pl_gamut_map_function pl_gamut_map_relative; + +// Performs simple RGB->RGB saturation mapping. The input R/G/B channels are +// mapped directly onto the output R/G/B channels. Will never clip, but will +// distort all hues and/or result in a faded look. +PL_API extern const struct pl_gamut_map_function pl_gamut_map_saturation; + +// Performs absolute colorimetric clipping. Like pl_gamut_map_relative, but +// does not adapt the white point. +PL_API extern const struct pl_gamut_map_function pl_gamut_map_absolute; + +// Performs constant-luminance colorimetric clipping, desaturing colors +// towards white until they're in-range. +PL_API extern const struct pl_gamut_map_function pl_gamut_map_desaturate; + +// Uniformly darkens the input slightly to prevent clipping on blown-out +// highlights, then clamps colorimetrically to the input gamut boundary, +// biased slightly to preserve chromaticity over luminance. +PL_API extern const struct pl_gamut_map_function pl_gamut_map_darken; + +// Performs no gamut mapping, but simply highlights out-of-gamut pixels. +PL_API extern const struct pl_gamut_map_function pl_gamut_map_highlight; + +// Linearly/uniformly desaturates the image in order to bring the entire +// image into the target gamut. +PL_API extern const struct pl_gamut_map_function pl_gamut_map_linear; + +// A list of built-in gamut mapping functions, terminated by NULL +PL_API extern const struct pl_gamut_map_function * const pl_gamut_map_functions[]; +PL_API extern const int pl_num_gamut_map_functions; // excluding trailing NULL + +// Find the gamut mapping function with the given name, or NULL on failure. +PL_API const struct pl_gamut_map_function *pl_find_gamut_map_function(const char *name); + +PL_API_END + +#endif // LIBPLACEBO_GAMUT_MAPPING_H_ diff --git a/third_party/exo-dv5-native/include/libplacebo/gpu.h b/third_party/exo-dv5-native/include/libplacebo/gpu.h new file mode 100644 index 0000000000..446a46c93f --- /dev/null +++ b/third_party/exo-dv5-native/include/libplacebo/gpu.h @@ -0,0 +1,1419 @@ +/* + * This file is part of libplacebo. + * + * libplacebo is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libplacebo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with libplacebo. If not, see . + */ + +#ifndef LIBPLACEBO_GPU_H_ +#define LIBPLACEBO_GPU_H_ + +#include +#include +#include + +#include +#include +#include + +PL_API_BEGIN + +// These are not memory managed, and should represent compile-time constants +typedef const char *pl_debug_tag; +#define PL_DEBUG_TAG (__FILE__ ":" PL_TOSTRING(__LINE__)) + +// Type of a shader input descriptor. +enum pl_desc_type { + PL_DESC_INVALID = 0, + PL_DESC_SAMPLED_TEX, // C: pl_tex* GLSL: combined texture sampler + // (`pl_tex->params.sampleable` must be set) + PL_DESC_STORAGE_IMG, // C: pl_tex* GLSL: storage image + // (`pl_tex->params.storable` must be set) + PL_DESC_BUF_UNIFORM, // C: pl_buf* GLSL: uniform buffer + // (`pl_buf->params.uniform` must be set) + PL_DESC_BUF_STORAGE, // C: pl_buf* GLSL: storage buffer + // (`pl_buf->params.storable` must be set) + PL_DESC_BUF_TEXEL_UNIFORM,// C: pl_buf* GLSL: uniform samplerBuffer + // (`pl_buf->params.uniform` and `format` must be set) + PL_DESC_BUF_TEXEL_STORAGE,// C: pl_buf* GLSL: uniform imageBuffer + // (`pl_buf->params.uniform` and `format` must be set) + PL_DESC_TYPE_COUNT +}; + +// This file contains the definition of an API which is designed to abstract +// away from platform-specific APIs like the various OpenGL variants, Direct3D +// and Vulkan in a common way. It is a much more limited API than those APIs, +// since it tries targeting a very small common subset of features that is +// needed to implement libplacebo's rendering. +// +// NOTE: Most, but not all, parameter conditions (phrases such as "must" or +// "valid usage" are explicitly tested and result in error messages followed by +// graceful failure. Exceptions are noted where they exist. + +// Structure which wraps metadata describing GLSL capabilities. +struct pl_glsl_version { + int version; // GLSL version (e.g. 450), for #version + bool gles; // GLSL ES semantics (ESSL) + bool vulkan; // GL_KHR_vulkan_glsl semantics + + // Compute shader support and limits. If `compute` is false, then all + // of the remaining fields in this section are {0}. + bool compute; + size_t max_shmem_size; // maximum compute shader shared memory size + uint32_t max_group_threads; // maximum number of local threads per work group + uint32_t max_group_size[3]; // maximum work group size per dimension + + // If nonzero, signals availability of shader subgroups. This guarantess + // availability of all of the following extensions: + // - GL_KHR_shader_subgroup_basic + // - GL_KHR_shader_subgroup_vote + // - GL_KHR_shader_subgroup_arithmetic + // - GL_KHR_shader_subgroup_ballot + // - GL_KHR_shader_subgroup_shuffle + uint32_t subgroup_size; + + // Miscellaneous shader limits + int16_t min_gather_offset; // minimum `textureGatherOffset` offset + int16_t max_gather_offset; // maximum `textureGatherOffset` offset +}; + +// Backwards compatibility alias +#define pl_glsl_desc pl_glsl_version + +// Structure defining the physical limits and capabilities of this GPU +// instance. If a limit is given as 0, that means that feature is unsupported. +struct pl_gpu_limits { + // --- pl_gpu + bool thread_safe; // `pl_gpu` calls are thread-safe + bool callbacks; // supports asynchronous GPU callbacks + + // --- pl_buf + size_t max_buf_size; // maximum size of any buffer + size_t max_ubo_size; // maximum size of a `uniform` buffer + size_t max_ssbo_size; // maximum size of a `storable` buffer + size_t max_vbo_size; // maximum size of a `drawable` buffer + size_t max_mapped_size; // maximum size of a `host_mapped` buffer + uint64_t max_buffer_texels; // maximum number of texels in a texel buffer + bool host_cached; // if true, PL_BUF_MEM_HOST buffers are cached + bool host_ptr_slow; // if true, PL_HANDLE_HOST_PTR import is slow + size_t max_mapped_vram; // maximum (known) size of a `host_mapped` + // PL_BUF_MEM_DEVICE buffer, or 0 if this + // combination is not supported + + // Required alignment for PL_HANDLE_HOST_PTR imports. This is provided + // merely as a hint to the user. If the host pointer being imported is + // misaligned, libplacebo will internally round (over-map) the region. + size_t align_host_ptr; + + // --- pl_tex + uint32_t max_tex_1d_dim; // maximum width for a 1D texture + uint32_t max_tex_2d_dim; // maximum width/height for a 2D texture (required) + uint32_t max_tex_3d_dim; // maximum width/height/depth for a 3D texture + bool blittable_1d_3d; // supports blittable 1D/3D textures + bool buf_transfer; // supports `pl_tex_transfer_params.buf` + + // These don't represent hard limits but indicate performance hints for + // optimal alignment. For best performance, the corresponding field + // should be aligned to a multiple of these. They will always be a power + // of two. + size_t align_tex_xfer_pitch; // optimal `pl_tex_transfer_params.row_pitch` + size_t align_tex_xfer_offset; // optimal `pl_tex_transfer_params.buf_offset` + + // --- pl_pass + size_t max_variable_comps; // maximum components passed in variables + size_t max_constants; // maximum `pl_pass_params.num_constants` + bool array_size_constants; // push constants can be used to size arrays + size_t max_pushc_size; // maximum `push_constants_size` + size_t align_vertex_stride; // alignment of `pl_pass_params.vertex_stride` + uint32_t max_dispatch[3]; // maximum dispatch size per dimension + + // Note: At least one of `max_variable_comps` or `max_ubo_size` is + // guaranteed to be nonzero. + + // As a performance hint, the GPU may signal the number of command queues + // it has for fragment and compute shaders, respectively. Users may use + // this information to decide the appropriate type of shader to dispatch. + uint32_t fragment_queues; + uint32_t compute_queues; +}; + +// Backwards compatibility aliases +#define max_xfer_size max_buf_size +#define align_tex_xfer_stride align_tex_xfer_pitch + +// Some `pl_gpu` operations allow sharing GPU resources with external APIs - +// examples include interop with other graphics APIs such as CUDA, and also +// various hardware decoding APIs. This defines the mechanism underpinning the +// communication of such an interoperation. +typedef uint64_t pl_handle_caps; +enum pl_handle_type { + PL_HANDLE_FD = (1 << 0), // `int fd` for POSIX-style APIs + PL_HANDLE_WIN32 = (1 << 1), // `HANDLE` for win32 API + PL_HANDLE_WIN32_KMT = (1 << 2), // `HANDLE` for pre-Windows-8 win32 API + PL_HANDLE_DMA_BUF = (1 << 3), // 'int fd' for a dma_buf fd + PL_HANDLE_HOST_PTR = (1 << 4), // `void *` for a host-allocated pointer + PL_HANDLE_MTL_TEX = (1 << 5), // `MTLTexture*` for Apple platforms + PL_HANDLE_IOSURFACE = (1 << 6), // `IOSurfaceRef` for Apple platforms +}; + +struct pl_gpu_handle_caps { + pl_handle_caps tex; // supported handles for `pl_tex` + `pl_shared_mem` + pl_handle_caps buf; // supported handles for `pl_buf` + `pl_shared_mem` + pl_handle_caps sync; // supported handles for semaphores +}; + +// Wrapper for the handle used to communicate a shared resource externally. +// This handle is owned by the `pl_gpu` - if a user wishes to use it in a way +// that takes over ownership (e.g. importing into some APIs), they must clone +// the handle before doing so (e.g. using `dup` for fds). It is important to +// read the external API documentation _very_ carefully as different handle +// types may be managed in different ways. (eg: CUDA takes ownership of an fd, +// but does not take ownership of a win32 handle). +union pl_handle { + int fd; // PL_HANDLE_FD / PL_HANDLE_DMA_BUF + void *handle; // PL_HANDLE_WIN32 / PL_HANDLE_WIN32_KMT / PL_HANDLE_MTL_TEX / PL_HANDLE_IOSURFACE + void *ptr; // PL_HANDLE_HOST_PTR +}; + +// Structure encapsulating memory that is shared between libplacebo and the +// user. This memory can be imported into external APIs using the handle. +// +// If the object a `pl_shared_mem` belongs to is destroyed (e.g. via +// `pl_buf_destroy`), the handle becomes undefined, as do the contents of the +// memory it points to, as well as any external API objects imported from it. +struct pl_shared_mem { + union pl_handle handle; + size_t size; // the total size of the memory referenced by this handle + size_t offset; // the offset of the object within the referenced memory + + // Note: `size` is optional for some APIs and handle types, in particular + // when importing DMABUFs or D3D11 textures. + + // For PL_HANDLE_DMA_BUF, this specifies the DRM format modifier that + // describes this resource. Note that when importing `pl_buf`, this must + // be DRM_FORMAT_MOD_LINEAR. For importing `pl_tex`, it can be any + // format modifier supported by the implementation. + uint64_t drm_format_mod; + + // When importing a `pl_tex` of type PL_HANDLE_DMA_BUF, this can be used to + // set the image stride (AKA pitch) in memory. If left as 0, defaults to + // the image width/height. + size_t stride_w; + size_t stride_h; + + // When importing a `pl_tex` of type PL_HANDLE_MTL_TEX, this determines + // which plane is imported (0 - 2). + unsigned plane; +}; + +// Structure grouping PCI bus address fields for GPU devices +struct pl_gpu_pci_address { + uint32_t domain; + uint32_t bus; + uint32_t device; + uint32_t function; +}; + +typedef const struct pl_fmt_t *pl_fmt; + +// Abstract device context which wraps an underlying graphics context and can +// be used to dispatch rendering commands. +// +// Thread-safety: Depends on `pl_gpu_limits.thread_safe` +typedef const struct pl_gpu_t { + pl_log log; + + struct pl_glsl_version glsl; // GLSL features supported by this GPU + struct pl_gpu_limits limits; // physical device limits and capabilities + + // Fields relevant to external API interop. If the underlying device does + // not support interop with other APIs, these will all be {0}. + struct pl_gpu_handle_caps export_caps; // supported handles for exporting + struct pl_gpu_handle_caps import_caps; // supported handles for importing + uint8_t uuid[16]; // underlying device UUID + + // Supported texture formats, in preference order. (If there are multiple + // similar formats, the "better" ones come first) + pl_fmt *formats; + int num_formats; + + // PCI Bus address of the underlying device, to help with interop. + // This will only be filled in if interop is supported. + struct pl_gpu_pci_address pci; +} *pl_gpu; + +// Attach a pl_cache object to this GPU instance. This cache will be +// used to cache all compiled shaders, as well as several other shader objects +// (e.g. cached 3DLUTs). Calling this with `cache = NULL` disables the cache. +// +// Note: Calling this after shaders have already been compiled will not +// retroactively add those shaders to the cache, so it's recommended to set +// this early, before creating any passes. +PL_API void pl_gpu_set_cache(pl_gpu gpu, pl_cache cache); + +enum pl_fmt_type { + PL_FMT_UNKNOWN = 0, // also used for inconsistent multi-component formats + PL_FMT_UNORM, // unsigned, normalized integer format (sampled as float) + PL_FMT_SNORM, // signed, normalized integer format (sampled as float) + PL_FMT_UINT, // unsigned integer format (sampled as integer) + PL_FMT_SINT, // signed integer format (sampled as integer) + PL_FMT_FLOAT, // (signed) float formats, any bit size + PL_FMT_TYPE_COUNT, +}; + +enum pl_fmt_caps { + PL_FMT_CAP_SAMPLEABLE = 1 << 0, // may be sampled from (PL_DESC_SAMPLED_TEX) + PL_FMT_CAP_STORABLE = 1 << 1, // may be used as storage image (PL_DESC_STORAGE_IMG) + PL_FMT_CAP_LINEAR = 1 << 2, // may be linearly samplied from (PL_TEX_SAMPLE_LINEAR) + PL_FMT_CAP_RENDERABLE = 1 << 3, // may be rendered to (pl_pass_params.target_fmt) + PL_FMT_CAP_BLENDABLE = 1 << 4, // may be blended to (pl_pass_params.enable_blend) + PL_FMT_CAP_BLITTABLE = 1 << 5, // may be blitted from/to (pl_tex_blit) + PL_FMT_CAP_VERTEX = 1 << 6, // may be used as a vertex attribute + PL_FMT_CAP_TEXEL_UNIFORM = 1 << 7, // may be used as a texel uniform buffer + PL_FMT_CAP_TEXEL_STORAGE = 1 << 8, // may be used as a texel storage buffer + PL_FMT_CAP_HOST_READABLE = 1 << 9, // may be used with `host_readable` textures + PL_FMT_CAP_READWRITE = 1 << 10, // may be used with PL_DESC_ACCESS_READWRITE + + // Notes: + // - PL_FMT_CAP_LINEAR also implies PL_FMT_CAP_SAMPLEABLE + // - PL_FMT_CAP_STORABLE also implies `pl_gpu.glsl.compute` + // - PL_FMT_CAP_BLENDABLE implies PL_FMT_CAP_RENDERABLE + // - PL_FMT_CAP_VERTEX implies that the format is non-opaque + // - PL_FMT_CAP_HOST_READABLE implies that the format is non-opaque +}; + +struct pl_fmt_plane { + // Underlying format of this particular sub-plane. This describes the + // components, texel size and host representation for the purpose of + // e.g. transfers, blits, and sampling. + pl_fmt format; + + // X/Y subsampling shift factor for this plane. + uint8_t shift_x, shift_y; +}; + +// Structure describing a texel/vertex format. +struct pl_fmt_t { + const char *name; // symbolic name for this format (e.g. rgba32f) + uint64_t signature; // unique but stable signature (for pass reusability) + + enum pl_fmt_type type; // the format's data type and interpretation + enum pl_fmt_caps caps; // the features supported by this format + int num_components; // number of components for this format + int component_depth[4]; // meaningful bits per component, texture precision + size_t internal_size; // internal texel size (for blit compatibility) + + // For planar formats, this provides a description of each sub-plane. + // + // Note on planar formats: Planar formats are always opaque and typically + // support only a limit subset of capabilities (or none at all). Access + // should be done via sub-planes. (See `pl_tex.planes`) + struct pl_fmt_plane planes[4]; + int num_planes; // or 0 for non-planar textures + + // This controls the relationship between the data as seen by the host and + // the way it's interpreted by the texture. The host representation is + // always tightly packed (no padding bits in between each component). + // + // This representation assumes little endian ordering, i.e. components + // being ordered from LSB to MSB in memory. Note that for oddly packed + // formats like rgb10a2 or rgb565, this is inconsistent with the naming. + // (That is to say, rgb565 has sample order {2, 1, 0} under this convention + // - because rgb565 treats the R channel as the *most* significant bits) + // + // If `opaque` is true, then there's no meaningful correspondence between + // the two, and all of the remaining fields in this section are unset. + // + // If `emulated` is true, then this format doesn't actually exist on the + // GPU as an uploadable texture format - and any apparent support is being + // emulated (typically using compute shaders in the upload path). + bool opaque; + bool emulated; + size_t texel_size; // total size in bytes per texel + size_t texel_align; // texel alignment requirements (bytes) + int host_bits[4]; // number of meaningful bits in host memory + int sample_order[4]; // sampled index for each component, e.g. + // {2, 1, 0, 3} for BGRA textures + + // For sampleable formats, this bool indicates whether or not the format + // is compatible with `textureGather()` + bool gatherable; + + // If usable as a vertex or texel buffer format, this gives the GLSL type + // corresponding to the data. (e.g. vec4) + const char *glsl_type; + + // If usable as a storage image or texel storage buffer + // (PL_FMT_CAP_STORABLE / PL_FMT_CAP_TEXEL_STORAGE), this gives the GLSL + // texel format corresponding to the format (e.g. rgba16ui), if any. This + // field may be NULL, in which case the format modifier may be left + // unspecified. + const char *glsl_format; + + // If available, this gives the fourcc associated with the host + // representation. In particular, this is intended for use with + // PL_HANDLE_DMA_BUF, where this field will match the DRM format from + // . May be 0, for formats without matching DRM fourcc. + uint32_t fourcc; + + // If `fourcc` is set, this contains the list of supported drm format + // modifiers for this format. + const uint64_t *modifiers; + int num_modifiers; +}; + +// Returns whether or not a pl_fmt's components are ordered sequentially +// in memory in the order RGBA. +PL_API bool pl_fmt_is_ordered(pl_fmt fmt); + +// Returns whether or not a pl_fmt is sampled as a float (e.g. UNORM) +PL_API bool pl_fmt_is_float(pl_fmt fmt); + +// Returns whether or not a pl_fmt supports a given DRM modifier. +PL_API bool pl_fmt_has_modifier(pl_fmt fmt, uint64_t modifier); + +// Helper function to find a format with a given number of components and +// minimum effective precision per component. If `host_bits` is set, then the +// format will always be non-opaque, unpadded, ordered and have exactly this +// bit depth for each component. Finally, all `caps` must be supported. +PL_API pl_fmt pl_find_fmt(pl_gpu gpu, enum pl_fmt_type type, int num_components, + int min_depth, int host_bits, enum pl_fmt_caps caps); + +// Finds a vertex format for a given configuration. The resulting vertex will +// have a component depth equivalent to the sizeof() the equivalent host type. +// (e.g. PL_FMT_FLOAT will always have sizeof(float)) +PL_API pl_fmt pl_find_vertex_fmt(pl_gpu gpu, enum pl_fmt_type type, int num_components); + +// Find a format based on its name. +PL_API pl_fmt pl_find_named_fmt(pl_gpu gpu, const char *name); + +// Find a format based on its fourcc. +PL_API pl_fmt pl_find_fourcc(pl_gpu gpu, uint32_t fourcc); + +// A generic 'timer query' object. These can be used to measure an +// approximation of the GPU execution time of a given operation. Due to the +// highly asynchronous nature of GPUs, the actual results of any individual +// timer query may be delayed by quite a bit. As such, users should avoid +// trying to pair any particular GPU command with any particular timer query +// result, and only reuse `pl_timer` objects with identical operations. The +// results of timer queries are guaranteed to be in-order, but individual +// queries may be dropped, and some operations might not record timer results +// at all. (For example, if the underlying hardware does not support timer +// queries for a given operation type) +// +// Thread-safety: Unsafe +typedef struct pl_timer_t *pl_timer; + +// Creates a new timer object. This may return NULL, for example if the +// implementation does not support timers, but since passing NULL to +// `pl_timer_destroy` and `pl_timer_query` is safe, users generally need not +// concern themselves with handling this. +PL_API pl_timer pl_timer_create(pl_gpu gpu); +PL_API void pl_timer_destroy(pl_gpu gpu, pl_timer *); + +// Queries any results that have been measured since the last execution of +// `pl_timer_query`. There may be more than one result, in which case the user +// should simply call the function again to get the subsequent values. This +// function returns a value of 0 in the event that there are no more +// unprocessed results. +// +// The results are reported in nanoseconds, but the actual precision of the +// timestamp queries may be significantly lower. +// +// Note: Results do not queue up indefinitely. Generally, the implementation +// will only keep track of a small, fixed number of results internally. Make +// sure to include this function as part of your main rendering loop to process +// all of its results, or older results will be overwritten by newer ones. +PL_API uint64_t pl_timer_query(pl_gpu gpu, pl_timer); + +enum pl_buf_mem_type { + PL_BUF_MEM_AUTO = 0, // use whatever seems most appropriate + PL_BUF_MEM_HOST, // try allocating from host memory (RAM) + PL_BUF_MEM_DEVICE, // try allocating from device memory (VRAM) + PL_BUF_MEM_TYPE_COUNT, + + // Note: This distinction only matters for discrete GPUs +}; + +// Structure describing a buffer. +struct pl_buf_params { + size_t size; // size in bytes (must be <= `pl_gpu_limits.max_buf_size`) + bool host_writable; // contents may be updated via pl_buf_write() + bool host_readable; // contents may be read back via pl_buf_read() + bool host_mapped; // create a persistent, RW mapping (pl_buf.data) + + // May be used as PL_DESC_BUF_UNIFORM or PL_DESC_BUF_TEXEL_UNIFORM. + // Requires `size <= pl_gpu_limits.max_ubo_size` + bool uniform; + + // May be used as PL_DESC_BUF_STORAGE or PL_DESC_BUF_TEXEL_STORAGE. + // Requires `size <= pl_gpu_limits.max_ssbo_size` + bool storable; + + // May be used as the source of vertex data for `pl_pass_run`. + bool drawable; + + // Provide a hint for the memory type you want to use when allocating + // this buffer's memory. + // + // Note: Restrictions may apply depending on the usage flags. In + // particular, allocating buffers with `uniform` or `storable` enabled from + // non-device memory will almost surely fail. + enum pl_buf_mem_type memory_type; + + // Setting this to a format with the `PL_FMT_CAP_TEXEL_*` capability allows + // this buffer to be used as a `PL_DESC_BUF_TEXEL_*`, when `uniform` and + // `storage` are respectively also enabled. + pl_fmt format; + + // At most one of `export_handle` and `import_handle` can be set for a + // buffer. + + // Setting this indicates that the memory backing this buffer should be + // shared with external APIs, If so, this must be exactly *one* of + // `pl_gpu.export_caps.buf`. + enum pl_handle_type export_handle; + + // Setting this indicates that the memory backing this buffer will be + // imported from an external API. If so, this must be exactly *one* of + // `pl_gpu.import_caps.buf`. + enum pl_handle_type import_handle; + + // If the shared memory is being imported, the import handle must be + // specified here. Otherwise, this is ignored. + struct pl_shared_mem shared_mem; + + // If non-NULL, the buffer will be created with these contents. Otherwise, + // the initial data is undefined. Using this does *not* require setting + // host_writable. + const void *initial_data; + + // Arbitrary user data. libplacebo does not use this at all. + void *user_data; + + // Arbitrary identifying tag. Used only for debugging purposes. + pl_debug_tag debug_tag; +}; + +#define pl_buf_params(...) (&(struct pl_buf_params) { \ + .debug_tag = PL_DEBUG_TAG, \ + __VA_ARGS__ \ + }) + +// A generic buffer, which can be used for multiple purposes (texture transfer, +// storage buffer, uniform buffer, etc.) +// +// Note on efficiency: A pl_buf does not necessarily represent a true "buffer" +// object on the underlying graphics API. It may also refer to a sub-slice of +// a larger buffer, depending on the implementation details of the GPU. The +// bottom line is that users do not need to worry about the efficiency of using +// many small pl_buf objects. Having many small pl_bufs, even lots of few-byte +// vertex buffers, is designed to be completely fine. +// +// Thread-safety: Unsafe +typedef const struct pl_buf_t { + struct pl_buf_params params; + uint8_t *data; // for persistently mapped buffers, points to the first byte + + // If `params.handle_type` is set, this structure references the shared + // memory backing this buffer, via the requested handle type. + // + // While this buffer is not in an "exported" state, the contents of the + // memory are undefined. (See: `pl_buf_export`) + struct pl_shared_mem shared_mem; +} *pl_buf; + +// Create a buffer. The type of buffer depends on the parameters. The buffer +// parameters must adhere to the restrictions imposed by the pl_gpu_limits. +// Returns NULL on failure. +// +// For buffers with shared memory, the buffer is considered to be in an +// "exported" state by default, and may be used directly by the external API +// after being created (until the first libplacebo operation on the buffer). +PL_API pl_buf pl_buf_create(pl_gpu gpu, const struct pl_buf_params *params); +PL_API void pl_buf_destroy(pl_gpu gpu, pl_buf *buf); + +// This behaves like `pl_buf_create`, but if the buffer already exists and has +// incompatible parameters, it will get destroyed first. A buffer is considered +// "compatible" if it has the same buffer type and texel format, a size greater +// than or equal to the requested size, and it has a superset of the features +// the user requested. After this operation, the contents of the buffer are +// undefined. +// +// Note: Due to its unpredictability, it's not allowed to use this with +// `params->initial_data` being set. Similarly, it's not allowed on a buffer +// with `params->export_handle`. since this may invalidate the corresponding +// external API's handle. Conversely, it *is* allowed on a buffer with +// `params->host_mapped`, and the corresponding `buf->data` pointer *may* +// change as a result of doing so. +// +// Note: If the `user_data` alone changes, this does not trigger a buffer +// recreation. In theory, this can be used to detect when the buffer ended +// up being recreated. +PL_API bool pl_buf_recreate(pl_gpu gpu, pl_buf *buf, const struct pl_buf_params *params); + +// Update the contents of a buffer, starting at a given offset (must be a +// multiple of 4) and up to a given size, with the contents of *data. +// +// This function will block until the buffer is no longer in use. Use +// `pl_buf_poll` to perform non-blocking queries of buffer availability. +// +// Note: This function can incur synchronization overhead, so it shouldn't be +// used in tight loops. If you do need to loop (e.g. to perform a strided +// write), consider using host-mapped buffers, or fixing the memory in RAM, +// before calling this function. +PL_API void pl_buf_write(pl_gpu gpu, pl_buf buf, size_t buf_offset, + const void *data, size_t size); + +// Read back the contents of a buffer, starting at a given offset, storing the +// data into *dest. Returns whether successful. +// +// This function will block until the buffer is no longer in use. Use +// `pl_buf_poll` to perform non-blocking queries of buffer availability. +PL_API bool pl_buf_read(pl_gpu gpu, pl_buf buf, size_t buf_offset, + void *dest, size_t size); + +// Copy `size` bytes from one buffer to another, reading from and writing to +// the respective offsets. +PL_API void pl_buf_copy(pl_gpu gpu, pl_buf dst, size_t dst_offset, + pl_buf src, size_t src_offset, size_t size); + +// Initiates a buffer export operation, allowing a buffer to be accessed by an +// external API. This is only valid for buffers with `params.handle_type`. +// Calling this twice in a row is a harmless no-op. Returns whether successful. +// +// There is no corresponding "buffer import" operation, the next libplacebo +// operation that touches the buffer (e.g. pl_tex_upload, but also pl_buf_write +// and pl_buf_read) will implicitly import the buffer back to libplacebo. Users +// must ensure that all pending operations made by the external API are fully +// completed before using it in libplacebo again. (Otherwise, the behaviour +// is undefined) +// +// Please note that this function returning does not mean the memory is +// immediately available as such. In general, it will mark a buffer as "in use" +// in the same way any other buffer operation would, and it is the user's +// responsibility to wait until `pl_buf_poll` returns false before accessing +// the memory from the external API. +// +// In terms of the access performed by this operation, it is not considered a +// "read" or "write" and therefore does not technically conflict with reads or +// writes to the buffer performed by the host (via mapped memory - any use of +// `pl_buf_read` or `pl_buf_write` would defeat the purpose of the export). +// However, restrictions made by the external API may apply that prevent this. +// +// The recommended use pattern is something like this: +// +// while (loop) { +// pl_buf buf = get_free_buffer(); // or block on pl_buf_poll +// // write to the buffer using the external API +// pl_tex_upload(gpu, /* ... buf ... */); // implicitly imports +// pl_buf_export(gpu, buf); +// } +// +// i.e. perform an external API operation, then use and immediately export the +// buffer in libplacebo, and finally wait until `pl_buf_poll` is false before +// re-using it in the external API. (Or get a new buffer in the meantime) +PL_API bool pl_buf_export(pl_gpu gpu, pl_buf buf); + +// Returns whether or not a buffer is currently "in use". This can either be +// because of a pending read operation, a pending write operation or a pending +// buffer export operation. Any access to the buffer by external APIs or via +// the host pointer (for host-mapped buffers) is forbidden while a buffer is +// "in use". The only exception to this rule is multiple reads, for example +// reading from a buffer with `pl_tex_upload` while simultaneously reading from +// it using mapped memory. +// +// The `timeout`, specified in nanoseconds, indicates how long to block for +// before returning. If set to 0, this function will never block, and only +// returns the current status of the buffer. The actual precision of the +// timeout may be significantly longer than one nanosecond, and has no upper +// bound. This function does not provide hard latency guarantees. This function +// may also return at any time, even if the buffer is still in use. If the user +// wishes to block until the buffer is definitely no longer in use, the +// recommended usage is: +// +// while (pl_buf_poll(gpu, buf, UINT64_MAX)) +// ; // do nothing +// +// Note: libplacebo operations on buffers are always internally synchronized, +// so this is only needed for host-mapped or externally exported buffers. +// However, it may be used to do non-blocking queries before calling blocking +// functions such as `pl_buf_read`. +// +// Note: If `pl_gpu_limits.thread_safe` is set, this function is implicitly +// synchronized, meaning it can safely be called on a `pl_buf` that is in use +// by another thread. +PL_API bool pl_buf_poll(pl_gpu gpu, pl_buf buf, uint64_t timeout); + +enum pl_tex_sample_mode { + PL_TEX_SAMPLE_NEAREST, // nearest neighbour sampling + PL_TEX_SAMPLE_LINEAR, // linear filtering, requires PL_FMT_CAP_LINEAR + PL_TEX_SAMPLE_MODE_COUNT, +}; + +enum pl_tex_address_mode { + PL_TEX_ADDRESS_CLAMP, // clamp the nearest edge texel + PL_TEX_ADDRESS_REPEAT, // repeat (tile) the texture + PL_TEX_ADDRESS_MIRROR, // repeat (mirror) the texture + PL_TEX_ADDRESS_MODE_COUNT, +}; + +// Structure describing a texture. +struct pl_tex_params { + int w, h, d; // physical dimension; unused dimensions must be 0 + pl_fmt format; + + // The following bools describe what operations can be performed. The + // corresponding pl_fmt capability must be set for every enabled + // operation type. + // + // Note: For planar formats, it is also possible to set capabilities only + // supported by sub-planes. In this case, the corresponding functionality + // will be available for the sub-plane, but not the planar texture itself. + bool sampleable; // usable as a PL_DESC_SAMPLED_TEX + bool renderable; // usable as a render target (pl_pass_run) + // (must only be used with 2D textures) + bool storable; // usable as a storage image (PL_DESC_IMG_*) + bool blit_src; // usable as a blit source + bool blit_dst; // usable as a blit destination + bool host_writable; // may be updated with pl_tex_upload() + bool host_readable; // may be fetched with pl_tex_download() + + // Note: For `blit_src`, `blit_dst`, the texture must either be + // 2-dimensional or `pl_gpu_limits.blittable_1d_3d` must be set. + + // At most one of `export_handle` and `import_handle` can be set for a + // texture. + + // Setting this indicates that the memory backing this texture should be + // shared with external APIs, If so, this must be exactly *one* of + // `pl_gpu.export_caps.tex`. + enum pl_handle_type export_handle; + + // Setting this indicates that the memory backing this texture will be + // imported from an external API. If so, this must be exactly *one* of + // `pl_gpu.import_caps.tex`. Mutually exclusive with `initial_data`. + enum pl_handle_type import_handle; + + // If the shared memory is being imported, the import handle must be + // specified here. Otherwise, this is ignored. + struct pl_shared_mem shared_mem; + + // If non-NULL, the texture will be created with these contents (tightly + // packed). Using this does *not* require setting host_writable. Otherwise, + // the initial data is undefined. Mutually exclusive with `import_handle`. + const void *initial_data; + + // Arbitrary user data. libplacebo does not use this at all. + void *user_data; + + // Arbitrary identifying tag. Used only for debugging purposes. + pl_debug_tag debug_tag; +}; + +#define pl_tex_params(...) (&(struct pl_tex_params) { \ + .debug_tag = PL_DEBUG_TAG, \ + __VA_ARGS__ \ + }) + +static inline int pl_tex_params_dimension(const struct pl_tex_params params) +{ + return params.d ? 3 : params.h ? 2 : 1; +} + +enum pl_sampler_type { + PL_SAMPLER_NORMAL, // gsampler2D, gsampler3D etc. + PL_SAMPLER_RECT, // gsampler2DRect + PL_SAMPLER_EXTERNAL, // gsamplerExternalOES + PL_SAMPLER_EXTERNAL_YUV, // __samplerExternal2DY2YEXT (raw YUV) + PL_SAMPLER_TYPE_COUNT, +}; + +// Conflates the following typical GPU API concepts: +// - texture itself +// - sampler state +// - staging buffers for texture upload +// - framebuffer objects +// - wrappers for swapchain framebuffers +// - synchronization needed for upload/rendering/etc. +// +// Essentially a pl_tex can be anything ranging from a normal texture, a wrapped +// external/real framebuffer, a framebuffer object + texture pair, a mapped +// texture (via pl_hwdec), or other sorts of things that can be sampled from +// and/or rendered to. +// +// Thread-safety: Unsafe +typedef const struct pl_tex_t *pl_tex; +struct pl_tex_t { + struct pl_tex_params params; + + // If `params.format` is a planar format, this contains `pl_tex` handles + // encapsulating individual texture planes. Conversely, if this is a + // sub-plane of a planar texture, `parent` points to the planar texture. + // + // Note: Calling `pl_tex_destroy` on sub-planes is undefined behavior. + pl_tex planes[4]; + pl_tex parent; + + // If `params.export_handle` is set, this structure references the shared + // memory backing this buffer, via the requested handle type. + // + // While this texture is not in an "exported" state, the contents of the + // memory are undefined. (See: `pl_tex_export`) + // + // Note: Due to vulkan driver limitations, `shared_mem.drm_format_mod` will + // currently always be set to DRM_FORMAT_MOD_INVALID. No guarantee can be + // made about the cross-driver compatibility of textures exported this way. + struct pl_shared_mem shared_mem; + + // If `params.sampleable` is true, this indicates the correct sampler type + // to use when sampling from this texture. + enum pl_sampler_type sampler_type; + + // Backend-specific sampler identity. A non-zero value means render passes + // must be specialized for the immutable sampler attached to this texture. + uint64_t sampler_signature; +}; + +// Create a texture (with undefined contents). Returns NULL on failure. This is +// assumed to be an expensive/rare operation, and may need to perform memory +// allocation or framebuffer creation. +PL_API pl_tex pl_tex_create(pl_gpu gpu, const struct pl_tex_params *params); +PL_API void pl_tex_destroy(pl_gpu gpu, pl_tex *tex); + +// This works like `pl_tex_create`, but if the texture already exists and has +// incompatible texture parameters, it will get destroyed first. A texture is +// considered "compatible" if it has the same texture format and sample/address +// mode and it supports a superset of the features the user requested. +// +// Even if the texture is not recreated, calling this function will still +// invalidate the contents of the texture. (Note: Because of this, +// `initial_data` may not be used with `pl_tex_recreate`. Doing so is an error) +// +// Note: If the `user_data` alone changes, this does not trigger a texture +// recreation. In theory, this can be used to detect when the texture ended +// up being recreated. +PL_API bool pl_tex_recreate(pl_gpu gpu, pl_tex *tex, const struct pl_tex_params *params); + +// Invalidates the contents of a texture. After this, the contents are fully +// undefined. +PL_API void pl_tex_invalidate(pl_gpu gpu, pl_tex tex); + +union pl_clear_color { + float f[4]; + int32_t i[4]; + uint32_t u[4]; +}; + +// Clear the dst texture with the given color (rgba). This is functionally +// identical to a blit operation, which means `dst->params.blit_dst` must be +// set. +PL_API void pl_tex_clear_ex(pl_gpu gpu, pl_tex dst, const union pl_clear_color color); + +// Wrapper for `pl_tex_clear_ex` which only works for floating point textures. +PL_API void pl_tex_clear(pl_gpu gpu, pl_tex dst, const float color[4]); + +struct pl_tex_blit_params { + // The texture to blit from. Must have `params.blit_src` enabled. + pl_tex src; + + // The texture to blit to. Must have `params.blit_dst` enabled, and a + // format that is loosely compatible with `src`. This essentially means + // that they must have the same `internal_size`. Additionally, UINT + // textures can only be blitted to other UINT textures, and SINT textures + // can only be blitted to other SINT textures. + pl_tex dst; + + // The region of the source texture to blit. Must be within the texture + // bounds of `src`. May be flipped. (Optional) + pl_rect3d src_rc; + + // The region of the destination texture to blit into. Must be within the + // texture bounds of `dst`. May be flipped. Areas outside of `dst_rc` in + // `dst` are preserved. (Optional) + pl_rect3d dst_rc; + + // If `src_rc` and `dst_rc` have different sizes, the texture will be + // scaled using the given texture sampling mode. + enum pl_tex_sample_mode sample_mode; +}; + +#define pl_tex_blit_params(...) (&(struct pl_tex_blit_params) { __VA_ARGS__ }) + +// Copy a sub-rectangle from one texture to another. +PL_API void pl_tex_blit(pl_gpu gpu, const struct pl_tex_blit_params *params); + +// Structure describing a texture transfer operation. +struct pl_tex_transfer_params { + // Texture to transfer to/from. Depending on the type of the operation, + // this must have params.host_writable (uploads) or params.host_readable + // (downloads) set, respectively. + pl_tex tex; + + // Note: Superfluous parameters are ignored, i.e. for a 1D texture, the y + // and z fields of `rc`, as well as the corresponding pitches, are ignored. + // In all other cases, the pitch must be large enough to contain the + // corresponding dimension of `rc`, and the `rc` must be normalized and + // fully contained within the image dimensions. Missing fields in the `rc` + // are inferred from the image size. If unset, the pitch is inferred + // from `rc` (that is, it's assumed that the data is tightly packed in the + // buffer). Otherwise, `row_pitch` *must* be a multiple of + // `tex->params.format->texel_align`, and `depth_pitch` must be a multiple + // of `row_pitch`. + pl_rect3d rc; // region of the texture to transfer + size_t row_pitch; // the number of bytes separating image rows + size_t depth_pitch; // the number of bytes separating image planes + + // An optional timer to report the approximate duration of the texture + // transfer to. Note that this is only an approximation, since the actual + // texture transfer may happen entirely in the background (in particular, + // for implementations with asynchronous transfer capabilities). It's also + // not guaranteed that all GPUs support this. + pl_timer timer; + + // An optional callback to fire after the operation completes. If this is + // specified, then the operation is performed asynchronously. Note that + // transfers to/from buffers are always asynchronous, even without, this + // field, so it's more useful for `ptr` transfers. (Though it can still be + // helpful to avoid having to manually poll buffers all the time) + // + // When this is *not* specified, uploads from `ptr` are either synchronous, + // or internally asynchronous but with an extra host memcpy, while + // downloads from `ptr` are blocking. As such, it's recommended to always + // try using asynchronous texture transfers wherever possible. + // + // Note: Requires `pl_gpu_limits.callbacks` + // + // Note: Callbacks are implicitly synchronized, meaning that callbacks are + // guaranteed to never execute concurrently with other callbacks. However, + // they may execute from any thread that the `pl_gpu` is used on. + void (*callback)(void *priv); + void *priv; // arbitrary user data + + // For the data source/target of a transfer operation, there are two valid + // options: + // + // 1. Transferring to/from a buffer: (requires `pl_gpu_limits.buf_transfer`) + pl_buf buf; // buffer to use + size_t buf_offset; // offset of data within buffer, should be a + // multiple of `tex->params.format->texel_size` + // 2. Transferring to/from host memory directly: + void *ptr; // address of data + bool no_import; // always use memcpy, bypassing host ptr import + + // Note: The contents of the memory region / buffer must exactly match the + // texture format; i.e. there is no explicit conversion between formats. +}; + +#define pl_tex_transfer_params(...) (&(struct pl_tex_transfer_params) { __VA_ARGS__ }) + +// Upload data to a texture. Returns whether successful. +PL_API bool pl_tex_upload(pl_gpu gpu, const struct pl_tex_transfer_params *params); + +// Download data from a texture. Returns whether successful. +PL_API bool pl_tex_download(pl_gpu gpu, const struct pl_tex_transfer_params *params); + +// Returns whether or not a texture is currently "in use". This can either be +// because of a pending read operation, a pending write operation or a pending +// texture export operation. Note that this function's usefulness is extremely +// limited under ordinary circumstances. In practically all cases, textures do +// not need to be directly synchronized by the user, except when interfacing +// with external libraries. This function should NOT, however, be used as a +// crutch to avoid having to implement semaphore-based synchronization. Use +// the API-specific functions such as `pl_vulkan_hold/release` for that. +// +// A good example of a use case in which this function is required is when +// interoperating with external memory management that needs to know when an +// imported texture is safe to free / reclaim internally, in which case +// semaphores are insufficient because memory management is a host operation. +// +// The `timeout`, specified in nanoseconds, indicates how long to block for +// before returning. If set to 0, this function will never block, and only +// returns the current status of the texture. The actual precision of the +// timeout may be significantly longer than one nanosecond, and has no upper +// bound. This function does not provide hard latency guarantees. This function +// may also return at any time, even if the texture is still in use. If the +// user wishes to block until the texture is definitely no longer in use, the +// recommended usage is: +// +// while (pl_tex_poll(gpu, buf, UINT64_MAX)) +// ; // do nothing +// +// Note: If `pl_gpu_limits.thread_safe` is set, this function is implicitly +// synchronized, meaning it can safely be called on a `pl_tex` that is in use +// by another thread. +PL_API bool pl_tex_poll(pl_gpu gpu, pl_tex tex, uint64_t timeout); + +// Data type of a shader input variable (e.g. uniform, or UBO member) +enum pl_var_type { + PL_VAR_INVALID = 0, + PL_VAR_SINT, // C: int GLSL: int/ivec + PL_VAR_UINT, // C: unsigned int GLSL: uint/uvec + PL_VAR_FLOAT, // C: float GLSL: float/vec/mat + PL_VAR_TYPE_COUNT +}; + +// Returns the host size (in bytes) of a pl_var_type. +PL_API size_t pl_var_type_size(enum pl_var_type type); + +// Represents a shader input variable (concrete data, e.g. vector, matrix) +struct pl_var { + const char *name; // name as used in the shader + enum pl_var_type type; + // The total number of values is given by dim_v * dim_m. For example, a + // vec2 would have dim_v = 2 and dim_m = 1. A mat3x4 would have dim_v = 4 + // and dim_m = 3. + int dim_v; // vector dimension + int dim_m; // matrix dimension (number of columns, see below) + int dim_a; // array dimension +}; + +// Helper functions for constructing the most common pl_vars, with names +// corresponding to their corresponding GLSL built-in types. +PL_API struct pl_var pl_var_float(const char *name); +PL_API struct pl_var pl_var_vec2(const char *name); +PL_API struct pl_var pl_var_vec3(const char *name); +PL_API struct pl_var pl_var_vec4(const char *name); +PL_API struct pl_var pl_var_mat2(const char *name); +PL_API struct pl_var pl_var_mat2x3(const char *name); +PL_API struct pl_var pl_var_mat2x4(const char *name); +PL_API struct pl_var pl_var_mat3(const char *name); +PL_API struct pl_var pl_var_mat3x4(const char *name); +PL_API struct pl_var pl_var_mat4x2(const char *name); +PL_API struct pl_var pl_var_mat4x3(const char *name); +PL_API struct pl_var pl_var_mat4(const char *name); +PL_API struct pl_var pl_var_int(const char *name); +PL_API struct pl_var pl_var_ivec2(const char *name); +PL_API struct pl_var pl_var_ivec3(const char *name); +PL_API struct pl_var pl_var_ivec4(const char *name); +PL_API struct pl_var pl_var_uint(const char *name); +PL_API struct pl_var pl_var_uvec2(const char *name); +PL_API struct pl_var pl_var_uvec3(const char *name); +PL_API struct pl_var pl_var_uvec4(const char *name); + +struct pl_named_var { + const char *glsl_name; + struct pl_var var; +}; + +// The same list as above, tagged by name and terminated with a {0} entry. +PL_API extern const struct pl_named_var pl_var_glsl_types[]; + +// Efficient helper function for performing a lookup in the above array. +// Returns NULL if the variable is not legal. Note that the array dimension is +// ignored, since it's usually part of the variable name and not the type name. +PL_API const char *pl_var_glsl_type_name(struct pl_var var); + +// Converts a pl_fmt to an "equivalent" pl_var. Equivalent in this sense means +// that the pl_var's type will be the same as the vertex's sampled type (e.g. +// PL_FMT_UNORM gets turned into PL_VAR_FLOAT). +PL_API struct pl_var pl_var_from_fmt(pl_fmt fmt, const char *name); + +// Describes the memory layout of a variable, relative to some starting location +// (typically the offset within a uniform/storage/pushconstant buffer) +// +// Note on matrices: All GPUs expect column major matrices, for both buffers and +// input variables. Care needs to be taken to avoid trying to use e.g. a +// pl_matrix3x3 (which is row major) directly as a pl_var_update.data! +// +// In terms of the host layout, a column-major matrix (e.g. matCxR) with C +// columns and R rows is treated like an array vecR[C]. The `stride` here refers +// to the separation between these array elements, i.e. the separation between +// the individual columns. +// +// Visualization of a mat4x3: +// +// 0 1 2 3 <- columns +// 0 [ (A) (D) (G) (J) ] +// 1 [ (B) (E) (H) (K) ] +// 2 [ (C) (F) (I) (L) ] +// ^ rows +// +// Layout in GPU memory: (stride=16, size=60) +// +// [ A B C ] X <- column 0, offset +0 +// [ D E F ] X <- column 1, offset +16 +// [ G H I ] X <- column 2, offset +32 +// [ J K L ] <- column 3, offset +48 +// +// Note the lack of padding on the last column in this example. +// In general: size <= stride * dim_m +// +// C representation: (stride=12, size=48) +// +// { { A, B, C }, +// { D, E, F }, +// { G, H, I }, +// { J, K, L } } +// +// Note on arrays: `stride` represents both the stride between elements of a +// matrix, and the stride between elements of an array. That is, there is no +// distinction between the columns of a matrix and the rows of an array. For +// example, a mat2[10] and a vec2[20] share the same pl_var_layout - the stride +// would be sizeof(vec2) and the size would be sizeof(vec2) * 2 * 10. +// +// For non-array/matrix types, `stride` is equal to `size`. + +struct pl_var_layout { + size_t offset; // the starting offset of the first byte + size_t stride; // the delta between two elements of an array/matrix + size_t size; // the total size of the input +}; + +// Returns the host layout of an input variable as required for a +// tightly-packed, byte-aligned C data type, given a starting offset. +PL_API struct pl_var_layout pl_var_host_layout(size_t offset, const struct pl_var *var); + +// Returns the GLSL std140 layout of an input variable given a current buffer +// offset, as required for a buffer descriptor of type PL_DESC_BUF_UNIFORM +// +// The normal way to use this function is when calculating the size and offset +// requirements of a uniform buffer in an incremental fashion, to calculate the +// new offset of the next variable in this buffer. +PL_API struct pl_var_layout pl_std140_layout(size_t offset, const struct pl_var *var); + +// Returns the GLSL std430 layout of an input variable given a current buffer +// offset, as required for a buffer descriptor of type PL_DESC_BUF_STORAGE, and +// for push constants. +PL_API struct pl_var_layout pl_std430_layout(size_t offset, const struct pl_var *var); + +// Convenience definitions / friendly names for these +#define pl_buf_uniform_layout pl_std140_layout +#define pl_buf_storage_layout pl_std430_layout +#define pl_push_constant_layout pl_std430_layout + +// Like memcpy, but copies bytes from `src` to `dst` in a manner governed by +// the stride and size of `dst_layout` as well as `src_layout`. Also takes +// into account the respective `offset`. +PL_API void memcpy_layout(void *dst, struct pl_var_layout dst_layout, + const void *src, struct pl_var_layout src_layout); + +// Represents a compile-time constant. +struct pl_constant { + enum pl_var_type type; // constant data type + uint32_t id; // GLSL `constant_id` + size_t offset; // byte offset in `constant_data` +}; + +// Represents a vertex attribute. +struct pl_vertex_attrib { + const char *name; // name as used in the shader + pl_fmt fmt; // data format (must have PL_FMT_CAP_VERTEX) + size_t offset; // byte offset into the vertex struct + int location; // vertex location (as used in the shader) +}; + +// Returns an abstract namespace index for a given descriptor type. This will +// always be a value >= 0 and < PL_DESC_TYPE_COUNT. Implementations can use +// this to figure out which descriptors may share the same value of `binding`. +// Bindings must only be unique for all descriptors within the same namespace. +PL_API int pl_desc_namespace(pl_gpu gpu, enum pl_desc_type type); + +// Access mode of a shader input descriptor. +enum pl_desc_access { + PL_DESC_ACCESS_READWRITE, + PL_DESC_ACCESS_READONLY, + PL_DESC_ACCESS_WRITEONLY, + PL_DESC_ACCESS_COUNT, +}; + +// Returns the GLSL syntax for a given access mode (e.g. "readonly"). +PL_API const char *pl_desc_access_glsl_name(enum pl_desc_access mode); + +// Represents a shader descriptor (e.g. texture or buffer binding) +struct pl_desc { + const char *name; // name as used in the shader + enum pl_desc_type type; + + // The binding of this descriptor, as used in the shader. All bindings + // within a namespace must be unique. (see: pl_desc_namespace) + int binding; + + // For storage images and storage buffers, this can be used to restrict + // the type of access that may be performed on the descriptor. Ignored for + // the other descriptor types (uniform buffers and sampled textures are + // always read-only). + enum pl_desc_access access; + + // Static sampler state used while creating sampled-texture descriptors. + // `sampler_signature` is zero for ordinary dynamically bound samplers. + uint64_t sampler_signature; + enum pl_tex_address_mode address_mode; + enum pl_tex_sample_mode sample_mode; +}; + +// Framebuffer blending mode (for raster passes) +enum pl_blend_mode { + PL_BLEND_ZERO, + PL_BLEND_ONE, + PL_BLEND_SRC_ALPHA, + PL_BLEND_ONE_MINUS_SRC_ALPHA, + PL_BLEND_MODE_COUNT, +}; + +struct pl_blend_params { + enum pl_blend_mode src_rgb; + enum pl_blend_mode dst_rgb; + enum pl_blend_mode src_alpha; + enum pl_blend_mode dst_alpha; +}; + +#define pl_blend_params(...) (&(struct pl_blend_params) { __VA_ARGS__ }) + +// Typical alpha compositing +PL_API extern const struct pl_blend_params pl_alpha_overlay; + +enum pl_prim_type { + PL_PRIM_TRIANGLE_LIST, + PL_PRIM_TRIANGLE_STRIP, + PL_PRIM_TYPE_COUNT, +}; + +enum pl_index_format { + PL_INDEX_UINT16 = 0, + PL_INDEX_UINT32, + PL_INDEX_FORMAT_COUNT, +}; + +enum pl_pass_type { + PL_PASS_INVALID = 0, + PL_PASS_RASTER, // vertex+fragment shader + PL_PASS_COMPUTE, // compute shader (requires `pl_gpu.glsl.compute`) + PL_PASS_TYPE_COUNT, +}; + +// Description of a rendering pass. It conflates the following: +// - GLSL shader(s) and its list of inputs +// - target parameters (for raster passes) +struct pl_pass_params { + enum pl_pass_type type; + + // Input variables. + struct pl_var *variables; + int num_variables; + + // Input descriptors. + struct pl_desc *descriptors; + int num_descriptors; + + // Compile-time specialization constants. + struct pl_constant *constants; + int num_constants; + + // Initial data for the specialization constants. Optional. If NULL, + // specialization constants receive the values from the shader text. + void *constant_data; + + // Push constant region. Must be be a multiple of 4 <= limits.max_pushc_size + size_t push_constants_size; + + // The shader text in GLSL. For PL_PASS_RASTER, this is interpreted + // as a fragment shader. For PL_PASS_COMPUTE, this is interpreted as + // a compute shader. + const char *glsl_shader; + + // --- type==PL_PASS_RASTER only + + // Describes the interpretation and layout of the vertex data. + enum pl_prim_type vertex_type; + struct pl_vertex_attrib *vertex_attribs; + int num_vertex_attribs; + size_t vertex_stride; // must be a multiple of limits.align_vertex_stride + + // The vertex shader itself. + const char *vertex_shader; + + // Target format. The format must support PL_FMT_CAP_RENDERABLE. The + // resulting pass may only be used on textures that have a format with a + // `pl_fmt.signature` compatible to this format. + pl_fmt target_format; + + // Target blending mode. If this is NULL, blending is disabled. Otherwise, + // the `target_format` must also support PL_FMT_CAP_BLENDABLE. + const struct pl_blend_params *blend_params; + + // If false, the target's existing contents will be discarded before the + // pass is run. (Semantically equivalent to calling pl_tex_invalidate + // before every pl_pass_run, but slightly more efficient) + // + // Specifying `blend_params` requires `load_target` to be true. + bool load_target; + + // --- Deprecated / removed fields. + PL_DEPRECATED_IN(v6.322) const uint8_t *cached_program; // Non-functional + PL_DEPRECATED_IN(v6.322) size_t cached_program_len; +}; + +#define pl_pass_params(...) (&(struct pl_pass_params) { __VA_ARGS__ }) + +// Conflates the following typical GPU API concepts: +// - various kinds of shaders +// - rendering pipelines +// - descriptor sets, uniforms, other bindings +// - all synchronization necessary +// - the current values of all inputs +// +// Thread-safety: Unsafe +typedef const struct pl_pass_t { + struct pl_pass_params params; +} *pl_pass; + +// Compile a shader and create a render pass. This is a rare/expensive +// operation and may take a significant amount of time, even if a cached +// program is used. Returns NULL on failure. +PL_API pl_pass pl_pass_create(pl_gpu gpu, const struct pl_pass_params *params); +PL_API void pl_pass_destroy(pl_gpu gpu, pl_pass *pass); + +struct pl_desc_binding { + const void *object; // pl_* object with type corresponding to pl_desc_type + + // For PL_DESC_SAMPLED_TEX, this can be used to configure the sampler. + enum pl_tex_address_mode address_mode; + enum pl_tex_sample_mode sample_mode; +}; + +struct pl_var_update { + int index; // index into params.variables[] + const void *data; // pointer to raw byte data corresponding to pl_var_host_layout() +}; + +struct pl_pass_run_params { + pl_pass pass; + + // If present, the shader will be re-specialized with the new constants + // provided. This is a significantly cheaper operation than recompiling a + // brand new shader, but should still be avoided if possible. + // + // Leaving it as NULL re-uses the existing specialization values. Ignored + // if the shader has no specialization constants. Guaranteed to be a no-op + // if the values have not changed since the last invocation. + void *constant_data; + + // This list only contains descriptors/variables which have changed + // since the previous invocation. All non-mentioned variables implicitly + // preserve their state from the last invocation. + struct pl_var_update *var_updates; + int num_var_updates; + + // This list contains all descriptors used by this pass. It must + // always be filled, even if the descriptors haven't changed. The order + // must match that of pass->params.descriptors + struct pl_desc_binding *desc_bindings; + + // The push constants for this invocation. This must always be set and + // fully defined for every invocation if params.push_constants_size > 0. + void *push_constants; + + // An optional timer to report the approximate runtime of this shader pass + // invocation to. Note that this is only an approximation, since shaders + // may overlap their execution times and contend for GPU time. + pl_timer timer; + + // --- pass->params.type==PL_PASS_RASTER only + + // Target must be a 2D texture, `target->params.renderable` must be true, + // and `target->params.format->signature` must match the signature provided + // in `pass->params.target_format`. + // + // If the viewport or scissors are left blank, they are inferred from + // target->params. + // + // WARNING: Rendering to a *target that is being read from by the same + // shader is undefined behavior. In general, trying to bind the same + // resource multiple times to the same shader is undefined behavior. + pl_tex target; + pl_rect2d viewport; // screen space viewport (must be normalized) + pl_rect2d scissors; // target render scissors (must be normalized) + + // Number of vertices to render + int vertex_count; + + // Vertex data may be provided in one of two forms: + // + // 1. Drawing from host memory directly + const void *vertex_data; + // 2. Drawing from a vertex buffer (requires `vertex_buf->params.drawable`) + pl_buf vertex_buf; + size_t buf_offset; + + // (Optional) Index data may be provided in the form given by `index_fmt`. + // These will be used for instanced rendering. Similar to vertex data, this + // can be provided in two forms: + // 1. From host memory + const void *index_data; + enum pl_index_format index_fmt; + // 2. From an index buffer (requires `index_buf->params.drawable`) + pl_buf index_buf; + size_t index_offset; + // Note: Drawing from an index buffer requires vertex data to also be + // present in buffer form, i.e. it's forbidden to mix `index_buf` with + // `vertex_data` (though vice versa is allowed). + + // --- pass->params.type==PL_PASS_COMPUTE only + + // Number of work groups to dispatch per dimension (X/Y/Z). Must be <= the + // corresponding index of limits.max_dispatch + int compute_groups[3]; +}; + +#define pl_pass_run_params(...) (&(struct pl_pass_run_params) { __VA_ARGS__ }) + +// Execute a render pass. +PL_API void pl_pass_run(pl_gpu gpu, const struct pl_pass_run_params *params); + +// This is semantically a no-op, but it provides a hint that you want to flush +// any partially queued up commands and begin execution. There is normally no +// need to call this, because queued commands will always be implicitly flushed +// whenever necessary to make forward progress on commands like `pl_buf_poll`, +// or when submitting a frame to a swapchain for display. In fact, calling this +// function can negatively impact performance, because some GPUs rely on being +// able to re-order and modify queued commands in order to enable optimizations +// retroactively. +// +// The only time this might be beneficial to call explicitly is if you're doing +// lots of offline processing, i.e. you aren't rendering to a swapchain but to +// textures that you download from again. In that case you should call this +// function after each "work item" to ensure good parallelism between them. +// +// It's worth noting that this function may block if you're over-feeding the +// GPU without waiting for existing results to finish. +PL_API void pl_gpu_flush(pl_gpu gpu); + +// This is like `pl_gpu_flush` but also blocks until the GPU is fully idle +// before returning. Using this in your rendering loop is seriously disadvised, +// and almost never the right solution. The intended use case is for deinit +// logic, where users may want to force the all pending GPU operations to +// finish so they can clean up their state more easily. +// +// After this operation is called, it's guaranteed that all pending buffer +// operations are complete - i.e. `pl_buf_poll` is guaranteed to return false. +// It's also guaranteed that any outstanding timer query results are available. +// +// Note: If you only care about buffer operations, you can accomplish this more +// easily by using `pl_buf_poll` with the timeout set to `UINT64_MAX`. But if +// you have many buffers it may be more convenient to call this function +// instead. The difference is that this function will also affect e.g. renders +// to a `pl_swapchain`. +PL_API void pl_gpu_finish(pl_gpu gpu); + +// Returns true if the GPU is considered to be in a "failed" state, which +// during normal operation is typically the result of things like the device +// being lost (due to e.g. power management). +// +// If this returns true, users *should* destroy and recreate the `pl_gpu`, +// including all associated resources, via the appropriate mechanism. +PL_API bool pl_gpu_is_failed(pl_gpu gpu); + +PL_API_END + +#endif // LIBPLACEBO_GPU_H_ diff --git a/third_party/exo-dv5-native/include/libplacebo/log.h b/third_party/exo-dv5-native/include/libplacebo/log.h new file mode 100644 index 0000000000..b24c931233 --- /dev/null +++ b/third_party/exo-dv5-native/include/libplacebo/log.h @@ -0,0 +1,113 @@ +/* + * This file is part of libplacebo. + * + * libplacebo is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libplacebo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with libplacebo. If not, see . + */ + +#ifndef LIBPLACEBO_LOG_H_ +#define LIBPLACEBO_LOG_H_ + +#include +#include + +PL_API_BEGIN + +// The log level associated with a given log message. +enum pl_log_level { + PL_LOG_NONE = 0, + PL_LOG_FATAL, // results in total loss of function of a major component + PL_LOG_ERR, // serious error; may result in degraded function + PL_LOG_WARN, // warning; potentially bad, probably user-relevant + PL_LOG_INFO, // informational message, also potentially harmless errors + PL_LOG_DEBUG, // verbose debug message, informational + PL_LOG_TRACE, // very noisy trace of activity,, usually benign + PL_LOG_ALL = PL_LOG_TRACE, +}; + +struct pl_log_params { + // Logging callback. All messages, informational or otherwise, will get + // redirected to this callback. The logged messages do not include trailing + // newlines. Optional. + void (*log_cb)(void *log_priv, enum pl_log_level level, const char *msg); + void *log_priv; + + // The current log level. Controls the level of message that will be + // redirected to the log callback. Setting this to PL_LOG_ALL means all + // messages will be forwarded, but doing so indiscriminately can result + // in increased CPU usage as it may enable extra debug paths based on the + // configured log level. + enum pl_log_level log_level; +}; + +#define pl_log_params(...) (&(struct pl_log_params) { __VA_ARGS__ }) +PL_API extern const struct pl_log_params pl_log_default_params; + +// Thread-safety: Safe +// +// Note: In any context in which `pl_log` is used, users may also pass NULL +// to disable logging. In other words, NULL is a valid `pl_log`. +typedef const struct pl_log_t { + struct pl_log_params params; +} *pl_log; + +#define pl_log_glue1(x, y) x##y +#define pl_log_glue2(x, y) pl_log_glue1(x, y) +// Force a link error in the case of linking against an incompatible API +// version. +#define pl_log_create pl_log_glue2(pl_log_create_, PL_API_VER) +// Creates a pl_log. `api_ver` is for historical reasons and ignored currently. +// `params` defaults to `&pl_log_default_params` if left as NULL. +// +// Note: As a general rule, any `params` struct used as an argument to a +// function need only live until the corresponding function returns. +PL_API pl_log pl_log_create(int api_ver, const struct pl_log_params *params); + +// Destroy a `pl_log` object. +// +// Note: As a general rule, all `_destroy` functions take the pointer to the +// object to free as their parameter. This pointer is overwritten by NULL +// afterwards. Calling a _destroy function on &{NULL} is valid, but calling it +// on NULL itself is invalid. +PL_API void pl_log_destroy(pl_log *log); + +// Update the parameters of a `pl_log` without destroying it. This can be +// used to change the log function, log context or log level retroactively. +// `params` defaults to `&pl_log_default_params` if left as NULL. +// +// Returns the previous params, atomically. +PL_API struct pl_log_params pl_log_update(pl_log log, const struct pl_log_params *params); + +// Like `pl_log_update` but only updates the log level, leaving the log +// callback intact. +// +// Returns the previous log level, atomically. +PL_API enum pl_log_level pl_log_level_update(pl_log log, enum pl_log_level level); + +// Two simple, stream-based loggers. You can use these as the log_cb. If you +// also set log_priv to a FILE* (e.g. stdout or stderr) it will be printed +// there; otherwise, it will be printed to stdout or stderr depending on the +// log level. +// +// The version with colors will use ANSI escape sequences to indicate the log +// level. The version without will use explicit prefixes. +PL_API void pl_log_simple(void *stream, enum pl_log_level level, const char *msg); +PL_API void pl_log_color(void *stream, enum pl_log_level level, const char *msg); + +// Backwards compatibility with older versions of libplacebo +#define pl_context pl_log +#define pl_context_params pl_log_params + +PL_API_END + +#endif // LIBPLACEBO_LOG_H_ diff --git a/third_party/exo-dv5-native/include/libplacebo/renderer.h b/third_party/exo-dv5-native/include/libplacebo/renderer.h new file mode 100644 index 0000000000..08466bd318 --- /dev/null +++ b/third_party/exo-dv5-native/include/libplacebo/renderer.h @@ -0,0 +1,884 @@ +/* + * This file is part of libplacebo. + * + * libplacebo is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libplacebo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with libplacebo. If not, see . + */ + +#ifndef LIBPLACEBO_RENDERER_H_ +#define LIBPLACEBO_RENDERER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +PL_API_BEGIN + +// Thread-safety: Unsafe +typedef struct pl_renderer_t *pl_renderer; + +// Enum values used in pl_renderer_errors_t as a bit positions for error flags +enum pl_render_error { + PL_RENDER_ERR_NONE = 0, + PL_RENDER_ERR_FBO = 1 << 0, + PL_RENDER_ERR_SAMPLING = 1 << 1, + PL_RENDER_ERR_DEBANDING = 1 << 2, + PL_RENDER_ERR_BLENDING = 1 << 3, + PL_RENDER_ERR_OVERLAY = 1 << 4, + PL_RENDER_ERR_PEAK_DETECT = 1 << 5, + PL_RENDER_ERR_FILM_GRAIN = 1 << 6, + PL_RENDER_ERR_FRAME_MIXING = 1 << 7, + PL_RENDER_ERR_DEINTERLACING = 1 << 8, + PL_RENDER_ERR_ERROR_DIFFUSION = 1 << 9, + PL_RENDER_ERR_HOOKS = 1 << 10, + PL_RENDER_ERR_CONTRAST_RECOVERY = 1 << 11, + PL_RENDER_ERR_BLUR = 1 << 12, +}; + +// Struct describing current renderer state, including internal processing errors, +// as well as list of signatures of disabled hooks. +struct pl_render_errors { + enum pl_render_error errors; + // List containing signatures of disabled hooks + const uint64_t *disabled_hooks; + int num_disabled_hooks; +}; + +// Creates a new renderer object, which is backed by a GPU context. This is a +// high-level object that takes care of the rendering chain as a whole, from +// the source textures to the finished frame. +PL_API pl_renderer pl_renderer_create(pl_log log, pl_gpu gpu); +PL_API void pl_renderer_destroy(pl_renderer *rr); + +// Returns current renderer state, see pl_render_errors. +PL_API struct pl_render_errors pl_renderer_get_errors(pl_renderer rr); + +// Clears errors state of renderer. If `errors` is NULL, all render errors will +// be cleared. Otherwise only selected errors/hooks will be cleared. +// If `PL_RENDER_ERR_HOOKS` is set and `num_disabled_hooks` is 0, clear all hooks. +// Otherwise only selected hooks will be cleard based on `disabled_hooks` array. +PL_API void pl_renderer_reset_errors(pl_renderer rr, + const struct pl_render_errors *errors); + +enum pl_lut_type { + PL_LUT_UNKNOWN = 0, + PL_LUT_NATIVE, // applied to raw image contents (after fixing bit depth) + PL_LUT_NORMALIZED, // applied to normalized (HDR) RGB values + PL_LUT_CONVERSION, // LUT fully replaces color conversion + + // Note: When using a PL_LUT_CONVERSION to replace the YUV->RGB conversion, + // `pl_render_params.color_adjustment` is no longer applied. Similarly, + // when using a PL_LUT_CONVERSION to replace the image->target color space + // conversion, `pl_render_params.color_map_params` are ignored. + // + // Note: For LUTs attached to the output frame, PL_LUT_CONVERSION should + // instead perform the inverse (RGB->native) conversion. + // + // Note: PL_LUT_UNKNOWN tries inferring the meaning of the LUT from the + // LUT's tagged metadata, and otherwise falls back to PL_LUT_NATIVE. +}; + +enum pl_clear_mode { + PL_CLEAR_COLOR = 0, // set texture to a solid color + PL_CLEAR_TILES, // set texture to a tiled pattern + PL_CLEAR_SKIP, // skip the clearing pass (no-op) + PL_CLEAR_BLUR, // clear with a blurred copy of the image (border only) + PL_CLEAR_MODE_COUNT, +}; + +enum pl_render_stage { + PL_RENDER_STAGE_FRAME, // full frame redraws, for fresh/uncached frames + PL_RENDER_STAGE_BLEND, // the output blend pass (only for pl_render_image_mix) + PL_RENDER_STAGE_COUNT, +}; + +struct pl_render_info { + const struct pl_dispatch_info *pass; // information about the shader + enum pl_render_stage stage; // the associated render stage + + // This specifies the chronological index of this pass within the frame and + // stage (starting at `index == 0`). + int index; + + // For PL_RENDER_STAGE_BLEND, this specifies the number of frames + // being blended (since that results in a different shader). + int count; +}; + +// Represents the options used for rendering. These affect the quality of +// the result. +struct pl_render_params { + // Configures the algorithms used for upscaling and downscaling, + // respectively. If left as NULL, then libplacebo will only use inexpensive + // sampling (bilinear or nearest neighbour depending on the capabilities + // of the hardware / texture). + // + // Note: Setting `downscaler` to NULL also implies `skip_anti_aliasing`, + // since the built-in GPU sampling algorithms can't anti-alias. + // + // Note: If set to the same address as the built-in `pl_filter_bicubic`, + // `pl_filter_nearest` etc.; libplacebo will also use the more efficient + // direct sampling algorithm where possible without quality loss. + const struct pl_filter_config *upscaler; + const struct pl_filter_config *downscaler; + + // If set, this overrides the value of `upscaler`/`downscaling` for + // subsampled (chroma) planes. These scalers are used whenever the size of + // multiple different `pl_plane`s in a single `pl_frame` differ, requiring + // adaptation when converting to/from RGB. Note that a value of NULL simply + // means "no override". To force built-in scaling explicitly, set this to + // `&pl_filter_bilinear`. + const struct pl_filter_config *plane_upscaler; + const struct pl_filter_config *plane_downscaler; + + // The anti-ringing strength to apply to filters. See the equivalent option + // in `pl_sample_filter_params` for more information. + float antiringing_strength; + + // Configures the algorithm used for frame mixing (when using + // `pl_render_image_mix`). Ignored otherwise. As a special requirement, + // this must be a filter config with `polar` set to false, since it's only + // used for 1D mixing and thus only 1D filters are compatible. + // + // If set to NULL, frame mixing is disabled, in which case + // `pl_render_image_mix` will use nearest-neighbour semantics. (Note that + // this still goes through the redraw cache, unless you also enable + // `skip_caching_single_frame`) + const struct pl_filter_config *frame_mixer; + + // Configures the settings used to deband source textures. Leaving this as + // NULL disables debanding. + // + // Note: The `deband_params.grain` setting is automatically adjusted to + // prevent blowing up on HDR sources. The user need not account for this. + const struct pl_deband_params *deband_params; + + // Configures the settings used to sigmoidize the image before upscaling. + // This is not always used. If NULL, disables sigmoidization. + const struct pl_sigmoid_params *sigmoid_params; + + // Configures the color adjustment parameters used to decode the color. + // This can be used to apply additional artistic settings such as + // desaturation, etc. If NULL, defaults to &pl_color_adjustment_neutral. + const struct pl_color_adjustment *color_adjustment; + + // Configures the settings used to detect the peak of the source content, + // for HDR sources. Has no effect on SDR content. If NULL, peak detection + // is disabled. + const struct pl_peak_detect_params *peak_detect_params; + + // Configures the settings used to tone map from HDR to SDR, or from higher + // gamut to standard gamut content. If NULL, defaults to + // `&pl_color_map_default_params`. + const struct pl_color_map_params *color_map_params; + + // Configures the settings used to dither to the output depth. Leaving this + // as NULL disables dithering. + const struct pl_dither_params *dither_params; + + // Configures the error diffusion kernel to use for error diffusion + // dithering. If set, this will be used instead of `dither_params` whenever + // possible. Leaving this as NULL disables error diffusion. + const struct pl_error_diffusion_kernel *error_diffusion; + + // Configures the settings used to simulate color blindness, if desired. + // If NULL, this feature is disabled. + const struct pl_cone_params *cone_params; + + // Configures output blending. When rendering to the final target, the + // framebuffer contents will be blended using this blend mode. Requires + // that the target format has PL_FMT_CAP_BLENDABLE. NULL disables blending. + const struct pl_blend_params *blend_params; + + // Configures the settings used to deinterlace frames (see + // `pl_frame.field`), if required.. If NULL, deinterlacing is "disabled", + // meaning interlaced frames are rendered as weaved frames instead. + // + // Note: As a consequence of how `pl_frame` represents individual fields, + // and especially when using the `pl_queue`, this will still result in + // frames being redundantly rendered twice. As such, it's highly + // recommended to, instead, fully disable deinterlacing by not marking + // source frames as interlaced in the first place. + const struct pl_deinterlace_params *deinterlace_params; + + // If set, applies an extra distortion matrix to the image, after + // scaling and before presenting it to the screen. Can be used for e.g. + // fractional rotation. + // + // Note: The distortion canvas will be set to the size of `target->crop`, + // so this cannot effectively draw outside the specified target area, + // nor change the aspect ratio of the image. + const struct pl_distort_params *distort_params; + + // List of custom user shaders / hooks. + // See for more information. + const struct pl_hook * const *hooks; + int num_hooks; + + // Color mapping LUT. If present, this will be applied as part of the + // image being rendered, in normalized RGB space. + // + // Note: In this context, PL_LUT_NATIVE means "gamma light" and + // PL_LUT_NORMALIZED means "linear light". For HDR signals, normalized LUTs + // are scaled so 1.0 corresponds to the `pl_color_transfer_nominal_peak`. + // + // Note: A PL_LUT_CONVERSION fully replaces the color adaptation from + // `image` to `target`, including any tone-mapping (if necessary) and ICC + // profiles. It has the same representation as PL_LUT_NATIVE, so in this + // case the input and output are (respectively) non-linear light RGB. + const struct pl_custom_lut *lut; + enum pl_lut_type lut_type; + + // Controls how the image background is drawn for transparent images. + enum pl_clear_mode background; + + // Controls how the remaining empty space in the target is filled up, when + // the image does not span the entire framebuffer. + enum pl_clear_mode border; + + // The color to use for PL_CLEAR_COLOR. + // + // Note: Despite the name, this also affects `border = PL_CLEAR_COLOR`. + float background_color[3]; + float background_transparency; // 0.0 for opaque, 1.0 for fully transparent + + // The color and size to use for PL_CLEAR_TILES + float tile_colors[2][3]; + int tile_size; + + // The blur radius (in pixels) to use for PL_CLEAR_BLUR + float blur_radius; + + // If set to a value above 0.0, the output will be rendered with rounded + // corners, as if an alpha transparency mask had been applied. The value + // indicates the relative fraction of the side length to round - a value + // of 1.0 rounds the corners as much as possible. + float corner_rounding; + + // --- Performance / quality trade-off options: + // These should generally be left off where quality is desired, as they can + // degrade the result quite noticeably; but may be useful for older or + // slower hardware. Note that libplacebo will automatically disable + // advanced features on hardware where they are unsupported, regardless of + // these settings. So only enable them if you need a performance bump. + + // Disables anti-aliasing on downscaling. This will result in moiré + // artifacts and nasty, jagged pixels when downscaling, except for some + // very limited special cases (e.g. bilinear downsampling to exactly 0.5x). + // + // Significantly speeds up downscaling with high downscaling ratios. + bool skip_anti_aliasing; + + // Normally, when the size of the `target` used with `pl_render_image_mix` + // changes, or the render parameters are updated, the internal cache of + // mixed frames must be discarded in order to re-render all required + // frames. Setting this option to `true` will skip the cache invalidation + // and instead re-use the existing frames (with bilinear scaling to the new + // size if necessary), which comes at a quality loss shortly after a + // resize, but should make it much more smooth. + bool preserve_mixing_cache; + + // --- Performance tuning / debugging options + // These may affect performance or may make debugging problems easier, + // but shouldn't have any effect on the quality. + + // Normally, `pl_render_image_mix` will also push single frames through the + // mixer cache, in order to speed up re-draws. Enabling this option + // disables that logic, causing single frames to bypass the cache. (Though + // it will still read from, if they happen to already be cached) + bool skip_caching_single_frame; + + // Disables linearization / sigmoidization before scaling. This might be + // useful when tracking down unexpected image artifacts or excessing + // ringing, but it shouldn't normally be necessary. + bool disable_linear_scaling; + + // Forces the use of the "general" scaling algorithms even when using the + // special-cased built-in presets like `pl_filter_bicubic`. Basically, this + // disables the more efficient implementations in favor of the slower, + // general-purpose ones. + bool disable_builtin_scalers; + + // Forces correction of subpixel offsets (using the configured `upscaler`). + bool correct_subpixel_offsets; + + // Forces the use of dithering, even when rendering to 16-bit FBOs. This is + // generally pretty pointless because most 16-bit FBOs have high enough + // depth that rounding errors are below the human perception threshold, + // but this can be used to test the dither code. + bool force_dither; + + // Disables the gamma-correct dithering logic which normally applies when + // dithering to low bit depths. No real use, outside of testing. + bool disable_dither_gamma_correction; + + // Completely overrides the use of FBOs, as if there were no renderable + // texture format available. This disables most features. + bool disable_fbos; + + // Use only low-bit-depth FBOs (8 bits). Note that this also implies + // disabling linear scaling and sigmoidization. + bool force_low_bit_depth_fbos; + + // If this is true, all shaders will be generated as "dynamic" shaders, + // with any compile-time constants being replaced by runtime-adjustable + // values. This is generally a performance loss, but has the advantage of + // being able to freely change parameters without triggering shader + // recompilations. + // + // It's a good idea to enable while presenting configurable settings to the + // user, but it should be set to false once those values are "dialed in". + bool dynamic_constants; + + // This callback is invoked for every pass successfully executed in the + // process of rendering a frame. Optional. + // + // Note: `info` is only valid until this function returns. + void (*info_callback)(void *priv, const struct pl_render_info *info); + void *info_priv; + + // --- Deprecated/removed fields + PL_DEPRECATED_IN(v6.254) bool allow_delayed_peak_detect; // moved to pl_peak_detect_params + PL_DEPRECATED_IN(v6.327) const struct pl_icc_params *icc_params; // use pl_frame.icc + PL_DEPRECATED_IN(v6.328) bool ignore_icc_profiles; // non-functional, just set pl_frame.icc to NULL + PL_DEPRECATED_IN(v6.335) int lut_entries; // hard-coded as 256 + PL_DEPRECATED_IN(v6.335) float polar_cutoff; // hard-coded as 1e-3 + PL_DEPRECATED_IN(v7.346) bool skip_target_clearing; // `border = PL_CLEAR_SKIP` + PL_DEPRECATED_IN(v7.346) bool blend_against_tiles; // `background = PL_CLEAR_TILES` +}; + +// Bare minimum parameters, with no features enabled. This is the fastest +// possible configuration, and should therefore be fine on any system. +#define PL_RENDER_DEFAULTS \ + .color_map_params = &pl_color_map_default_params, \ + .color_adjustment = &pl_color_adjustment_neutral, \ + .tile_colors = {{0.93, 0.93, 0.93}, \ + {0.87, 0.87, 0.87}}, \ + .tile_size = 32, \ + .blur_radius = 16.0, + +#define pl_render_params(...) (&(struct pl_render_params) { PL_RENDER_DEFAULTS __VA_ARGS__ }) +PL_API extern const struct pl_render_params pl_render_fast_params; + +// This contains the default/recommended options for reasonable image quality, +// while also not being too terribly slow. All of the *_params structs are +// defaulted to the corresponding *_default_params, except for deband_params, +// which is disabled by default. +// +// This should be fine on most integrated GPUs, but if it's too slow, +// consider using `pl_render_fast_params` instead. +PL_API extern const struct pl_render_params pl_render_default_params; + +// This contains a higher quality preset for better image quality at the cost +// of quite a bit of performance. In addition to the settings implied by +// `pl_render_default_params`, it enables debanding, sets the upscaler to +// `pl_filter_ewa_lanczossharp`, and uses pl_*_high_quality_params structs where +// available. This should only really be used with a discrete GPU and where +// maximum image quality is desired. +PL_API extern const struct pl_render_params pl_render_high_quality_params; + +#define PL_MAX_PLANES 4 + +// High level description of a single slice of an image. This basically +// represents a single 2D plane, with any number of components +struct pl_plane { + // The texture underlying this plane. The texture must be 2D, and must + // have specific parameters set depending on what the plane is being used + // for (see `pl_render_image`). + pl_tex texture; + + // The preferred behaviour when sampling outside of this texture. Optional, + // since the default (PL_TEX_ADDRESS_CLAMP) is very reasonable. + enum pl_tex_address_mode address_mode; + + // Controls whether or not the `texture` will be considered flipped + // vertically with respect to the overall image dimensions. It's generally + // preferable to flip planes using this setting instead of the crop in + // cases where the flipping is the result of e.g. negative plane strides or + // flipped framebuffers (OpenGL). + // + // Note that any planar padding (due to e.g. size mismatch or misalignment + // of subsampled planes) is always at the physical end of the texture + // (highest y coordinate) - even if this bool is true. However, any + // subsampling shift (`shift_y`) is applied with respect to the flipped + // direction. This ensures the correct interpretation when e.g. vertically + // flipping 4:2:0 sources by flipping all planes. + bool flipped; + + // Describes the number and interpretation of the components in this plane. + // This defines the mapping from component index to the canonical component + // order (RGBA, YCbCrA or XYZA). It's worth pointing out that this is + // completely separate from `texture->format.sample_order`. The latter is + // essentially irrelevant/transparent for the API user, since it just + // determines which order the texture data shows up as inside the GLSL + // shader; whereas this field controls the actual meaning of the component. + // + // Example; if the user has a plane with just {Y} and a plane with just + // {Cb Cr}, and a GPU that only supports bgra formats, you would still + // specify the component mapping as {0} and {1 2} respectively, even though + // the GPU is sampling the data in the order BGRA. Use -1 for "ignored" + // components. + int components; // number of relevant components + int component_mapping[4]; // semantic index of each component + + // Controls the sample offset, relative to the "reference" dimensions. For + // an example of what to set here, see `pl_chroma_location_offset`. Note + // that this is given in unit of reference pixels. For a graphical example, + // imagine you have a 2x2 image with a 1x1 (subsampled) plane. Without any + // shift (0.0), the situation looks like this: + // + // X-------X X = reference pixel + // | | P = plane pixel + // | P | + // | | + // X-------X + // + // For 4:2:0 subsampling, this corresponds to PL_CHROMA_CENTER. If the + // shift_x was instead set to -0.5, the `P` pixel would be offset to the + // left by half the separation between the reference (`X` pixels), resulting + // in the following: + // + // X-------X X = reference pixel + // | | P = plane pixel + // P | + // | | + // X-------X + // + // For 4:2:0 subsampling, this corresponds to PL_CHROMA_LEFT. + // + // Note: It's recommended to fill this using `pl_chroma_location_offset` on + // the chroma planes. + float shift_x, shift_y; +}; + +enum pl_overlay_mode { + PL_OVERLAY_NORMAL = 0, // treat the texture as a normal, full-color texture + PL_OVERLAY_MONOCHROME, // treat the texture as a single-component alpha map + PL_OVERLAY_MODE_COUNT, +}; + +enum pl_overlay_coords { + PL_OVERLAY_COORDS_AUTO = 0, // equal to SRC/DST_FRAME, respectively + PL_OVERLAY_COORDS_SRC_FRAME, // relative to the raw src frame + PL_OVERLAY_COORDS_SRC_CROP, // relative to the src frame crop + PL_OVERLAY_COORDS_DST_FRAME, // relative to the raw dst frame + PL_OVERLAY_COORDS_DST_CROP, // relative to the dst frame crop + PL_OVERLAY_COORDS_COUNT, + + // Note on rotations: If there is an end-to-end rotation between `src` and + // `dst`, then any overlays relative to SRC_FRAME or SRC_CROP will be + // rotated alongside the image, while overlays relative to DST_FRAME or + // DST_CROP will not. +}; + +struct pl_overlay_part { + pl_rect2df src; // source coordinate with respect to `pl_overlay.tex` + pl_rect2df dst; // target coordinates with respect to `pl_overlay.coords` + + // If `mode` is PL_OVERLAY_MONOCHROME, then this specifies the color of + // this overlay part. The color is multiplied into the sampled texture's + // first channel. + float color[4]; +}; + +// A struct representing an image overlay (e.g. for subtitles or on-screen +// status messages, controls, ...) +struct pl_overlay { + // The texture containing the backing data for overlay parts. Must have + // `params.sampleable` set. + pl_tex tex; + + // This controls the coloring mode of this overlay. + enum pl_overlay_mode mode; + + // Controls which coordinates this overlay is addressed relative to. + enum pl_overlay_coords coords; + + // This controls the colorspace information for this overlay. The contents + // of the texture / the value of `color` are interpreted according to this. + struct pl_color_repr repr; + struct pl_color_space color; + + // The number of parts for this overlay. + const struct pl_overlay_part *parts; + int num_parts; +}; + +// High-level description of a complete frame, including metadata and planes +struct pl_frame { + // Each frame is split up into some number of planes, each of which may + // carry several components and be of any size / offset. + int num_planes; + struct pl_plane planes[PL_MAX_PLANES]; + + // Optional enhancement layer for layered video formats. When set, points + // to a fully-described pl_frame whose planes are composed onto this + // (base layer) frame. Composition math is driven by metadata on the base + // frame. Currently used only for Dolby Vision Profile 7 FEL, gated by + // `repr.dovi->nlq_active`; ignored otherwise. + const struct pl_frame *enhancement_layer; + + // For interlaced frames. If set, this `pl_frame` corresponds to a single + // field of the underlying source textures. `first_field` indicates which + // of these fields is ordered first in time. `prev` and `next` should point + // to the previous/next frames in the file, or NULL if there are none. + // + // Note: Setting these fields on the render target has no meaning and will + // be ignored. + enum pl_field field; + enum pl_field first_field; + const struct pl_frame *prev, *next; + + // If set, will be called immediately before GPU access to this frame. This + // function *may* be used to, for example, perform synchronization with + // external APIs (e.g. `pl_vulkan_hold/release`). If your mapping requires + // a memcpy of some sort (e.g. pl_tex_transfer), users *should* instead do + // the memcpy up-front and avoid the use of these callbacks - because they + // might be called multiple times on the same frame. + // + // This function *may* arbitrarily mutate the `pl_frame`, but it *should* + // ideally only update `planes` - in particular, color metadata and so + // forth should be provided up-front as best as possible. Note that changes + // here will not be reflected back to the structs provided in the original + // `pl_render_*` call (e.g. via `pl_frame_mix`). + // + // Note: Unless dealing with interlaced frames, only one frame will ever be + // acquired at a time per `pl_render_*` call. So users *can* safely use + // this with, for example, hwdec mappers that can only map a single frame + // at a time. When using this with, for example, `pl_render_image_mix`, + // each frame to be blended is acquired and release in succession, before + // moving on to the next frame. For interlaced frames, the previous and + // next frames must also be acquired simultaneously. + bool (*acquire)(pl_gpu gpu, struct pl_frame *frame); + + // If set, will be called after a plane is done being used by the GPU, + // *including* after any errors (e.g. `acquire` returning false). + void (*release)(pl_gpu gpu, struct pl_frame *frame); + + // Color representation / encoding / semantics of this frame. + struct pl_color_repr repr; + struct pl_color_space color; + + // Optional ICC profile associated with this frame. + pl_icc_object icc; + + // Alternative to `icc`, this can be used in cases where allocating and + // tracking an pl_icc_object externally may be inconvenient. The resulting + // profile will be managed internally by the pl_renderer. + struct pl_icc_profile profile; + + // Optional LUT associated with this frame. + const struct pl_custom_lut *lut; + enum pl_lut_type lut_type; + + // The logical crop / rectangle containing the valid information, relative + // to the reference plane's dimensions (e.g. luma). Pixels outside of this + // rectangle will ostensibly be ignored, but note that this is not a hard + // guarantee. In particular, scaler filters may end up sampling outside of + // this crop. This rect may be flipped, and may be partially or wholly + // outside the bounds of the underlying textures. (Optional) + // + // Note that `pl_render_image` will map the input crop directly to the + // output crop, stretching and scaling as needed. If you wish to preserve + // the aspect ratio, use a dedicated function like pl_rect2df_aspect_copy. + pl_rect2df crop; + + // Logical rotation of the image, with respect to the underlying planes. + // For example, if this is PL_ROTATION_90, then the image will be rotated + // to the right by 90° when mapping to `crop`. The actual position on-screen + // is unaffected, so users should ensure that the (rotated) aspect ratio + // matches the source. (Or use a helper like `pl_rect2df_aspect_set_rot`) + // + // Note: For `target` frames, this corresponds to a rotation of the + // display, for `image` frames, this corresponds to a rotation of the + // camera. + // + // So, as an example, target->rotation = PL_ROTATE_90 means the end user + // has rotated the display to the right by 90° (meaning rendering will be + // rotated 90° to the *left* to compensate), and image->rotation = + // PL_ROTATE_90 means the video provider has rotated the camera to the + // right by 90° (so rendering will be rotated 90° to the *right* to + // compensate). + pl_rotation rotation; + + // The pixel aspect ratio of this frame. This is informational only, since + // the effective DAR is already given by the relative ratio between the + // frame crop and the target crop. If left unset, defaults to 1.0. + // + // Note that this is relative to the raw (encoded) pixels, i.e. before + // application of any `rotation`. + float pixel_aspect_ratio; + + // A list of additional overlays associated with this frame. Note that will + // be rendered directly onto intermediate/cache frames, so changing any of + // these overlays may require flushing the renderer cache. + const struct pl_overlay *overlays; + int num_overlays; + + // Note on subsampling and plane correspondence: All planes belonging to + // the same frame will only be stretched by an integer multiple (or inverse + // thereof) in order to match the reference dimensions of this image. For + // example, suppose you have an 8x4 image. A valid plane scaling would be + // 4x2 -> 8x4 or 4x4 -> 4x4, but not 6x4 -> 8x4. So if a 6x4 plane is + // given, then it would be treated like a cropped 8x4 plane (since 1.0 is + // the closest scaling ratio to the actual ratio of 1.3). + // + // For an explanation of why this makes sense, consider the relatively + // common example of a subsampled, oddly sized (e.g. jpeg) image. In such + // cases, for example a 35x23 image, the 4:2:0 subsampled chroma plane + // would have to end up as 17.5x11.5, which gets rounded up to 18x12 by + // implementations. So in this example, the 18x12 chroma plane would get + // treated by libplacebo as an oversized chroma plane - i.e. the plane + // would get sampled as if it was 17.5 pixels wide and 11.5 pixels large. + + // Associated film grain data (see ). + // + // Note: This is ignored for the `target` of `pl_render_image`, since + // un-applying grain makes little sense. + struct pl_film_grain_data film_grain; + + // Ignored by libplacebo. May be useful for users. + void *user_data; +}; + +// Helper function to infer the chroma location offset for each plane in a +// frame. This is equivalent to calling `pl_chroma_location_offset` on all +// subsampled planes' shift_x/shift_y variables. +PL_API void pl_frame_set_chroma_location(struct pl_frame *frame, + enum pl_chroma_location chroma_loc); + +// Fills in a `pl_frame` based on a swapchain frame's FBO and metadata. +PL_API void pl_frame_from_swapchain(struct pl_frame *out_frame, + const struct pl_swapchain_frame *frame); + +// Helper function to determine if a frame is logically cropped or not. In +// particular, this is useful in determining whether or not an output frame +// needs to be cleared before rendering or not. +PL_API bool pl_frame_is_cropped(const struct pl_frame *frame); + +// Helper function to reset a frame to a given RGB color. If the frame's +// color representation is something other than RGB, the clear color will +// be adjusted accordingly. `clear_color` should be non-premultiplied. +PL_API void pl_frame_clear_rgba(pl_gpu gpu, const struct pl_frame *frame, + const float clear_color[4]); + +// Like `pl_frame_clear_rgba` but without an alpha channel. +static inline void pl_frame_clear(pl_gpu gpu, const struct pl_frame *frame, + const float clear_color[3]) +{ + const float clear_color_rgba[4] = { clear_color[0], clear_color[1], clear_color[2], 1.0 }; + pl_frame_clear_rgba(gpu, frame, clear_color_rgba); +} + +// Helper function to clear a frame to a fully tiled background. +PL_API void pl_frame_clear_tiles(pl_gpu gpu, const struct pl_frame *frame, + const float tile_colors[2][3], int tile_size); + +// Helper functions to return the fixed/inferred pl_frame parameters used +// for rendering internally. Mutates `image` and `target` in-place to hold +// the modified values, which are what will actually be used for rendering. +// +// This currently includes: +// - Defaulting all missing pl_color_space/repr parameters +// - Coalescing all rotation to the target +// - Rounding and clamping the target crop to pixel boundaries and adjusting the +// image crop correspondingly +// +// Note: This is idempotent and does not generally alter the effects of a +// subsequent `pl_render_image` on the same pl_frame pair. (But see the +// following warning) +// +// Warning: This does *not* call pl_frame.acquire/release, and so the returned +// metadata *may* be incorrect if the acquire callback mutates the pl_frame in +// nontrivial ways, in particular the crop and color space fields. +PL_API void pl_frames_infer(pl_renderer rr, struct pl_frame *image, + struct pl_frame *target); + + +// Render a single image to a target using the given parameters. This is +// fully dynamic, i.e. the params can change at any time. libplacebo will +// internally detect and flush whatever caches are invalidated as a result of +// changing colorspace, size etc. +// +// Required plane capabilities: +// - Planes in `image` must be `sampleable` +// - Planes in `target` must be `renderable` +// +// Recommended plane capabilities: (Optional, but good for performance) +// - Planes in `image` should have `sample_mode` PL_TEX_SAMPLE_LINEAR +// - Planes in `target` should be `storable` +// - Planes in `target` should have `blit_dst` +// +// Note on lifetime: Once this call returns, the passed structures may be +// freely overwritten or discarded by the caller, even the referenced +// `pl_tex` objects may be freely reused. +// +// Note: `image` may be NULL, in which case `target.overlays` will still be +// rendered, but nothing else. +PL_API bool pl_render_image(pl_renderer rr, const struct pl_frame *image, + const struct pl_frame *target, + const struct pl_render_params *params); + +// Flushes the internal state of this renderer. This is normally not needed, +// even if the image parameters, colorspace or target configuration change, +// since libplacebo will internally detect such circumstances and recreate +// outdated resources automatically. Doing this explicitly *may* be useful to +// purge some state related to things like HDR peak detection or frame mixing, +// so calling it is a good idea if the content source is expected to change +// dramatically (e.g. when switching to a different file). +PL_API void pl_renderer_flush_cache(pl_renderer rr); + +// Mirrors `pl_get_detected_hdr_metadata`, giving you the current internal peak +// detection HDR metadata (when peak detection is active). Returns false if no +// information is available (e.g. not HDR source, peak detection disabled). +PL_API bool pl_renderer_get_hdr_metadata(pl_renderer rr, + struct pl_hdr_metadata *metadata); + +// Represents a mixture of input frames, distributed temporally. +// +// NOTE: Frames must be sorted by timestamp, i.e. `timestamps` must be +// monotonically increasing. +struct pl_frame_mix { + // The number of frames in this mixture. The number of frames should be + // sufficient to meet the needs of the configured frame mixer. See the + // section below for more information. + // + // If the number of frames is 0, this call will be equivalent to + // `pl_render_image` with `image == NULL`. + int num_frames; + + // A list of the frames themselves. The frames can have different + // colorspaces, configurations of planes, or even sizes. + // + // Note: This is a list of pointers, to avoid users having to copy + // around `pl_frame` structs when re-organizing this array. + const struct pl_frame **frames; + + // A list of unique signatures, one for each frame. These are used to + // identify frames across calls to this function, so it's crucial that they + // be both unique per-frame but also stable across invocations of + // `pl_render_frame_mix`. + const uint64_t *signatures; + + // A list of relative timestamps for each frame. These are relative to the + // time of the vsync being drawn, i.e. this function will render the frame + // that will be made visible at timestamp 0.0. The values are expected to + // be normalized such that a separation of 1.0 corresponds to roughly one + // nominal source frame duration. So a constant framerate video file will + // always have timestamps like e.g. {-2.3, -1.3, -0.3, 0.7, 1.7, 2.7}, + // using an example radius of 3. + // + // In cases where the framerate is variable (e.g. VFR video), the choice of + // what to scale to use can be difficult to answer. A typical choice would + // be either to use the canonical (container-tagged) framerate, or the + // highest momentary framerate, as a reference. If all else fails, you + // could also use the display's framerate. + // + // Note: This function assumes zero-order-hold semantics, i.e. the frame at + // timestamp 0.7 is intended to remain visible until timestamp 1.7, when + // the next frame replaces it. + const float *timestamps; + + // The duration for which the vsync being drawn will be held, using the + // same scale as `timestamps`. If the display has an unknown or variable + // frame-rate (e.g. Adaptive Sync), then you're probably better off not + // using this function and instead just painting the frames directly using + // `pl_render_frame` at the correct PTS. + // + // As an example, if `vsync_duration` is 0.4, then it's assumed that the + // vsync being painted is visible for the period [0.0, 0.4]. + float vsync_duration; + + // Explanation of the frame mixing radius: The algorithm chosen in + // `pl_render_params.frame_mixer` has a canonical radius equal to + // `pl_filter_config.kernel->radius`. This means that the frame mixing + // algorithm will (only) need to consult all of the frames that have a + // distance within the interval [-radius, radius]. As such, the user should + // include all such frames in `frames`, but may prune or omit frames that + // lie outside it. + // + // The built-in frame mixing (`pl_render_params.frame_mixer == NULL`) has + // no concept of radius, it just always needs access to the "current" and + // "next" frames. +}; + +// Helper function to calculate the base frame mixing radius. +// +// Note: When the source FPS exceeds the display FPS, this radius must be +// increased by the corresponding ratio. +static inline float pl_frame_mix_radius(const struct pl_render_params *params) +{ + // For backwards compatibility, allow !frame_mixer->kernel + if (!params->frame_mixer || !params->frame_mixer->kernel) + return 0.0; + + return params->frame_mixer->kernel->radius; +} + +// Find closest frame to current PTS by zero-order hold semantics, or NULL. +PL_API const struct pl_frame *pl_frame_mix_current(const struct pl_frame_mix *mix); + +// Find closest frame to current PTS by nearest neighbour semantics, or NULL. +PL_API const struct pl_frame *pl_frame_mix_nearest(const struct pl_frame_mix *mix); + +// Render a mixture of images to the target using the given parameters. This +// functions much like a generalization of `pl_render_image`, for when the API +// user has more control over the frame queue / vsync loop, and can provide a +// few frames from the past and future + timestamp information. +// +// This allows libplacebo to perform rudimentary frame mixing / interpolation, +// in order to eliminate judder artifacts typically associated with +// source/display frame rate mismatch. +PL_API bool pl_render_image_mix(pl_renderer rr, const struct pl_frame_mix *images, + const struct pl_frame *target, + const struct pl_render_params *params); + +// Analog of `pl_frame_infer` corresponding to `pl_render_image_mix`. This +// function will *not* mutate the frames contained in `mix`, and instead +// return an adjusted copy of the "reference" frame for that image mix in +// `out_refimage`, or {0} if the mix is empty. +PL_API void pl_frames_infer_mix(pl_renderer rr, const struct pl_frame_mix *mix, + struct pl_frame *target, struct pl_frame *out_ref); + +// Backwards compatibility with old filters API, may be deprecated. +// Redundant with pl_filter_configs and masking `allowed` for +// PL_FILTER_SCALING and PL_FILTER_FRAME_MIXING respectively. + +// A list of recommended frame mixer presets, terminated by {0} +PL_API extern const struct pl_filter_preset pl_frame_mixers[]; +PL_API extern const int pl_num_frame_mixers; // excluding trailing {0} + +// A list of recommended scaler presets, terminated by {0}. This is almost +// equivalent to `pl_filter_presets` with the exception of including extra +// built-in filters that don't map to the `pl_filter` architecture. +PL_API extern const struct pl_filter_preset pl_scale_filters[]; +PL_API extern const int pl_num_scale_filters; // excluding trailing {0} + +// Deprecated in favor of `pl_cache_save/pl_cache_load` on the `pl_cache` +// associated with the `pl_gpu` this renderer is using. +PL_DEPRECATED_IN(v6.323) PL_API size_t pl_renderer_save(pl_renderer rr, uint8_t *out_cache); +PL_DEPRECATED_IN(v6.323) PL_API void pl_renderer_load(pl_renderer rr, const uint8_t *cache); + +PL_API_END + +#endif // LIBPLACEBO_RENDERER_H_ diff --git a/third_party/exo-dv5-native/include/libplacebo/shaders.h b/third_party/exo-dv5-native/include/libplacebo/shaders.h new file mode 100644 index 0000000000..96b9525337 --- /dev/null +++ b/third_party/exo-dv5-native/include/libplacebo/shaders.h @@ -0,0 +1,273 @@ +/* + * This file is part of libplacebo. + * + * libplacebo is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libplacebo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with libplacebo. If not, see . + */ + +#ifndef LIBPLACEBO_SHADERS_H_ +#define LIBPLACEBO_SHADERS_H_ + +// This function defines the "direct" interface to libplacebo's GLSL shaders, +// suitable for use in contexts where the user controls GLSL shader compilation +// but wishes to include functions generated by libplacebo as part of their +// own rendering process. This API is normally not used for operation with +// libplacebo's higher-level constructs such as `pl_dispatch` or `pl_renderer`. + +#include + +PL_API_BEGIN + +// Thread-safety: Unsafe +typedef struct pl_shader_t *pl_shader; + +struct pl_shader_params { + // The `id` represents an abstract identifier for the shader, to avoid + // collisions with other shaders being used as part of the same larger, + // overarching shader. This is relevant for users which want to combine + // multiple `pl_shader` objects together, in which case all `pl_shader` + // objects should have a unique `id`. + uint8_t id; + + // If `gpu` is non-NULL, then this `gpu` will be used to create objects + // such as textures and buffers, or check for required capabilities, for + // operations which depend on either of those. This is fully optional, i.e. + // these GLSL primitives are designed to be used without a dependency on + // `gpu` wherever possible - however, some features may not work, and will + // be disabled even if requested. + pl_gpu gpu; + + // The `index` represents an abstract frame index, which shaders may use + // internally to do things like temporal dithering or seeding PRNGs. If the + // user does not care about temporal dithering/debanding, or wants + // deterministic rendering, this may safely be left as 0. Otherwise, it + // should be incremented by 1 on successive frames. + uint8_t index; + + // If `glsl.version` is nonzero, then this structure will be used to + // determine the effective GLSL mode and capabilities. If `gpu` is also + // set, then this overrides `gpu->glsl`. + struct pl_glsl_version glsl; + + // If this is true, all constants in the shader will be replaced by + // dynamic variables. This is mainly useful to avoid recompilation for + // shaders which expect to have their values change constantly. + bool dynamic_constants; +}; + +#define pl_shader_params(...) (&(struct pl_shader_params) { __VA_ARGS__ }) + +// Creates a new, blank, mutable pl_shader object. +// +// Note: Rather than allocating and destroying many shaders, users are +// encouraged to reuse them (using `pl_shader_reset`) for efficiency. +PL_API pl_shader pl_shader_alloc(pl_log log, const struct pl_shader_params *params); + +// Frees a pl_shader and all resources associated with it. +PL_API void pl_shader_free(pl_shader *sh); + +// Resets a pl_shader to a blank slate, without releasing internal memory. +// If you're going to be re-generating shaders often, this function will let +// you skip the re-allocation overhead. +PL_API void pl_shader_reset(pl_shader sh, const struct pl_shader_params *params); + +// Returns whether or not a shader is in a "failed" state. Trying to modify a +// shader in illegal ways (e.g. signature mismatch) will result in the shader +// being marked as "failed". Since most pl_shader_ operations have a void +// return type, the user can use this function to figure out whether a specific +// shader operation has failed or not. This function is somewhat redundant +// since `pl_shader_finalize` will also return NULL in this case. +PL_API bool pl_shader_is_failed(const pl_shader sh); + +// Returns whether or not a pl_shader needs to be run as a compute shader. This +// will never be the case unless the `pl_glsl_version` this `pl_shader` was +// created using has `compute` support enabled. +PL_API bool pl_shader_is_compute(const pl_shader sh); + +// Returns whether or not the shader has any particular output size +// requirements. Some shaders, in particular those that sample from other +// textures, have specific output size requirements which need to be respected +// by the caller. If this is false, then the shader is compatible with every +// output size. If true, the size requirements are stored into *w and *h. +PL_API bool pl_shader_output_size(const pl_shader sh, int *w, int *h); + +// Indicates the type of signature that is associated with a shader result. +// Every shader result defines a function that may be called by the user, and +// this enum indicates the type of value that this function takes and/or +// returns. +// +// Which signature a shader ends up with depends on the type of operation being +// performed by a shader fragment, as determined by the user's calls. See below +// for more information. +enum pl_shader_sig { + PL_SHADER_SIG_NONE = 0, // no input / void output + PL_SHADER_SIG_COLOR, // vec4 color (normalized so that 1.0 is the ref white) + + // The following are only valid as input signatures: + PL_SHADER_SIG_SAMPLER, // (gsampler* src_tex, vecN tex_coord) pair, + // specifics depend on how the shader was generated +}; + +// Structure encapsulating information about a shader. This is internally +// refcounted, to allow moving it around without having to create deep copies. +typedef const struct pl_shader_info_t { + // A copy of the parameters used to create the shader. + struct pl_shader_params params; + + // A list of friendly names for the semantic operations being performed by + // this shader, e.g. "color decoding" or "debanding". + const char **steps; + int num_steps; + + // As a convenience, this contains a pretty-printed version of the + // above list, with entries tallied and separated by commas + const char *description; +} *pl_shader_info; + +PL_API pl_shader_info pl_shader_info_ref(pl_shader_info info); +PL_API void pl_shader_info_deref(pl_shader_info *info); + +// Represents a finalized shader fragment. This is not a complete shader, but a +// collection of raw shader text together with description of the input +// attributes, variables and vertices it expects to be available. +struct pl_shader_res { + // Descriptive information about the shader. Note that this reference is + // attached to the shader itself - the user does not need to manually ref + // or deref `info` unless they wish to move it elsewhere. + pl_shader_info info; + + // The shader text, as literal GLSL. This will always be a function + // definition, such that the the function with the indicated name and + // signature may be called by the user. + const char *glsl; + const char *name; + enum pl_shader_sig input; // what the function expects + enum pl_shader_sig output; // what the function returns + + // For compute shaders (pl_shader_is_compute), this indicates the requested + // work group size. Otherwise, both fields are 0. The interpretation of + // these work groups is that they're tiled across the output image. + int compute_group_size[2]; + + // If this pass is a compute shader, this field indicates the shared memory + // size requirements for this shader pass. + size_t compute_shmem; + + // A set of input vertex attributes needed by this shader fragment. + const struct pl_shader_va *vertex_attribs; + int num_vertex_attribs; + + // A set of input variables needed by this shader fragment. + const struct pl_shader_var *variables; + int num_variables; + + // A list of input descriptors needed by this shader fragment, + const struct pl_shader_desc *descriptors; + int num_descriptors; + + // A list of compile-time constants used by this shader fragment. + const struct pl_shader_const *constants; + int num_constants; + + // --- Deprecated fields (see `info`) + PL_DEPRECATED_IN(v6.266) struct pl_shader_params params; + PL_DEPRECATED_IN(v6.266) const char **steps; + PL_DEPRECATED_IN(v6.266) int num_steps; + PL_DEPRECATED_IN(v6.266) const char *description; +}; + +// Represents a vertex attribute. The four values will be bound to the four +// corner vertices respectively, in row-wise order starting from the top left: +// data[0] data[1] +// data[2] data[3] +struct pl_shader_va { + struct pl_vertex_attrib attr; // VA type, excluding `offset` and `location` + const void *data[4]; +}; + +// Represents a bound shared variable / descriptor +struct pl_shader_var { + struct pl_var var; // the underlying variable description + const void *data; // the raw data (as per `pl_var_host_layout`) + bool dynamic; // if true, the value is expected to change frequently +}; + +struct pl_buffer_var { + struct pl_var var; + struct pl_var_layout layout; +}; + +typedef uint16_t pl_memory_qualifiers; +enum { + PL_MEMORY_COHERENT = 1 << 0, // supports synchronization across shader invocations + PL_MEMORY_VOLATILE = 1 << 1, // all writes are synchronized automatically + + // Note: All descriptors are also implicitly assumed to have the 'restrict' + // memory qualifier. There is currently no way to override this behavior. +}; + +struct pl_shader_desc { + struct pl_desc desc; // descriptor type, excluding `int binding` + struct pl_desc_binding binding; // contents of the descriptor binding + + // For PL_DESC_BUF_UNIFORM/STORAGE, this specifies the layout of the + // variables contained by a buffer. Ignored for the other descriptor types + struct pl_buffer_var *buffer_vars; + int num_buffer_vars; + + // For storage images and buffers, this specifies additional memory + // qualifiers on the descriptor. It's highly recommended to always use + // at least PL_MEMORY_RESTRICT. Ignored for other descriptor types. + pl_memory_qualifiers memory; +}; + +// Represents a compile-time constant. This can be lowered to a specialization +// constant to support cheaper recompilations. +struct pl_shader_const { + enum pl_var_type type; + const char *name; + const void *data; + + // If true, this constant *must* be a compile-time constant, which + // basically just overrides `pl_shader_params.dynamic_constants`. Useful + // for constants which will serve as inputs to e.g. array sizes. + bool compile_time; +}; + +// Finalize a pl_shader. It is no longer mutable at this point, and any further +// attempts to modify it result in an error. (Functions which take a `const +// pl_shader` argument do not modify the shader and may be freely +// called on an already-finalized shader) +// +// The returned pl_shader_res is bound to the lifetime of the pl_shader - and +// will only remain valid until the pl_shader is freed or reset. This function +// may be called multiple times, and will produce the same result each time. +// +// This function will return NULL if the shader is considered to be in a +// "failed" state (see pl_shader_is_failed). +PL_API const struct pl_shader_res *pl_shader_finalize(pl_shader sh); + +// Shader objects represent abstract resources that shaders need to manage in +// order to ensure their operation. This could include shader storage buffers, +// generated lookup textures, or other sorts of configured state. The body +// of a shader object is fully opaque; but the user is in charge of cleaning up +// after them and passing them to the right shader passes. +// +// Note: pl_shader_obj objects must be initialized to NULL by the caller. +typedef struct pl_shader_obj_t *pl_shader_obj; + +PL_API void pl_shader_obj_destroy(pl_shader_obj *obj); + +PL_API_END + +#endif // LIBPLACEBO_SHADERS_H_ diff --git a/third_party/exo-dv5-native/include/libplacebo/shaders/colorspace.h b/third_party/exo-dv5-native/include/libplacebo/shaders/colorspace.h new file mode 100644 index 0000000000..81236997a8 --- /dev/null +++ b/third_party/exo-dv5-native/include/libplacebo/shaders/colorspace.h @@ -0,0 +1,402 @@ +/* + * This file is part of libplacebo. + * + * libplacebo is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libplacebo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with libplacebo. If not, see . + */ + +#ifndef LIBPLACEBO_SHADERS_COLORSPACE_H_ +#define LIBPLACEBO_SHADERS_COLORSPACE_H_ + +// Color space transformation shaders. These all input and output a color +// value (PL_SHADER_SIG_COLOR). + +#include +#include +#include +#include + +// For backwards compatibility +#include + +PL_API_BEGIN + +// Transform the input color, in its given representation, to ensure +// compatibility with the indicated alpha mode. Mutates `repr` to reflect the +// change. Note that this is a no-op if the input is PL_ALPHA_UNKNOWN. +PL_API void pl_shader_set_alpha(pl_shader sh, struct pl_color_repr *repr, + enum pl_alpha_mode mode); + +// Colorspace reshaping for PL_COLOR_SYSTEM_DOLBYVISION. Note that this is done +// automatically by `pl_shader_decode_color` for PL_COLOR_SYSTEM_DOLBYVISION. +PL_API void pl_shader_dovi_reshape(pl_shader sh, const struct pl_dovi_metadata *data); + +// Arguments for the `pl_shader_decode_color_ex` call. +struct pl_color_decode_args { + // Input color representation. Mutated to reflect the decode. Required. + struct pl_color_repr *repr; + + // Color adjustment parameters. If NULL, defaults to + // `&pl_color_adjustment_neutral`. + const struct pl_color_adjustment *color_adjustment; + + // Optional sub-shader producing the enhancement-layer. The expected format + // and output of the shader depends on the EL being used, based on repr. + // Currently only Dolby Vision EL is supported. + pl_shader enhancement_layer; +}; + +#define pl_color_decode_args(...) (&(struct pl_color_decode_args) { __VA_ARGS__ }) + +// Decode the color into normalized RGB, given a specified color_repr. This +// also takes care of additional pre- and post-conversions requires for the +// "special" color systems (XYZ, BT.2020-C, etc.). If `args->color_adjustment` +// is left as NULL, it defaults to &pl_color_adjustment_neutral. +// +// Note: This function always returns PC-range RGB with independent alpha. +// It mutates the pl_color_repr to reflect the change. +// +// Note: For DCDM XYZ decoding input is expected to be linear, use +// `pl_shader_linearize` before calling this function. +PL_API void pl_shader_decode_color_ex(pl_shader sh, + const struct pl_color_decode_args *args); + +// Backwards compatibility wrapper around `pl_shader_decode_color_ex`. +PL_DEPRECATED_IN(v7.368) +PL_API void pl_shader_decode_color(pl_shader sh, struct pl_color_repr *repr, + const struct pl_color_adjustment *params); + +// Encodes a color from normalized, PC-range, independent alpha RGB into a +// given representation. That is, this performs the inverse operation of +// `pl_shader_decode_color` (sans color adjustments). +// +// Note: For DCDM XYZ encoding input is expected to be linear +PL_API void pl_shader_encode_color(pl_shader sh, const struct pl_color_repr *repr); + +// Linearize (expand) `vec4 color`, given a specified color space. Shader +// equivalent of `pl_color_linearize`. +PL_API void pl_shader_linearize(pl_shader sh, const struct pl_color_space *csp); + +// Delinearize (compress), given a color space as output. Shader equivalent +// of `pl_color_delinearize`. +PL_API void pl_shader_delinearize(pl_shader sh, const struct pl_color_space *csp); + +struct pl_sigmoid_params { + // The center (bias) of the sigmoid curve. Must be between 0.0 and 1.0. + // If left as NULL, defaults to 0.75 + float center; + + // The slope (steepness) of the sigmoid curve. Must be between 1.0 and 20.0. + // If left as NULL, defaults to 6.5. + float slope; +}; + +#define PL_SIGMOID_DEFAULTS \ + .center = 0.75, \ + .slope = 6.50, + +#define pl_sigmoid_params(...) (&(struct pl_sigmoid_params) { PL_SIGMOID_DEFAULTS __VA_ARGS__ }) +PL_API extern const struct pl_sigmoid_params pl_sigmoid_default_params; + +// Applies a sigmoidal color transform to all channels. This helps avoid +// ringing artifacts during upscaling by bringing the color information closer +// to neutral and away from the extremes. If `params` is NULL, it defaults to +// &pl_sigmoid_default_params. +// +// For more information about sigmoidization, see: +// https://imagemagick.org/Usage/resize/#resize_sigmoidal +// +// Warning: This function clamps the input to the interval [0,1]; and as such +// it should *NOT* be used on already-decoded high-dynamic range content. +PL_API void pl_shader_sigmoidize(pl_shader sh, const struct pl_sigmoid_params *params); + +// This performs the inverse operation to `pl_shader_sigmoidize`. +PL_API void pl_shader_unsigmoidize(pl_shader sh, const struct pl_sigmoid_params *params); + +struct pl_peak_detect_params { + // Smoothing coefficient for the detected values. This controls the time + // parameter (tau) of an IIR low pass filter. In other words, it represent + // the cutoff period (= 1 / cutoff frequency) in frames. Frequencies below + // this length will be suppressed. This helps block out annoying + // "sparkling" or "flickering" due to small variations in frame-to-frame + // brightness. If left as 0.0, this smoothing is completely disabled. + float smoothing_period; + + // In order to avoid reacting sluggishly on scene changes as a result of + // the low-pass filter, we disable it when the difference between the + // current frame brightness and the average frame brightness exceeds a + // given threshold difference. But rather than a single hard cutoff, which + // would lead to weird discontinuities on fades, we gradually disable it + // over a small window of brightness ranges. These parameters control the + // lower and upper bounds of this window, in units of 1% PQ. + // + // Setting either one of these to 0.0 disables this logic. + float scene_threshold_low; + float scene_threshold_high; + + // Which percentile of the input image brightness histogram to consider as + // the true peak of the scene. If this is set to 100 (or 0), the brightest + // pixel is measured. Otherwise, the top of the frequency distribution is + // progressively cut off. Setting this too low will cause clipping of very + // bright details, but can improve the dynamic brightness range of scenes + // with very bright isolated highlights. + // + // A recommended value is 99.995%, which is very conservative and should + // cause no major issues in typical content. + float percentile; + + // Black cutoff strength. To prevent unnatural pixel shimmer and excessive + // darkness in mostly black scenes, as well as avoid black bars from + // affecting the content, (smoothly) cut off any value below this (PQ%) + // threshold. Defaults to 1.0, or 1% PQ. + // + // Setting this to 0.0 (or a negative value) disables this functionality. + float black_cutoff; + + // Allows the peak detection result to be delayed by up to a single frame, + // which can sometimes improve thoughput, at the cost of introducing the + // possibility of 1-frame flickers on transitions. Disabled by default. + bool allow_delayed; + + // --- Deprecated / removed fields + PL_DEPRECATED_IN(v6.313) float minimum_peak; +}; + +#define PL_PEAK_DETECT_DEFAULTS \ + .smoothing_period = 20.0f, \ + .scene_threshold_low = 1.0f, \ + .scene_threshold_high = 3.0f, \ + .percentile = 100.0f, \ + .black_cutoff = 1.0f, + +#define PL_PEAK_DETECT_HQ_DEFAULTS \ + PL_PEAK_DETECT_DEFAULTS \ + .percentile = 99.995f, + +#define pl_peak_detect_params(...) (&(struct pl_peak_detect_params) { PL_PEAK_DETECT_DEFAULTS __VA_ARGS__ }) +PL_API extern const struct pl_peak_detect_params pl_peak_detect_default_params; +PL_API extern const struct pl_peak_detect_params pl_peak_detect_high_quality_params; + +// This function can be used to measure the CLL and FALL of a video +// source automatically, using a compute shader. The measured values are +// smoothed automatically (depending on the parameters), so to keep track of +// the measured results over time, a tone mapping shader state object is used +// to hold the state. Returns false on failure initializing the tone mapping +// object, or if compute shaders are not supported. +// +// It's important that the same shader object is used for successive frames +// belonging to the same source. If the source changes (e.g. due to a file +// change or seek), the user should reset it with `pl_reset_detected_peak` (or +// destroy it and use a new state object). +// +// The parameter `csp` holds the representation of the color values that are +// the input to this function. (They must already be in decoded RGB form, i.e. +// alternate color representations are not supported) +PL_API bool pl_shader_detect_peak(pl_shader sh, struct pl_color_space csp, + pl_shader_obj *state, + const struct pl_peak_detect_params *params); + +// After dispatching the above shader, this function can be used to retrieve +// the detected dynamic HDR10+ metadata parameters. The other fields of +// `metadata` are not written to. Returns whether or not any values were +// written. If not, the values are left untouched, so this can be used to +// safely update `pl_hdr_metadata` values in-place. This function may or may +// not block, depending on the previous setting of `allow_delayed`. +PL_API bool pl_get_detected_hdr_metadata(const pl_shader_obj state, + struct pl_hdr_metadata *metadata); + +// Resets the peak detection state in a given tone mapping state object. This +// is not equal to `pl_shader_obj_destroy`, because it does not destroy any +// state used by `pl_shader_tone_map`. +PL_API void pl_reset_detected_peak(pl_shader_obj state); + +// Feature map extraction (for pl_color_map_args.feature_map). The result +// of this shader should be downscaled / low-passed to the indicated kernel +// size before use. (This does not happen automatically) +PL_API void pl_shader_extract_features(pl_shader sh, struct pl_color_space csp); + +// Deprecated and unused. Libplacebo now always performs a variant of the old +// hybrid tone-mapping, mixing together the intensity (I) and per-channel (LMS) +// results. +enum pl_tone_map_mode { + PL_TONE_MAP_AUTO PL_DEPRECATED_ENUM_IN(v6.269), + PL_TONE_MAP_RGB PL_DEPRECATED_ENUM_IN(v6.269), + PL_TONE_MAP_MAX PL_DEPRECATED_ENUM_IN(v6.269), + PL_TONE_MAP_HYBRID PL_DEPRECATED_ENUM_IN(v6.269), + PL_TONE_MAP_LUMA PL_DEPRECATED_ENUM_IN(v6.269), + PL_TONE_MAP_MODE_COUNT, +}; + +// Deprecated by +enum pl_gamut_mode { + PL_GAMUT_CLIP PL_DEPRECATED_ENUM_IN(v6.269), // pl_gamut_map_clip + PL_GAMUT_WARN PL_DEPRECATED_ENUM_IN(v6.269), // pl_gamut_map_highlight + PL_GAMUT_DARKEN PL_DEPRECATED_ENUM_IN(v6.269), // pl_gamut_map_darken + PL_GAMUT_DESATURATE PL_DEPRECATED_ENUM_IN(v6.269), // pl_gamut_map_desaturate + PL_GAMUT_MODE_COUNT, +}; + +struct pl_color_map_params { + // --- Gamut mapping options + + // Gamut mapping function to use to handle out-of-gamut colors, including + // colors which are out-of-gamut as a consequence of tone mapping. + const struct pl_gamut_map_function *gamut_mapping; + + // Gamut mapping constants, for expert tuning. Leave as default otherwise. + struct pl_gamut_map_constants gamut_constants; + + // Gamut mapping 3DLUT size, for channels ICh. Defaults to {48, 32, 256} + int lut3d_size[3]; + + // Use higher quality, but slower, tricubic interpolation for gamut mapping + // 3DLUTs. May substantially improve the 3DLUT gamut mapping accuracy, in + // particular at smaller 3DLUT sizes. Shouldn't have much effect at the + // default size. + bool lut3d_tricubic; + + // If true, allows the gamut mapping function to expand the gamut, in + // cases where the target gamut exceeds that of the source. If false, + // the source gamut will never be enlarged, even when using a gamut + // mapping function capable of bidirectional mapping. + bool gamut_expansion; + + // --- Tone mapping options + + // Tone mapping function to use to handle out-of-range colors. + const struct pl_tone_map_function *tone_mapping_function; + + // Tone mapping constants, for expert tuning. Leave as default otherwise. + struct pl_tone_map_constants tone_constants; + + // If true, and supported by the given tone mapping function, libplacebo + // will perform inverse tone mapping to expand the dynamic range of a + // signal. libplacebo is not liable for any HDR-induced eye damage. + bool inverse_tone_mapping; + + // Data source to use when tone-mapping. Setting this to a specific + // value allows overriding the default metadata preference logic. + enum pl_hdr_metadata_type metadata; + + // Tone mapping LUT size. Defaults to 256. + int lut_size; + + // HDR contrast recovery strength. If set to a value above 0.0, the source + // image will be divided into high-frequency and low-frequency components, + // and a portion of the high-frequency image is added back onto the + // tone-mapped output. May cause excessive ringing artifacts for some HDR + // sources, but can improve the subjective sharpness and detail left over + // in the image after tone-mapping. + float contrast_recovery; + + // Contrast recovery lowpass kernel size. Defaults to 3.5. Increasing + // or decreasing this will affect the visual appearance substantially. + float contrast_smoothness; + + // --- Debugging options + + // Force the use of a full tone-mapping LUT even for functions that have + // faster pure GLSL replacements (e.g. clip, linear, saturation). + bool force_tone_mapping_lut; + + // Visualize the tone-mapping LUT and gamut mapping 3DLUT, in IPT space. + bool visualize_lut; + + // Controls where to draw the visualization, relative to the rendered + // video (dimensions 0-1). Optional, defaults to the full picture. + pl_rect2df visualize_rect; + + // Controls the rotation of the 3DLUT visualization. + float visualize_hue; // useful range [-pi, pi] + float visualize_theta; // useful range [0, pi/2] + + // Graphically highlight hard-clipped pixels during tone-mapping (i.e. + // pixels that exceed the claimed source luminance range). + bool show_clipping; + + // --- Deprecated fields + PL_DEPRECATED_IN(v6.269) enum pl_tone_map_mode tone_mapping_mode; // removed + PL_DEPRECATED_IN(v6.311) float tone_mapping_param; // see `tone_constants` + PL_DEPRECATED_IN(v6.269) float tone_mapping_crosstalk; // now hard-coded as 0.04 + PL_DEPRECATED_IN(v6.269) enum pl_rendering_intent intent; // see `gamut_mapping` + PL_DEPRECATED_IN(v6.269) enum pl_gamut_mode gamut_mode; // see `gamut_mapping` + PL_DEPRECATED_IN(v6.290) float hybrid_mix; // removed +}; + +#define PL_COLOR_MAP_DEFAULTS \ + .gamut_mapping = &pl_gamut_map_perceptual, \ + .tone_mapping_function = &pl_tone_map_spline, \ + .gamut_constants = { PL_GAMUT_MAP_CONSTANTS }, \ + .tone_constants = { PL_TONE_MAP_CONSTANTS }, \ + .metadata = PL_HDR_METADATA_ANY, \ + .lut3d_size = {48, 32, 256}, \ + .lut_size = 256, \ + .visualize_rect = {0, 0, 1, 1}, \ + .contrast_smoothness = 3.5f, + +#define PL_COLOR_MAP_HQ_DEFAULTS \ + PL_COLOR_MAP_DEFAULTS \ + .contrast_recovery = 0.30f, + +#define pl_color_map_params(...) (&(struct pl_color_map_params) { PL_COLOR_MAP_DEFAULTS __VA_ARGS__ }) +PL_API extern const struct pl_color_map_params pl_color_map_default_params; +PL_API extern const struct pl_color_map_params pl_color_map_high_quality_params; + +// Execution arguments for the `pl_shader_color_map_ex` call. Distinct from +// `pl_color_map_params` because it is filled by internally-provided execution +// metadata, instead of user-tunable aesthetic parameters. +struct pl_color_map_args { + // Input/output color space for the mapping. + struct pl_color_space src; + struct pl_color_space dst; + + // If true, the logic will assume the input has already been linearized by + // the caller (e.g. as part of a previous linear light scaling operation). + bool prelinearized; + + // Object to be used to store generated LUTs. Note that this is the same + // state object used by `pl_shader_detect_peak`, and if that function has + // been called on `state` prior to `pl_shader_color_map`, the detected + // values will be used to guide the tone mapping algorithm. If this is not + // provided, tone/gamut mapping are disabled. + pl_shader_obj *state; + + // Low-resolution intensity feature map, as generated by + // `pl_shader_extract_features`. Optional. No effect if + // `params->contrast_recovery` is disabled. + pl_tex feature_map; +}; + +#define pl_color_map_args(...) (&(struct pl_color_map_args) { __VA_ARGS__ }) + +// Maps `vec4 color` from one color space to another color space according +// to the parameters (described in greater depth above). If `params` is left +// as NULL, it defaults to `&pl_color_map_default_params` +PL_API void pl_shader_color_map_ex(pl_shader sh, + const struct pl_color_map_params *params, + const struct pl_color_map_args *args); + +// Backwards compatibility wrapper around `pl_shader_color_map_ex` +PL_API void pl_shader_color_map(pl_shader sh, const struct pl_color_map_params *params, + struct pl_color_space src, struct pl_color_space dst, + pl_shader_obj *state, bool prelinearized); + +// Applies a set of cone distortion parameters to `vec4 color` in a given color +// space. This can be used to simulate color blindness. See `pl_cone_params` +// for more information. +PL_API void pl_shader_cone_distort(pl_shader sh, struct pl_color_space csp, + const struct pl_cone_params *params); + +PL_API_END + +#endif // LIBPLACEBO_SHADERS_COLORSPACE_H_ diff --git a/third_party/exo-dv5-native/include/libplacebo/shaders/custom.h b/third_party/exo-dv5-native/include/libplacebo/shaders/custom.h new file mode 100644 index 0000000000..a4eec695c4 --- /dev/null +++ b/third_party/exo-dv5-native/include/libplacebo/shaders/custom.h @@ -0,0 +1,341 @@ +/* + * This file is part of libplacebo. + * + * libplacebo is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libplacebo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with libplacebo. If not, see . + */ + +#ifndef LIBPLACEBO_SHADERS_CUSTOM_H_ +#define LIBPLACEBO_SHADERS_CUSTOM_H_ + +#include + +// Functions for writing custom shaders and hooking them into the `pl_renderer` +// pipeline, as well as compatibility functions for parsing shaders in mpv +// format. + +#include +#include +#include + +PL_API_BEGIN + +// Parameters describing custom shader text to be embedded into a `pl_shader` +// object. All of the strings are optional and can be left as NULL, but without +// a `body` in particular, the shader will do nothing useful on its own. +struct pl_custom_shader { + // The prelude contains text such as extra #defines, #extension pragmas, + // or other parts of the shader that must be placed at the very + // beginning (before input layout declarations etc.) + // + // Note: #extension pragmas do not need to be emitted to enable support for + // resource types already attached to the shader (e.g. SSBOs), compute + // shaders, or GPU capabilities known to libplacebo (e.g. subgroups). + const char *prelude; + + // The header contains text such as helper function definitions, extra + // uniforms, shared memory variables or buffer descriptions. + const char *header; + + // A friendly name for the shader. (Optional) + const char *description; + + // The "primary" GLSL code. This will be effectively appended to the "main" + // function. It lives in an environment given by the `input` signature, and + // is expected to return results in a way given by the `output` signature. + // + // Note: In the case of PL_SHADER_SIG_COLOR, the output `vec4 color` is + // allocated by `pl_shader_custom`, the user merely needs to assign to it. + // + // Note: For ease of development it can be useful to have the main logic + // live inside a helper function defined as part of `header`, and specify + // the `body` as a single line that simply calls the helper function. + const char *body; + enum pl_shader_sig input; + enum pl_shader_sig output; + + // Extra descriptors, variables and vertex attributes to attach to the + // resulting `pl_shader_res`. + // + // Note: The names inside these will possibly be replaced by fresh + // identifiers internally, so users should avoid looking for exact string + // matches for the given names inside the `pl_shader_res`. + const struct pl_shader_desc *descriptors; + int num_descriptors; + const struct pl_shader_var *variables; + int num_variables; + const struct pl_shader_va *vertex_attribs; + int num_vertex_attribs; + const struct pl_shader_const *constants; + int num_constants; + + // If true, this shader must be a compute shader. The desired workgroup + // size and shared memory usage can be optionally specified, or 0 if no + // specific work group size or shared memory size restrictions apply. + // + // See also: `pl_shader_res.compute_group_size` + bool compute; + size_t compute_shmem; + int compute_group_size[2]; + + // Fixes the output size requirements of the shader to exact dimensions. + // Optional, if left as 0, means the shader can be dispatched at any size. + int output_w; + int output_h; +}; + +// Append custom shader code, including extra descriptors and variables, to an +// existing `pl_shader` object. Returns whether successful. This function may +// fail in the event that e.g. the custom shader requires compute shaders on +// an unsupported GPU, or exceeds the GPU's shared memory capabilities. +PL_API bool pl_shader_custom(pl_shader sh, const struct pl_custom_shader *params); + +// Which "rendering stages" are available for user shader hooking purposes. +// Except where otherwise noted, all stages are "non-resizable", i.e. the +// shaders already have specific output size requirements. +enum pl_hook_stage { + // Hook stages for the untouched planes, as made available by the source. + // These are all resizable, i.e. there are no specific output stage + // requirements. + PL_HOOK_RGB_INPUT = 1 << 0, + PL_HOOK_LUMA_INPUT = 1 << 1, + PL_HOOK_CHROMA_INPUT = 1 << 2, + PL_HOOK_ALPHA_INPUT = 1 << 3, + PL_HOOK_XYZ_INPUT = 1 << 4, + + // Hook stages for the scaled/aligned planes + PL_HOOK_CHROMA_SCALED = 1 << 5, + PL_HOOK_ALPHA_SCALED = 1 << 6, + + PL_HOOK_NATIVE = 1 << 7, // Combined image in its native color space + PL_HOOK_RGB = 1 << 8, // After conversion to RGB (resizable) + PL_HOOK_LINEAR = 1 << 9, // After linearization but before scaling + PL_HOOK_SIGMOID = 1 << 10, // After sigmoidization + PL_HOOK_PRE_KERNEL = 1 << 11, // Immediately before the main scaler kernel + PL_HOOK_POST_KERNEL = 1 << 12, // Immediately after the main scaler kernel + PL_HOOK_SCALED = 1 << 13, // After scaling, before color management + PL_HOOK_PRE_OUTPUT = 1 << 14, // After color management, before blending/rotation + PL_HOOK_OUTPUT = 1 << 15, // After blending/rotation, before dithering +}; + +// Returns true if a given hook stage is resizable +static inline bool pl_hook_stage_resizable(enum pl_hook_stage stage) { + switch (stage) { + case PL_HOOK_RGB_INPUT: + case PL_HOOK_LUMA_INPUT: + case PL_HOOK_CHROMA_INPUT: + case PL_HOOK_ALPHA_INPUT: + case PL_HOOK_XYZ_INPUT: + case PL_HOOK_NATIVE: + case PL_HOOK_RGB: + return true; + + case PL_HOOK_CHROMA_SCALED: + case PL_HOOK_ALPHA_SCALED: + case PL_HOOK_LINEAR: + case PL_HOOK_SIGMOID: + case PL_HOOK_PRE_KERNEL: + case PL_HOOK_POST_KERNEL: + case PL_HOOK_SCALED: + case PL_HOOK_PRE_OUTPUT: + case PL_HOOK_OUTPUT: + return false; + } + + abort(); +} + +// The different forms of communicating image data between the renderer and +// the hooks +enum pl_hook_sig { + PL_HOOK_SIG_NONE, // No data is passed, no data is received/returned + PL_HOOK_SIG_COLOR, // `vec4 color` already pre-sampled in a `pl_shader` + PL_HOOK_SIG_TEX, // `pl_tex` containing the image data + PL_HOOK_SIG_COUNT, +}; + +struct pl_hook_params { + // GPU objects associated with the `pl_renderer`, which the user may + // use for their own purposes. + pl_gpu gpu; + pl_dispatch dispatch; + + // Helper function to fetch a new temporary texture, using renderer-backed + // storage. This is guaranteed to have sane image usage requirements and a + // 16-bit or floating point format. The user does not need to free/destroy + // this texture in any way. May return NULL. + pl_tex (*get_tex)(void *priv, int width, int height); + void *priv; + + // Which stage triggered the hook to run. + enum pl_hook_stage stage; + + // For `PL_HOOK_SIG_COLOR`, this contains the existing shader object with + // the color already pre-sampled into `vec4 color`. The user may modify + // this as much as they want, as long as they don't dispatch/finalize/reset + // it. + // + // Note that this shader might have specific output size requirements, + // depending on the exact shader stage hooked by the user, and may already + // be a compute shader. + pl_shader sh; + + // For `PL_HOOK_SIG_TEX`, this contains the texture that the user should + // sample from. + // + // Note: This texture object is owned by the renderer, and users must not + // modify its contents. It will not be touched for the duration of a frame, + // but the contents are lost in between frames. + pl_tex tex; + + // The effective current rectangle of the image we're rendering in this + // shader, i.e. the effective rect of the content we're interested in, + // as a crop of either `sh` or `tex` (depending on the signature). + // + // Note: This is still set even for `PL_HOOK_SIG_NONE`! + pl_rect2df rect; + + // The current effective colorspace and representation, of either the + // pre-sampled color (in `sh`), or the contents of `tex`, respectively. + // + // Note: This is still set even for `PL_HOOK_SIG_NONE`! + struct pl_color_repr repr; + struct pl_color_space color; + int components; + + // The representation and colorspace of the original image, for reference. + const struct pl_color_repr *orig_repr; + const struct pl_color_space *orig_color; + + // The (cropped) source and destination rectangles of the overall + // rendering. These are functionallty equivalent to `image.crop` and + // `target.crop`, respectively, but `src_rect` in particular may change as + // a result of previous hooks being executed. (e.g. prescalers) + pl_rect2df src_rect; + pl_rect2d dst_rect; +}; + +struct pl_hook_res { + // If true, the hook is assumed to have "failed" or errored in some way, + // and all other fields are ignored. + bool failed; + + // What type of output this hook is returning. + // Note: If this is `PL_HOOK_SIG_NONE`, all other fields are ignored. + enum pl_hook_sig output; + + // For `PL_HOOK_SIG_COLOR`, this *must* be set to a valid `pl_shader` + // object containing the sampled color value (i.e. with an output signature + // of `PL_SHADER_SIG_COLOR`), and *should* be allocated from the given + // `pl_dispatch` object. Ignored otherwise. + pl_shader sh; + + // For `PL_HOOK_SIG_TEX`, this *must* contain the texture object containing + // the result of rendering the hook. This *should* be a texture allocated + // using the given `get_tex` callback, to ensure the format and texture + // usage flags are compatible with what the renderer expects. + pl_tex tex; + + // For shaders that return some sort of output, this contains the + // new/altered versions of the existing "current texture" metadata. + struct pl_color_repr repr; + struct pl_color_space color; + int components; + + // This contains the new effective rect of the contents. This may be + // different from the original `rect` for resizable passes. Ignored for + // non-resizable passes. + pl_rect2df rect; +}; + +enum pl_hook_par_mode { + PL_HOOK_PAR_VARIABLE, // normal shader variable + PL_HOOK_PAR_DYNAMIC, // dynamic shader variable, e.g. per-frame changing + PL_HOOK_PAR_CONSTANT, // fixed at compile time (e.g. for array sizes), + // must be scalar (non-vector/matrix) + PL_HOOK_PAR_DEFINE, // defined in the preprocessor, must be `int` + PL_HOOK_PAR_MODE_COUNT, +}; + +typedef union pl_var_data { + int i; + unsigned u; + float f; +} pl_var_data; + +struct pl_hook_par { + // Name as used in the shader. + const char *name; + + // Type of this shader parameter, and how it's manifested in the shader. + enum pl_var_type type; + enum pl_hook_par_mode mode; + + // Human-readable explanation of this parameter. (Optional) + const char *description; + + // Mutable data pointer to current value of variable. + pl_var_data *data; + + // Default/initial value, and lower/upper bounds. + pl_var_data initial; + pl_var_data minimum; + pl_var_data maximum; + + // Human-readable names for the variants of an integer option. This array + // can be indexed directly by integer values, ranging from `minimum.i` to + // `maximum.i`. May be NULL, in which case options are unnamed. + const char * const *names; +}; + +// Struct describing a hook. +// +// Note: Users may freely create their own instances of this struct, there is +// nothing particularly special about `pl_mpv_user_shader_parse`. +struct pl_hook { + enum pl_hook_stage stages; // Which stages to hook on + enum pl_hook_sig input; // Which input signature this hook expects + void *priv; // Arbitrary user context + + // Custom tunable shader parameters exported by this hook. These may be + // updated at any time by the user, to influence the behavior of the hook. + // Contents are arbitrary and subject to the method of hook construction. + const struct pl_hook_par *parameters; + int num_parameters; + + // Called at the beginning of passes, to reset/initialize the hook. (Optional) + void (*reset)(void *priv); + + // The hook function itself. Called by the renderer at any of the indicated + // hook stages. See `pl_hook_res` for more info on the return values. + struct pl_hook_res (*hook)(void *priv, const struct pl_hook_params *params); + + // Unique signature identifying this hook, used to disable misbehaving hooks. + // All hooks with the same signature will be disabled, should they fail to + // execute during run-time. + uint64_t signature; +}; + +// Compatibility layer with `mpv` user shaders. See the mpv man page for more +// information on the format. Will return `NULL` if the shader fails parsing. +// +// The resulting `pl_hook` objects should be destroyed with the corresponding +// destructor when no longer needed. +PL_API const struct pl_hook * +pl_mpv_user_shader_parse(pl_gpu gpu, const char *shader_text, size_t shader_len); + +PL_API void pl_mpv_user_shader_destroy(const struct pl_hook **hook); + +PL_API_END + +#endif // LIBPLACEBO_SHADERS_CUSTOM_H_ diff --git a/third_party/exo-dv5-native/include/libplacebo/shaders/deinterlacing.h b/third_party/exo-dv5-native/include/libplacebo/shaders/deinterlacing.h new file mode 100644 index 0000000000..c67407b1ea --- /dev/null +++ b/third_party/exo-dv5-native/include/libplacebo/shaders/deinterlacing.h @@ -0,0 +1,141 @@ + +/* + * This file is part of libplacebo, which is normally licensed under the terms + * of the LGPL v2.1+. However, this file (film_grain.h) is also available under + * the terms of the more permissive MIT license: + * + * Copyright (c) 2018-2019 Niklas Haas + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#ifndef LIBPLACEBO_SHADERS_DEINTERLACING_H_ +#define LIBPLACEBO_SHADERS_DEINTERLACING_H_ + +#include + +PL_API_BEGIN + +enum pl_field { + PL_FIELD_NONE = 0, // no deinterlacing + PL_FIELD_EVEN, // "top" fields, with even y coordinates + PL_FIELD_ODD, // "bottom" fields, with odd y coordinates + + // Convenience aliases + PL_FIELD_TOP = PL_FIELD_EVEN, + PL_FIELD_BOTTOM = PL_FIELD_ODD, +}; + +static inline enum pl_field pl_field_other(enum pl_field field) +{ + switch (field) { + case PL_FIELD_EVEN: return PL_FIELD_ODD; + case PL_FIELD_ODD: return PL_FIELD_EVEN; + default: return field; + } +} + +struct pl_field_pair { + // Top texture. If only this is specified, it's assumed to contain both + // fields in an interleaved fashion (MBAFF). + // + // Note: Support for separate fields (PAFF), is currently pending, so this + // is the only way to provide interlaced frames at the moment. + pl_tex top; +}; + +#define pl_field_pair(...) ((struct pl_field_pair) { __VA_ARGS__ }) + +struct pl_deinterlace_source { + // Previous, current and next source (interlaced) frames. `prev` and `next` + // may be NULL, but `cur` is required. If present, they must all have the + // exact same texture dimensions. + // + // Note: `prev` and `next` are only required for PL_DEINTERLACE_YADIF. + struct pl_field_pair prev, cur, next; + + // The parity of the current field to output. This field will be unmodified + // from `cur`, with the corresponding other field interpolated. + // + // If this is `PL_FIELD_NONE`, no deinterlacing is performed, and the + // texture is merely sampled as-is. + enum pl_field field; + + // The parity of the first frame in a stream. Set this the field that is + // (conceptually) ordered first in time. + // + // If this is `PL_FIELD_NONE`, it will instead default to `PL_FIELD_TOP`. + enum pl_field first_field; + + // Components to deinterlace. Components not specified will be ignored. + // Optional, if left as 0, all components will be deinterlaced. + uint8_t component_mask; +}; + +#define pl_deinterlace_source(...) (&(struct pl_deinterlace_source) { __VA_ARGS__ }) + +enum pl_deinterlace_algorithm { + // No-op deinterlacing, just sample the weaved frame un-touched. + PL_DEINTERLACE_WEAVE = 0, + + // Naive bob deinterlacing. Doubles the field lines vertically. + PL_DEINTERLACE_BOB, + + // "Yet another deinterlacing filter". Deinterlacer with temporal and + // spatial information. Based on FFmpeg's Yadif filter algorithm, but + // adapted slightly for the GPU. + PL_DEINTERLACE_YADIF, + + // "Bob weaver" deinterlacer. Motion-adaptive deinterlacer based on yadif, + // with the use of w3fdif and cubic interpolation algorithms. + PL_DEINTERLACE_BWDIF, + + PL_DEINTERLACE_ALGORITHM_COUNT, +}; + +// Returns whether or not an algorithm requires `prev`/`next` refs to be set. +static inline bool pl_deinterlace_needs_refs(enum pl_deinterlace_algorithm algo) +{ + return algo >= PL_DEINTERLACE_YADIF; +} + +struct pl_deinterlace_params { + // Algorithm to use. The recommended default is PL_DEINTERLACE_YADIF, which + // provides a good trade-off of quality and speed. + enum pl_deinterlace_algorithm algo; + + // Skip the spatial interlacing check. (PL_DEINTERLACE_YADIF only) + bool skip_spatial_check; +}; + +#define PL_DEINTERLACE_DEFAULTS \ + .algo = PL_DEINTERLACE_BWDIF, + +#define pl_deinterlace_params(...) (&(struct pl_deinterlace_params) { PL_DEINTERLACE_DEFAULTS __VA_ARGS__ }) +PL_API extern const struct pl_deinterlace_params pl_deinterlace_default_params; + +// Deinterlaces a set of interleaved source frames and outputs the result into +// `vec4 color`. If `params` is left as NULL, it defaults to +// `&pl_deinterlace_default_params`. +PL_API void pl_shader_deinterlace(pl_shader sh, const struct pl_deinterlace_source *src, + const struct pl_deinterlace_params *params); + +PL_API_END + +#endif // LIBPLACEBO_SHADERS_DEINTERLACING_H_ diff --git a/third_party/exo-dv5-native/include/libplacebo/shaders/dithering.h b/third_party/exo-dv5-native/include/libplacebo/shaders/dithering.h new file mode 100644 index 0000000000..9146c810ff --- /dev/null +++ b/third_party/exo-dv5-native/include/libplacebo/shaders/dithering.h @@ -0,0 +1,140 @@ +/* + * This file is part of libplacebo. + * + * libplacebo is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libplacebo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with libplacebo. If not, see . + */ + +#ifndef LIBPLACEBO_SHADERS_DITHERING_H_ +#define LIBPLACEBO_SHADERS_DITHERING_H_ + +// Dithering shaders + +#include +#include +#include + +PL_API_BEGIN + +enum pl_dither_method { + // Dither with blue noise. Very high quality, but requires the use of a + // LUT. Warning: Computing a blue noise texture with a large size can be + // very slow, however this only needs to be performed once. Even so, using + // this with a `lut_size` greater than 6 is generally ill-advised. This is + // the preferred/default dither method. + PL_DITHER_BLUE_NOISE, + + // Dither with an ordered (bayer) dither matrix, using a LUT. Low quality, + // and since this also uses a LUT, there's generally no advantage to picking + // this instead of `PL_DITHER_BLUE_NOISE`. It's mainly there for testing. + PL_DITHER_ORDERED_LUT, + + // The same as `PL_DITHER_ORDERED_LUT`, but uses fixed function math instead + // of a LUT. This is faster, but only supports a fixed dither matrix size + // of 16x16 (equal to a `lut_size` of 4). + PL_DITHER_ORDERED_FIXED, + + // Dither with white noise. This does not require a LUT and is fairly cheap + // to compute. Unlike the other modes it doesn't show any repeating + // patterns either spatially or temporally, but the downside is that this + // is visually fairly jarring due to the presence of low frequencies in the + // noise spectrum. + PL_DITHER_WHITE_NOISE, + + PL_DITHER_METHOD_COUNT, +}; + +struct pl_dither_params { + // The source of the dither noise to use. + enum pl_dither_method method; + + // For the dither methods which require the use of a LUT, this controls + // the size of the LUT (base 2). If left as NULL, this defaults to 6, which + // is equivalent to a 64x64 dither matrix. Must not be larger than 8. + int lut_size; + + // Enables temporal dithering. This reduces the persistence of dithering + // artifacts by perturbing the dithering matrix per frame. + // Warning: This can cause nasty aliasing artifacts on some LCD screens. + bool temporal; + + // Gamma function to use for dither gamma correction. This will only have + // an effect when dithering to low bit depths (<= 4). + enum pl_color_transfer transfer; +}; + +#define PL_DITHER_DEFAULTS \ + .method = PL_DITHER_BLUE_NOISE, \ + .lut_size = 6, \ + /* temporal dithering commonly flickers on LCDs */ \ + .temporal = false, + +#define pl_dither_params(...) (&(struct pl_dither_params) { PL_DITHER_DEFAULTS __VA_ARGS__ }) +PL_API extern const struct pl_dither_params pl_dither_default_params; + +// Dither the colors to a lower depth, given in bits. This can be used on input +// colors of any precision. Basically, this rounds the colors to only linear +// multiples of the stated bit depth. The average intensity of the result +// will not change (i.e., the dither noise is balanced in both directions). +// If `params` is NULL, it defaults to &pl_dither_default_params. +// +// For the dither methods which require the use of a LUT, `dither_state` must +// be set to a valid pointer. To avoid thrashing the resource, users should +// avoid trying to re-use the same LUT for different dither configurations. If +// passed as NULL, libplacebo will automatically fall back to dither algorithms +// that don't require the use of a LUT. +// +// Warning: This dithering algorithm is not gamma-invariant; so using it for +// very low bit depths (below 4 or so) will noticeably increase the brightness +// of the resulting image. When doing low bit depth dithering for aesthetic +// purposes, it's recommended that the user explicitly (de)linearize the colors +// before and after this algorithm. +PL_API void pl_shader_dither(pl_shader sh, int new_depth, + pl_shader_obj *dither_state, + const struct pl_dither_params *params); + +struct pl_error_diffusion_params { + // Both the input and output texture must be provided up-front, with the + // same size. The output texture must be storable, and the input texture + // must be sampleable. + pl_tex input_tex; + pl_tex output_tex; + + // Depth to dither to. Required. + int new_depth; + + // Error diffusion kernel to use. Optional. If unspecified, defaults to + // `&pl_error_diffusion_sierra_lite`. + const struct pl_error_diffusion_kernel *kernel; +}; + +#define pl_error_diffusion_params(...) (&(struct pl_error_diffusion_params) { __VA_ARGS__ }) + +// Computes the shared memory requirements for a given error diffusion kernel. +// This can be used to test up-front whether or not error diffusion would be +// supported or not, before having to initialize textures. +PL_API size_t pl_error_diffusion_shmem_req(const struct pl_error_diffusion_kernel *kernel, + int height); + +// Apply an error diffusion dithering kernel. This is a much more expensive and +// heavy dithering method, and is not generally recommended for realtime usage +// where performance is critical. +// +// Requires compute shader support. Returns false if dithering fail e.g. as a +// result of shader memory limits being exceeded. The resulting shader must be +// dispatched with a work group count of exactly 1. +PL_API bool pl_shader_error_diffusion(pl_shader sh, const struct pl_error_diffusion_params *params); + +PL_API_END + +#endif // LIBPLACEBO_SHADERS_DITHERING_H_ diff --git a/third_party/exo-dv5-native/include/libplacebo/shaders/film_grain.h b/third_party/exo-dv5-native/include/libplacebo/shaders/film_grain.h new file mode 100644 index 0000000000..8a9c78bb0b --- /dev/null +++ b/third_party/exo-dv5-native/include/libplacebo/shaders/film_grain.h @@ -0,0 +1,137 @@ +/* + * This file is part of libplacebo, which is normally licensed under the terms + * of the LGPL v2.1+. However, this file (film_grain.h) is also available under + * the terms of the more permissive MIT license: + * + * Copyright (c) 2018-2019 Niklas Haas + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#ifndef LIBPLACEBO_SHADERS_FILM_GRAIN_H_ +#define LIBPLACEBO_SHADERS_FILM_GRAIN_H_ + +// Film grain synthesis shaders for AV1 / H.274. + +#include +#include + +#include +#include + +PL_API_BEGIN + +enum pl_film_grain_type { + PL_FILM_GRAIN_NONE = 0, + PL_FILM_GRAIN_AV1, + PL_FILM_GRAIN_H274, + PL_FILM_GRAIN_COUNT, +}; + +// AV1 film grain parameters. For the exact meaning of these, see the AV1 +// specification (section 6.8.20). +struct pl_av1_grain_data { + int num_points_y; + uint8_t points_y[14][2]; // [n][0] = value, [n][1] = scaling + bool chroma_scaling_from_luma; + int num_points_uv[2]; // should be {0} for grayscale images + uint8_t points_uv[2][10][2]; // like points_y for points_uv[0, 1] = u, v + int scaling_shift; + int ar_coeff_lag; + int8_t ar_coeffs_y[24]; + int8_t ar_coeffs_uv[2][25]; + int ar_coeff_shift; + int grain_scale_shift; + int8_t uv_mult[2]; + int8_t uv_mult_luma[2]; + int16_t uv_offset[2]; // 9-bit value, range [-256, 255] + bool overlap; +}; + +// H.274 film grain parameters. For the exact meaning of these, see the H.274 +// specification (section 8.5). +struct pl_h274_grain_data { + int model_id; + int blending_mode_id; + int log2_scale_factor; + bool component_model_present[3]; + uint16_t num_intensity_intervals[3]; + uint8_t num_model_values[3]; + const uint8_t *intensity_interval_lower_bound[3]; + const uint8_t *intensity_interval_upper_bound[3]; + const int16_t (*comp_model_value[3])[6]; +}; + +// Tagged union for film grain data +struct pl_film_grain_data { + enum pl_film_grain_type type; // film grain type + uint64_t seed; // shared seed value + + union { + // Warning: These values are not sanity-checked at all, Invalid grain + // data results in undefined behavior! + struct pl_av1_grain_data av1; + struct pl_h274_grain_data h274; + } params; +}; + +// Options for the `pl_shader_film_grain` call. +struct pl_film_grain_params { + // Required for all film grain types: + struct pl_film_grain_data data; // film grain data + pl_tex tex; // texture to sample from + struct pl_color_repr *repr; // underlying color representation (see notes) + int components; + int component_mapping[4]; // same as `struct pl_plane` + + // Notes for `repr`: + // - repr->bits affects the rounding for grain generation + // - repr->levels affects whether or not we clip to full range or not + // - repr->sys affects the interpretation of channels + // - *repr gets normalized by this shader, which is why it's a pointer + + // Required for PL_FILM_GRAIN_AV1 only: + pl_tex luma_tex; // "luma" texture (see notes) + int luma_comp; // index of luma in `luma_tex` + + // Notes for `luma_tex`: + // - `luma_tex` must be specified if the `tex` does not itself contain the + // "luma-like" component. For XYZ systems, the Y channel is the luma + // component. For RGB systems, the G channel is. +}; + +#define pl_film_grain_params(...) (&(struct pl_film_grain_params) { __VA_ARGS__ }) + +// Test if film grain needs to be applied. This is a helper function that users +// can use to decide whether or not `pl_shader_film_grain` needs to be called, +// based on the given grain metadata. +PL_API bool pl_needs_film_grain(const struct pl_film_grain_params *params); + +// Sample from a texture while applying film grain at the same time. +// `grain_state` must be unique for every plane configuration, as it may +// contain plane-dependent state. +// +// Returns false on any error, or if film grain generation is not supported +// due to GLSL limitations. +PL_API bool pl_shader_film_grain(pl_shader sh, pl_shader_obj *grain_state, + const struct pl_film_grain_params *params); + +PL_API_END + +#endif // LIBPLACEBO_SHADERS_FILM_GRAIN_H_ diff --git a/third_party/exo-dv5-native/include/libplacebo/shaders/icc.h b/third_party/exo-dv5-native/include/libplacebo/shaders/icc.h new file mode 100644 index 0000000000..35933ea366 --- /dev/null +++ b/third_party/exo-dv5-native/include/libplacebo/shaders/icc.h @@ -0,0 +1,135 @@ +/* + * This file is part of libplacebo. + * + * libplacebo is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libplacebo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with libplacebo. If not, see . + */ + +#ifndef LIBPLACEBO_SHADERS_ICC_H_ +#define LIBPLACEBO_SHADERS_ICC_H_ + +// Functions for generating and applying ICC-derived (3D)LUTs + +#include +#include + +PL_API_BEGIN + +struct pl_icc_params { + // The rendering intent to use, for profiles with multiple intents. A + // recommended value is PL_INTENT_RELATIVE_COLORIMETRIC for color-accurate + // video reproduction, or PL_INTENT_PERCEPTUAL for profiles containing + // meaningful perceptual mapping tables for some more suitable color space + // like BT.709. + // + // If this is set to the special value PL_INTENT_AUTO, will use the + // preferred intent provided by the profile header. + enum pl_rendering_intent intent; + + // The size of the 3DLUT to generate. If left as NULL, these individually + // default to values appropriate for the profile. (Based on internal + // precision heuristics) + // + // Note: Setting this manually is strongly discouraged, as it can result + // in excessively high 3DLUT sizes where a much smaller LUT would have + // sufficed. + int size_r, size_g, size_b; + + // This field can be used to override the detected brightness level of the + // ICC profile. If you set this to the special value 0 (or a negative + // number), libplacebo will attempt reading the brightness value from the + // ICC profile's tagging (if available), falling back to PL_COLOR_SDR_WHITE + // if unavailable. + float max_luma; + + // Force black point compensation. May help avoid crushed or raised black + // points on "improper" profiles containing e.g. colorimetric tables that + // do not round-trip. Should not be required on well-behaved profiles, + // or when using PL_INTENT_PERCEPTUAL, but YMMV. + bool force_bpc; + + // If provided, this pl_cache instance will be used, instead of the + // GPU-internal cache, to cache the generated 3DLUTs. Note that these can + // get large, especially for large values of size_{r,g,b}, so the user may + // wish to split this cache off from the main shader cache. (Optional) + pl_cache cache; + + // Deprecated legacy caching API. Replaced by `cache`. + PL_DEPRECATED_IN(v6.321) void *cache_priv; + PL_DEPRECATED_IN(v6.321) void (*cache_save)(void *priv, uint64_t sig, const uint8_t *cache, size_t size); + PL_DEPRECATED_IN(v6.321) bool (*cache_load)(void *priv, uint64_t sig, uint8_t *cache, size_t size); +}; + +#define PL_ICC_DEFAULTS \ + .intent = PL_INTENT_RELATIVE_COLORIMETRIC, \ + .max_luma = PL_COLOR_SDR_WHITE, + +#define pl_icc_params(...) (&(struct pl_icc_params) { PL_ICC_DEFAULTS __VA_ARGS__ }) +PL_API extern const struct pl_icc_params pl_icc_default_params; + +// This object represents a "parsed" ICC profile. +typedef const struct pl_icc_object_t { + // Provided params, with the `intent` and `size` fields set (as described) + struct pl_icc_params params; + + // Signature of the corresponding ICC profile. + uint64_t signature; + + // Detected color space (or UNKNOWN for profiles which don't contain an + // exact match), with HDR metedata set to the detected gamut and + // white/black value ranges. + struct pl_color_space csp; + + // Best estimate of profile gamma. This only serves as a rough guideline. + float gamma; + + // Smallest containing primary set, always set. + enum pl_color_primaries containing_primaries; +} *pl_icc_object; + +// Attempts opening/parsing the contents of an ICC profile. The resulting +// object is memory managed and may outlive the original profile - access +// to the underlying profile is no longer needed once this returns. +PL_API pl_icc_object pl_icc_open(pl_log log, const struct pl_icc_profile *profile, + const struct pl_icc_params *params); +PL_API void pl_icc_close(pl_icc_object *icc); + +// Update an existing pl_icc_object, which may be NULL, replacing it by the +// new profile and parameters (if incompatible). +// +// Returns success. `obj` is set to the created profile, or NULL on error. +// +// Note: If `profile->signature` matches `(*obj)->signature`, or if `profile` is +// NULL, then the existing profile is directly reused, with only the effective +// parameters changing. In this case, `profile->data` is also *not* read from, +// and may safely be NULL. +PL_API bool pl_icc_update(pl_log log, pl_icc_object *obj, + const struct pl_icc_profile *profile, + const struct pl_icc_params *params); + +// Decode the input from the colorspace determined by the attached ICC profile +// to linear light RGB (in the profile's containing primary set). `lut` must be +// set to a shader object that will store the GPU resources associated with the +// generated LUT. The resulting color space will be written to `out_csp`. +PL_API void pl_icc_decode(pl_shader sh, pl_icc_object profile, pl_shader_obj *lut, + struct pl_color_space *out_csp); + +// Encode the input from linear light RGB (in the profile's containing primary +// set) into the colorspace determined by the attached ICC profile. `lut` must +// be set to a shader object that will store the GPU resources associated with +// the generated LUT. +PL_API void pl_icc_encode(pl_shader sh, pl_icc_object profile, pl_shader_obj *lut); + +PL_API_END + +#endif // LIBPLACEBO_SHADERS_ICC_H_ diff --git a/third_party/exo-dv5-native/include/libplacebo/shaders/lut.h b/third_party/exo-dv5-native/include/libplacebo/shaders/lut.h new file mode 100644 index 0000000000..6e30ddc735 --- /dev/null +++ b/third_party/exo-dv5-native/include/libplacebo/shaders/lut.h @@ -0,0 +1,78 @@ +/* + * This file is part of libplacebo. + * + * libplacebo is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libplacebo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with libplacebo. If not, see . + */ + +#ifndef LIBPLACEBO_SHADERS_LUT_H_ +#define LIBPLACEBO_SHADERS_LUT_H_ + +// Shaders for loading and applying arbitrary custom 1D/3DLUTs + +#include +#include + +PL_API_BEGIN + +// Struct defining custom LUTs +// +// Note: Users may freely create their own instances of this struct, there is +// nothing particularly special about `pl_lut_parse_cube`. +struct pl_custom_lut { + // Some unique signature identifying this LUT, needed to detect state + // changes (for cache invalidation). This should ideally be a hash of the + // file contents. (Which is what `pl_lut_parse_*` will set it to.) + uint64_t signature; + + // Size of each dimension, in the order R, G, B. For 1D LUTs, only the R + // dimension should be specified (the others left as 0). + int size[3]; + + // Raw LUT data itself, in properly scaled floating point format. For 3D + // LUTs, the innermost dimension is the first dimension (R), and the + // outermost dimension is the last dimension (B). Individual color samples + // are in the order R, G, B. + const float *data; + + // Extra input/output shaper matrices. Ignored if equal to {0}. This is + // mostly useful for 1D LUTs, since 3D LUTs can bake the shaper matrix into + // the LUT itself - but it can still help optimize LUT precision. + pl_matrix3x3 shaper_in, shaper_out; + + // Nominal metadata for the input/output of a LUT. Left as {0} if unknown. + // Note: This is purely informative, `pl_shader_custom_lut` ignores it. + struct pl_color_repr repr_in, repr_out; + struct pl_color_space color_in, color_out; +}; + +// Parse a 3DLUT in .cube format. Returns NULL if the file fails parsing. +PL_API struct pl_custom_lut *pl_lut_parse_cube(pl_log log, const char *str, size_t str_len); + +// Frees a LUT created by `pl_lut_parse_*`. +PL_API void pl_lut_free(struct pl_custom_lut **lut); + +// Apply a `pl_custom_lut`. The user is responsible for ensuring colors going +// into the LUT are in the expected format as informed by the LUT metadata. +// +// `lut_state` must be a pointer to a NULL-initialized shader state object that +// will be used to encapsulate any required GPU state. +// +// Note: `lut` does not have to be allocated by `pl_lut_parse_*`. It can be a +// struct filled out by the user. +PL_API void pl_shader_custom_lut(pl_shader sh, const struct pl_custom_lut *lut, + pl_shader_obj *lut_state); + +PL_API_END + +#endif // LIBPLACEBO_SHADERS_LUT_H_ diff --git a/third_party/exo-dv5-native/include/libplacebo/shaders/sampling.h b/third_party/exo-dv5-native/include/libplacebo/shaders/sampling.h new file mode 100644 index 0000000000..20eb0781e8 --- /dev/null +++ b/third_party/exo-dv5-native/include/libplacebo/shaders/sampling.h @@ -0,0 +1,248 @@ +/* + * This file is part of libplacebo. + * + * libplacebo is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libplacebo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with libplacebo. If not, see . + */ + +#ifndef LIBPLACEBO_SHADERS_SAMPLING_H_ +#define LIBPLACEBO_SHADERS_SAMPLING_H_ + +// Sampling operations. These shaders perform some form of sampling operation +// from a given pl_tex. In order to use these, the pl_shader *must* have been +// created using the same `gpu` as the originating `pl_tex`. Otherwise, this +// is undefined behavior. They require nothing (PL_SHADER_SIG_NONE) and return +// a color (PL_SHADER_SIG_COLOR). + +#include +#include +#include + +PL_API_BEGIN + +// Common parameters for sampling operations +struct pl_sample_src { + // There are two mutually exclusive ways of providing the source to sample + // from: + // + // 1. Provide the texture and sampled region directly. This generates + // a shader with input signature `PL_SHADER_SIG_NONE`, which binds the + // texture as a descriptor (and the coordinates as a vertex attribute) + pl_tex tex; // texture to sample + pl_rect2df rect; // sub-rect to sample from (optional) + enum pl_tex_address_mode address_mode; // preferred texture address mode + + // 2. Have the shader take it as an argument. Doing this requires + // specifying the missing metadata of the texture backing the sampler, so + // that the shader generation can generate the correct code. + int tex_w, tex_h; // dimensions of the actual texture + enum pl_fmt_type format; // format of the sampler being accepted + enum pl_sampler_type sampler; // type of the sampler being accepted + enum pl_tex_sample_mode mode; // sample mode of the sampler being accepted + float sampled_w, sampled_h; // dimensions of the sampled region (optional) + + // Common metadata for both sampler input types: + int components; // number of components to sample (optional) + uint8_t component_mask; // bitmask of components to sample (optional) + int new_w, new_h; // dimensions of the resulting output (optional) + float scale; // factor to multiply into sampled signal (optional) + + // Note: `component_mask` and `components` are mutually exclusive, the + // former is preferred if both are specified. +}; + +#define pl_sample_src(...) (&(struct pl_sample_src) { __VA_ARGS__ }) + +struct pl_deband_params { + // The number of debanding steps to perform per sample. Each step reduces a + // bit more banding, but takes time to compute. Note that the strength of + // each step falls off very quickly, so high numbers (>4) are practically + // useless. Defaults to 1. + int iterations; + + // The debanding filter's cut-off threshold. Higher numbers increase the + // debanding strength dramatically, but progressively diminish image + // details. Defaults to 3.0. + float threshold; + + // The debanding filter's initial radius. The radius increases linearly + // for each iteration. A higher radius will find more gradients, but a + // lower radius will smooth more aggressively. Defaults to 16.0. + float radius; + + // Add some extra noise to the image. This significantly helps cover up + // remaining quantization artifacts. Higher numbers add more noise. + // Note: When debanding HDR sources, even a small amount of grain can + // result in a very big change to the brightness level. It's recommended to + // either scale this value down or disable it entirely for HDR. + // + // Defaults to 4.0, which is very mild. + float grain; + + // 'Neutral' grain value for each channel being debanded (sorted in order + // from low to high index). Grain application will be modulated to avoid + // disturbing colors close to this value. Set this to a value corresponding + // to black in the relevant colorspace. + float grain_neutral[3]; +}; + +#define PL_DEBAND_DEFAULTS \ + .iterations = 1, \ + .threshold = 3.0, \ + .radius = 16.0, \ + .grain = 4.0, + +#define pl_deband_params(...) (&(struct pl_deband_params) {PL_DEBAND_DEFAULTS __VA_ARGS__ }) +PL_API extern const struct pl_deband_params pl_deband_default_params; + +// Debands a given texture and returns the sampled color in `vec4 color`. If +// `params` is left as NULL, it defaults to &pl_deband_default_params. +// +// Note: This can also be used as a pure grain function, by setting the number +// of iterations to 0. +PL_API void pl_shader_deband(pl_shader sh, const struct pl_sample_src *src, + const struct pl_deband_params *params); + +// Performs direct / native texture sampling, using whatever texture filter is +// available (linear for linearly sampleable sources, nearest otherwise). +// +// Note: This is generally very low quality and should be avoided if possible, +// for both upscaling and downscaling. +PL_API bool pl_shader_sample_direct(pl_shader sh, const struct pl_sample_src *src); + +// Performs hardware-accelerated nearest neighbour sampling. This is similar to +// `pl_shader_sample_direct`, but forces nearest neighbour interpolation. +PL_API bool pl_shader_sample_nearest(pl_shader sh, const struct pl_sample_src *src); + +// Performs hardware-accelerated bilinear sampling. This is similar to +// `pl_shader_sample_direct`, but forces bilinear interpolation. +PL_API bool pl_shader_sample_bilinear(pl_shader sh, const struct pl_sample_src *src); + +// Optimized versions of specific, strictly positive scaler kernels that take +// adantage of linear texture sampling to reduce the number of fetches needed +// by a factor of four. This family of functions performs radius-2 scaling +// with only four texture fetches, which is far more efficient than using +// the generalized 1D scaling method. Only works well for upscaling. +PL_API bool pl_shader_sample_bicubic(pl_shader sh, const struct pl_sample_src *src); +PL_API bool pl_shader_sample_hermite(pl_shader sh, const struct pl_sample_src *src); +PL_API bool pl_shader_sample_gaussian(pl_shader sh, const struct pl_sample_src *src); + +// A sampler that is similar to nearest neighbour sampling, but tries to +// preserve pixel aspect ratios. This is mathematically equivalent to taking an +// idealized image with square pixels, sampling it at an infinite resolution, +// and then downscaling that to the desired resolution. (Hence it being called +// "oversample"). Good for pixel art. +// +// The threshold provides a cutoff threshold below which the contribution of +// pixels should be ignored, trading some amount of aspect ratio distortion for +// a slightly crisper image. A value of `threshold == 0.5` makes this filter +// equivalent to regular nearest neighbour sampling. +PL_API bool pl_shader_sample_oversample(pl_shader sh, const struct pl_sample_src *src, + float threshold); + +struct pl_sample_filter_params { + // The filter to use for sampling. + struct pl_filter_config filter; + + // Antiringing strength. A value of 0.0 disables antiringing, and a value + // of 1.0 enables full-strength antiringing. Defaults to 0.0 if + // unspecified. + // + // Note: Ignored if `filter.antiring` is already set to something nonzero. + float antiring; + + // Disable the use of compute shaders (e.g. if rendering to non-storable tex) + bool no_compute; + // Disable the use of filter widening / anti-aliasing (for downscaling) + bool no_widening; + + // This shader object is used to store the LUT, and will be recreated + // if necessary. To avoid thrashing the resource, users should avoid trying + // to re-use the same LUT for different filter configurations or scaling + // ratios. Must be set to a valid pointer, and the target NULL-initialized. + pl_shader_obj *lut; + + // Deprecated / removed fields + PL_DEPRECATED_IN(v6.335) int lut_entries; // hard-coded as 256 + PL_DEPRECATED_IN(v6.335) float cutoff; // hard-coded as 1e-3 +}; + +#define pl_sample_filter_params(...) (&(struct pl_sample_filter_params) { __VA_ARGS__ }) + +// Performs polar sampling. This internally chooses between an optimized compute +// shader, and various fragment shaders, depending on the supported GLSL version +// and GPU features. Returns whether or not it was successful. +// +// Note: `params->filter.polar` must be true to use this function. +PL_API bool pl_shader_sample_polar(pl_shader sh, const struct pl_sample_src *src, + const struct pl_sample_filter_params *params); + +// Performs orthogonal (1D) sampling. Using this twice in a row (once vertical +// and once horizontal) effectively performs a 2D upscale. This is lower +// quality than polar sampling, but significantly faster, and therefore the +// recommended default. Returns whether or not it was successful. +// +// `src` must represent a scaling operation that only scales in one direction, +// i.e. either only X or only Y. The other direction must be left unscaled. +// +// Note: Due to internal limitations, this may currently only be used on 2D +// textures - even though the basic principle would work for 1D and 3D textures +// as well. +PL_API bool pl_shader_sample_ortho2(pl_shader sh, const struct pl_sample_src *src, + const struct pl_sample_filter_params *params); + +struct pl_distort_params { + // An arbitrary 2x2 affine transformation to apply to the input image. + // For simplicity, the input image is explicitly centered and scaled such + // that the longer dimension is in [-1,1], before applying this. + pl_transform2x2 transform; + + // If true, the texture is placed inside the center of the canvas without + // scaling. If false, it is effectively stretched to the canvas size. + bool unscaled; + + // If true, the transformation is automatically scaled down and shifted to + // ensure that the resulting image fits inside the output canvas. + bool constrain; + + // If true, use bicubic interpolation rather than faster bilinear + // interpolation. Higher quality but slower. + bool bicubic; + + // Specifies the texture address mode to use when sampling out of bounds. + enum pl_tex_address_mode address_mode; + + // If set, all out-of-bounds accesses will instead be treated as + // transparent, according to the given alpha mode. (Which should match the + // alpha mode of the texture) + // + // Note: `address_mode` has no effect when this is specified. + enum pl_alpha_mode alpha_mode; +}; + +#define PL_DISTORT_DEFAULTS \ + .transform.mat.m = {{ 1, 0 }, {0, 1}}, + +#define pl_distort_params(...) (&(struct pl_distort_params) {PL_DISTORT_DEFAULTS __VA_ARGS__ }) +PL_API extern const struct pl_distort_params pl_distort_default_params; + +// Distorts the input image using a given set of transformation parameters. +// `out_w` and `out_h` determine the size of the effective canvas inside which +// the distorted result may be rendered. Areas outside of this canvas will +// be implicitly cut off. +PL_API void pl_shader_distort(pl_shader sh, pl_tex tex, int out_w, int out_h, + const struct pl_distort_params *params); + +PL_API_END + +#endif // LIBPLACEBO_SHADERS_SAMPLING_H_ diff --git a/third_party/exo-dv5-native/include/libplacebo/swapchain.h b/third_party/exo-dv5-native/include/libplacebo/swapchain.h new file mode 100644 index 0000000000..b53aa5c1b1 --- /dev/null +++ b/third_party/exo-dv5-native/include/libplacebo/swapchain.h @@ -0,0 +1,171 @@ +/* + * This file is part of libplacebo. + * + * libplacebo is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libplacebo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with libplacebo. If not, see . + */ + +#ifndef LIBPLACEBO_SWAPCHAIN_H_ +#define LIBPLACEBO_SWAPCHAIN_H_ + +#include +#include +#include + +PL_API_BEGIN + +// This abstraction represents a low-level interface to visible surfaces +// exposed by a graphics API (and accompanying GPU instance), allowing users to +// directly present frames to the screen (or window, typically). This is a +// sister API to gpu.h and follows the same convention w.r.t undefined behavior. +// +// Thread-safety: Safe +typedef const struct pl_swapchain_t { + pl_log log; + pl_gpu gpu; +} *pl_swapchain; + +// Destroys this swapchain. May be used at any time, and may block until the +// completion of all outstanding rendering commands. The swapchain and any +// resources retrieved from it must not be used afterwards. +PL_API void pl_swapchain_destroy(pl_swapchain *sw); + +// Returns the approximate current swapchain latency in vsyncs, or 0 if +// unknown. A latency of 1 means that `submit_frame` followed by `swap_buffers` +// will block until the just-submitted frame has finished rendering. Typical +// values are 2 or 3, which enable better pipelining by allowing the GPU to be +// processing one or two frames at the same time as the user is preparing the +// next for submission. +PL_API int pl_swapchain_latency(pl_swapchain sw); + +// Update/query the swapchain size. This function performs both roles: it tries +// setting the swapchain size to the values requested by the user, and returns +// in the same variables what width/height the swapchain was actually set to - +// which may be (substantially) different from the values requested by the +// user. A value of 0 means "unknown/none" (in which case, libplacebo won't try +// updating the size - it will simply return the current state of the +// swapchain). It's also possible for libplacebo to return values of 0, such as +// in the case that the swapchain doesn't exist yet. +// +// Returns false on significant errors (e.g. dead surface). This function can +// effectively be used to probe if creating a swapchain works. +PL_API bool pl_swapchain_resize(pl_swapchain sw, int *width, int *height); + +// Backwards compatibility +#define pl_swapchain_colors pl_color_space + +// Inform the swapchain about the input color space. This API deliberately +// provides no feedback, because the swapchain can internally decide what to do +// with this information, including ignoring it entirely, or applying it +// asynchronously. Users must still base their rendering on the value of +// `pl_swapchain_frame.color_space`. +// +// Note: Calling this function a second time completely overrides any +// previously specified hint. So calling this on {0} or NULL resets the +// swapchain back to its initial/preferred colorspace. +// +// Note: If `csp->transfer` is a HDR transfer curve but HDR metadata is left +// unspecified, the HDR metadata defaults to `pl_hdr_metadata_hdr10`. +// Conversely, if the HDR metadata is non-empty but `csp->transfer` is left as +// PL_COLOR_TRC_UNKNOWN, then it instead defaults to PL_COLOR_TRC_PQ. +PL_API void pl_swapchain_colorspace_hint(pl_swapchain sw, const struct pl_color_space *csp); + +// The struct used to hold the results of `pl_swapchain_start_frame` +struct pl_swapchain_frame { + // A texture representing the framebuffer users should use for rendering. + // It's guaranteed that `fbo->params.renderable` and `fbo->params.blit_dst` + // will be true, but no other guarantees are made - not even that + // `fbo->params.format` is a real format. + pl_tex fbo; + + // If true, the user should assume that this framebuffer will be flipped + // as a result of presenting it on-screen. If false, nothing special needs + // to be done - but if true, users should flip the coordinate system of + // the `pl_pass` that is rendering to this framebuffer. + // + // Note: Normally, libplacebo follows the convention that (0,0) represents + // the top left of the image/screen. So when flipped is true, this means + // (0,0) on this framebuffer gets displayed as the bottom left of the image. + bool flipped; + + // Indicates the color representation this framebuffer will be interpreted + // as by the host system / compositor / display, including the bit depth + // and alpha handling (where available). + struct pl_color_repr color_repr; + struct pl_color_space color_space; +}; + +// Retrieve a new frame from the swapchain. Returns whether successful. It's +// worth noting that this function can fail sporadically for benign reasons, +// for example the window being invisible or inaccessible. This function may +// block until an image is available, which may be the case if the GPU is +// rendering frames significantly faster than the display can output them. It +// may also be non-blocking, so users shouldn't rely on this call alone in +// order to meter rendering speed. (Specifics depend on the underlying graphics +// API) +PL_API bool pl_swapchain_start_frame(pl_swapchain sw, struct pl_swapchain_frame *out_frame); + +// Submits the previously started frame. Non-blocking. This must be issued in +// lockstep with pl_swapchain_start_frame - there is no way to start multiple +// frames and submit them out-of-order. The frames submitted this way will +// generally be made visible in a first-in first-out fashion, although +// specifics depend on the mechanism used to create the pl_swapchain. (See the +// platform-specific APIs for more info). +// +// Returns whether successful. This should normally never fail, unless the +// GPU/surface has been lost or some other critical error has occurred. The +// "started" frame is consumed even in the event of failure. +// +// Note that `start_frame` and `submit_frame` form a lock pair, i.e. trying to +// call e.g. `pl_swapchain_resize` from another thread will block until +// `pl_swapchain_submit_frame` is finished. +PL_API bool pl_swapchain_submit_frame(pl_swapchain sw); + +// Performs a "buffer swap", or some generalization of the concept. In layman's +// terms, this blocks until the execution of the Nth previously submitted frame +// has been "made complete" in some sense. (The N derives from the swapchain's +// built-in latency. See `pl_swapchain_latency` for more information). +// +// Users should include this call in their rendering loops in order to make +// sure they aren't submitting rendering commands faster than the GPU can +// process them, which would potentially lead to a queue overrun or exhaust +// memory. +// +// An example loop might look like this: +// +// while (rendering) { +// struct pl_swapchain_frame frame; +// bool ok = pl_swapchain_start_frame(swapchain, &frame); +// if (!ok) { +// /* wait some time, or decide to stop rendering */ +// continue; +// } +// +// /* do some rendering with frame.fbo */ +// +// ok = pl_swapchain_submit_frame(swapchain); +// if (!ok) +// break; +// +// pl_swapchain_swap_buffers(swapchain); +// } +// +// The duration this function blocks for, if at all, may be very inconsistent +// and should not be used as an authoritative source of vsync timing +// information without sufficient smoothing/filtering (and if so, the time that +// `start_frame` blocked for should also be included). +PL_API void pl_swapchain_swap_buffers(pl_swapchain sw); + +PL_API_END + +#endif // LIBPLACEBO_SWAPCHAIN_H_ diff --git a/third_party/exo-dv5-native/include/libplacebo/tone_mapping.h b/third_party/exo-dv5-native/include/libplacebo/tone_mapping.h new file mode 100644 index 0000000000..b5e8aa42f9 --- /dev/null +++ b/third_party/exo-dv5-native/include/libplacebo/tone_mapping.h @@ -0,0 +1,268 @@ +/* + * This file is part of libplacebo. + * + * libplacebo is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libplacebo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with libplacebo. If not, see . + */ + +#ifndef LIBPLACEBO_TONE_MAPPING_H_ +#define LIBPLACEBO_TONE_MAPPING_H_ + +#include +#include + +#include +#include + +PL_API_BEGIN + +struct pl_tone_map_params; +struct pl_tone_map_function { + const char *name; // Identifier + const char *description; // Friendly / longer name + + // This controls the type of values input/output to/from `map` + enum pl_hdr_scaling scaling; + + // The tone-mapping function itself. Iterates over all values in `lut`, and + // adapts them as needed. + // + // Note that the `params` struct fed into this function is guaranteed to + // satisfy `params->input_scaling == params->output_scaling == scaling`, + // and also obeys `params->input_max >= params->output_max`. + void (*map)(float *lut, const struct pl_tone_map_params *params); + + // Inverse tone mapping function. Optional. If absent, this tone mapping + // curve only works in the forwards direction. + // + // For this function, `params->input_max <= params->output_max`. + void (*map_inverse)(float *lut, const struct pl_tone_map_params *params); + + // Private data. Unused by libplacebo, but may be accessed by `map`. + void *priv; + + // --- Deprecated fields + PL_DEPRECATED_IN(v6.311) const char *param_desc; + PL_DEPRECATED_IN(v6.311) float param_min; + PL_DEPRECATED_IN(v6.311) float param_def; + PL_DEPRECATED_IN(v6.311) float param_max; +}; + +struct pl_tone_map_constants { + // Configures the knee point, as a ratio between the source average and + // target average (in PQ space). An adaptation of 1.0 always adapts the + // source scene average brightness to the (scaled) target average, + // while a value of 0.0 never modifies scene brightness. [0,1] + // + // Affects all methods that use the ST2094 knee point determination + // (currently ST2094-40, ST2094-10 and spline) + float knee_adaptation; + + // Configures the knee point minimum and maximum, respectively, as + // a percentage of the PQ luminance range. Provides a hard limit on the + // knee point chosen by `knee_adaptation`. + float knee_minimum; // (0, 0.5) + float knee_maximum; // (0.5, 1.0) + + // Default knee point to use in the absence of source scene average + // metadata. Normally, this is ignored in favor of picking the knee + // point as the (relative) source scene average brightness level. + float knee_default; // [knee_minimum, knee_maximum] + + // Knee point offset (for BT.2390 only). Note that a value of 0.5 is + // the spec-defined default behavior, which differs from the libplacebo + // default of 1.0. [0.5, 2] + float knee_offset; + + // For the single-pivot polynomial (spline) function, this controls the + // coefficients used to tune the slope of the curve. This tuning is designed + // to make the slope closer to 1.0 when the difference in peaks is low, + // and closer to linear when the difference between peaks is high. + float slope_tuning; // [0,10] + float slope_offset; // [0,1] + + // Contrast setting for the spline function. Higher values make the curve + // steeper (closer to `clip`), preserving midtones at the cost of losing + // shadow/highlight details, while lower values make the curve shallowed + // (closer to `linear`), preserving highlights at the cost of losing midtone + // contrast. Values above 1.0 are possible, resulting in an output with more + // contrast than the input. + float spline_contrast; // [0,1.5] + + // For the reinhard function, this specifies the local contrast coefficient + // at the display peak. Essentially, a value of 0.5 implies that the + // reference white will be about half as bright as when clipping. (0,1) + float reinhard_contrast; + + // For legacy functions (mobius, gamma) which operate on linear light, this + // directly sets the corresponding knee point. (0,1) + float linear_knee; + + // For linear methods (linear, linearlight), this controls the linear + // exposure/gain applied to the image. (0,10] + float exposure; +}; + +#define PL_TONE_MAP_CONSTANTS \ + .knee_adaptation = 0.4f, \ + .knee_minimum = 0.1f, \ + .knee_maximum = 0.8f, \ + .knee_default = 0.4f, \ + .knee_offset = 1.0f, \ + .slope_tuning = 1.5f, \ + .slope_offset = 0.2f, \ + .spline_contrast = 0.5f, \ + .reinhard_contrast = 0.5f, \ + .linear_knee = 0.3f, \ + .exposure = 1.0f, + +struct pl_tone_map_params { + // If `function` is NULL, defaults to `pl_tone_map_clip`. + const struct pl_tone_map_function *function; + + // Common constants, should be initialized to PL_TONE_MAP_CONSTANTS if + // not intending to override them further. + struct pl_tone_map_constants constants; + + // The desired input/output scaling of the tone map. If this differs from + // `function->scaling`, any required conversion will be performed. + // + // Note that to maximize LUT efficiency, it's *highly* recommended to use + // either PL_HDR_PQ or PL_HDR_SQRT as the input scaling, except when + // using `pl_tone_map_sample`. + enum pl_hdr_scaling input_scaling; + enum pl_hdr_scaling output_scaling; + + // The size of the resulting LUT. (For `pl_tone_map_generate` only) + size_t lut_size; + + // The characteristics of the input, in `input_scaling` units. + float input_min; + float input_max; + float input_avg; // or 0 if unknown + + // The desired characteristics of the output, in `output_scaling` units. + float output_min; + float output_max; + + // The input HDR metadata. Only used by a select few tone-mapping + // functions, currently only SMPTE ST2094. (Optional) + struct pl_hdr_metadata hdr; + + // --- Deprecated fields + PL_DEPRECATED_IN(v6.311) float param; // see `constants` +}; + +#define pl_tone_map_params(...) (&(struct pl_tone_map_params) { __VA_ARGS__ }); + +// Note: Only does pointer equality testing on `function` +PL_API bool pl_tone_map_params_equal(const struct pl_tone_map_params *a, + const struct pl_tone_map_params *b); + +// Clamps/defaults the parameters, including input/output maximum. +PL_API void pl_tone_map_params_infer(struct pl_tone_map_params *params); + +// Returns true if the given tone mapping configuration effectively represents +// a no-op configuration. Tone mapping can be skipped in this case (although +// strictly speaking, the LUT would still clip illegal input values) +PL_API bool pl_tone_map_params_noop(const struct pl_tone_map_params *params); + +// Generate a tone-mapping LUT for a given configuration. This will always +// span the entire input range, as given by `input_min` and `input_max`. +PL_API void pl_tone_map_generate(float *out, const struct pl_tone_map_params *params); + +// Samples a tone mapping function at a single position. Note that this is less +// efficient than `pl_tone_map_generate` for generating multiple values. +// +// Ignores `params->lut_size`. +PL_API float pl_tone_map_sample(float x, const struct pl_tone_map_params *params); + +// Performs no tone-mapping, just clips out-of-range colors. Retains perfect +// color accuracy for in-range colors but completely destroys out-of-range +// information. Does not perform any black point adaptation. +PL_API extern const struct pl_tone_map_function pl_tone_map_clip; + +// EETF from SMPTE ST 2094-40 Annex B, which uses the provided OOTF based on +// Bezier curves to perform tone-mapping. The OOTF used is adjusted based on +// the ratio between the targeted and actual display peak luminances. In the +// absence of HDR10+ metadata, falls back to a simple constant bezier curve. +PL_API extern const struct pl_tone_map_function pl_tone_map_st2094_40; + +// EETF from SMPTE ST 2094-10 Annex B.2, which takes into account the input +// signal average luminance in addition to the maximum/minimum. +// +// Note: This does *not* currently include the subjective gain/offset/gamma +// controls defined in Annex B.3. (Open an issue with a valid sample file if +// you want such parameters to be respected.) +PL_API extern const struct pl_tone_map_function pl_tone_map_st2094_10; + +// EETF from the ITU-R Report BT.2390, a hermite spline roll-off with linear +// segment. +PL_API extern const struct pl_tone_map_function pl_tone_map_bt2390; + +// EETF from ITU-R Report BT.2446, method A. Can be used for both forward +// and inverse tone mapping. +PL_API extern const struct pl_tone_map_function pl_tone_map_bt2446a; + +// Simple spline consisting of two polynomials, joined by a single pivot point, +// which is tuned based on the source scene average brightness (taking into +// account dynamic metadata if available). This function can be used +// for both forward and inverse tone mapping. +PL_API extern const struct pl_tone_map_function pl_tone_map_spline; + +// Very simple non-linear curve. Named after Erik Reinhard. +PL_API extern const struct pl_tone_map_function pl_tone_map_reinhard; + +// Generalization of the reinhard tone mapping algorithm to support an +// additional linear slope near black. The name is derived from its function +// shape (ax+b)/(cx+d), which is known as a Möbius transformation. +PL_API extern const struct pl_tone_map_function pl_tone_map_mobius; + +// Piece-wise, filmic tone-mapping algorithm developed by John Hable for use in +// Uncharted 2, inspired by a similar tone-mapping algorithm used by Kodak. +// Popularized by its use in video games with HDR rendering. Preserves both +// dark and bright details very well, but comes with the drawback of changing +// the average brightness quite significantly. This is sort of similar to +// pl_tone_map_reinhard with `reinhard_contrast=0.24`. +PL_API extern const struct pl_tone_map_function pl_tone_map_hable; + +// Fits a gamma (power) function to transfer between the source and target +// color spaces, effectively resulting in a perceptual hard-knee joining two +// roughly linear sections. This preserves details at all scales, but can result +// in an image with a muted or dull appearance. +PL_API extern const struct pl_tone_map_function pl_tone_map_gamma; + +// Linearly stretches the input range to the output range, in PQ space. This +// will preserve all details accurately, but results in a significantly +// different average brightness. Can be used for inverse tone-mapping in +// addition to regular tone-mapping. +PL_API extern const struct pl_tone_map_function pl_tone_map_linear; + +// Like `pl_tone_map_linear`, but in linear light (instead of PQ). Works well +// for small range adjustments but may cause severe darkening when +// downconverting from e.g. 10k nits to SDR. +PL_API extern const struct pl_tone_map_function pl_tone_map_linear_light; + +// A list of built-in tone mapping functions, terminated by NULL +PL_API extern const struct pl_tone_map_function * const pl_tone_map_functions[]; +PL_API extern const int pl_num_tone_map_functions; // excluding trailing NULL + +// Find the tone mapping function with the given name, or NULL on failure. +PL_API const struct pl_tone_map_function *pl_find_tone_map_function(const char *name); + +// Deprecated alias, do not use +#define pl_tone_map_auto pl_tone_map_spline + +PL_API_END + +#endif // LIBPLACEBO_TONE_MAPPING_H_ diff --git a/third_party/exo-dv5-native/include/libplacebo/vulkan.h b/third_party/exo-dv5-native/include/libplacebo/vulkan.h new file mode 100644 index 0000000000..13a83dc1f9 --- /dev/null +++ b/third_party/exo-dv5-native/include/libplacebo/vulkan.h @@ -0,0 +1,688 @@ +/* + * This file is part of libplacebo. + * + * libplacebo is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * libplacebo is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with libplacebo. If not, see . + */ + +#ifndef LIBPLACEBO_VULKAN_H_ +#define LIBPLACEBO_VULKAN_H_ + +#include +#include +#include + +PL_API_BEGIN + +#define PL_VK_MIN_VERSION VK_API_VERSION_1_2 + +// Structure representing a VkInstance. Using this is not required. +typedef const struct pl_vk_inst_t { + VkInstance instance; + + // The Vulkan API version supported by this VkInstance. + uint32_t api_version; + + // The associated vkGetInstanceProcAddr pointer. + PFN_vkGetInstanceProcAddr get_proc_addr; + + // The instance extensions that were successfully enabled, including + // extensions enabled by libplacebo internally. May contain duplicates. + const char * const *extensions; + int num_extensions; + + // The instance layers that were successfully enabled, including + // layers enabled by libplacebo internally. May contain duplicates. + const char * const *layers; + int num_layers; +} *pl_vk_inst; + +struct pl_vk_inst_params { + // If set, enable the debugging and validation layers. These should + // generally be lightweight and relatively harmless to enable. + bool debug; + + // If set, also enable GPU-assisted verification and best practices + // layers. (Note: May cause substantial slowdown and/or result in lots of + // false positive spam) + bool debug_extra; + + // If nonzero, restricts the Vulkan API version to be at most this. This + // is only really useful for explicitly testing backwards compatibility. + uint32_t max_api_version; + + // Pointer to a user-provided `vkGetInstanceProcAddr`. If this is NULL, + // libplacebo will use the directly linked version (if available). + PFN_vkGetInstanceProcAddr get_proc_addr; + + // Enables extra instance extensions. Instance creation will fail if these + // extensions are not all supported. The user may use this to enable e.g. + // windowing system integration. + const char * const *extensions; + int num_extensions; + + // Enables extra optional instance extensions. These are opportunistically + // enabled if supported by the device, but otherwise skipped. + const char * const *opt_extensions; + int num_opt_extensions; + + // Enables extra layers. Instance creation will fail if these layers are + // not all supported. + // + // NOTE: Layers needed for required/optional extensions are automatically + // enabled. The user does not specifically need to enable layers related + // to extension support. + const char * const *layers; + int num_layers; + + // Enables extra optional layers. These are opportunistically enabled if + // supported by the platform, but otherwise skipped. + const char * const *opt_layers; + int num_opt_layers; +}; + +#define pl_vk_inst_params(...) (&(struct pl_vk_inst_params) { __VA_ARGS__ }) +PL_API extern const struct pl_vk_inst_params pl_vk_inst_default_params; + +// Helper function to simplify instance creation. The user could also bypass +// these helpers and do it manually, but this function is provided as a +// convenience. It also sets up a debug callback which forwards all vulkan +// messages to the `pl_log` callback. +PL_API pl_vk_inst pl_vk_inst_create(pl_log log, const struct pl_vk_inst_params *params); +PL_API void pl_vk_inst_destroy(pl_vk_inst *inst); + +struct pl_vulkan_queue { + uint32_t index; // Queue family index + uint32_t count; // Queue family count + VkDeviceQueueCreateFlags flags; // Queue family flags +}; + +// Structure representing the actual vulkan device and associated GPU instance +typedef const struct pl_vulkan_t *pl_vulkan; +struct pl_vulkan_t { + pl_gpu gpu; + + // The vulkan objects in use. The user may use this for their own purposes, + // but please note that the lifetime is tied to the lifetime of the + // pl_vulkan object, and must not be destroyed by the user. Note that the + // created vulkan device may have any number of queues and queue family + // assignments; so using it for queue submission commands is ill-advised. + VkInstance instance; + VkPhysicalDevice phys_device; + VkDevice device; + + // The associated vkGetInstanceProcAddr pointer. + PFN_vkGetInstanceProcAddr get_proc_addr; + + // The Vulkan API version supported by this VkPhysicalDevice. + uint32_t api_version; + + // The device extensions that were successfully enabled, including + // extensions enabled by libplacebo internally. May contain duplicates. + const char * const *extensions; + int num_extensions; + + // The device features that were enabled at device creation time. + // + // Note: Whenever a feature flag is ambiguious between several alternative + // locations, for completeness' sake, we include both. + const VkPhysicalDeviceFeatures2 *features; + + // The explicit queue families we are using to provide a given capability. + struct pl_vulkan_queue queue_graphics; // provides VK_QUEUE_GRAPHICS_BIT + struct pl_vulkan_queue queue_compute; // provides VK_QUEUE_COMPUTE_BIT + struct pl_vulkan_queue queue_transfer; // provides VK_QUEUE_TRANSFER_BIT + + // Functions for locking a queue. These must be used to lock VkQueues for + // submission or other related operations when sharing the VkDevice between + // multiple threads, Using this on queue families or indices not contained + // in `queues` is undefined behavior. + void (*lock_queue)(pl_vulkan vk, uint32_t qf, uint32_t qidx); + void (*unlock_queue)(pl_vulkan vk, uint32_t qf, uint32_t qidx); + + // --- Deprecated fields + + // These are the same active queue families and their queue counts in list + // form. This list does not contain duplicates, nor any extra queues + // enabled at device creation time. Deprecated in favor of querying + // `vkGetPhysicalDeviceQueueFamilyProperties` directly. + PL_DEPRECATED_IN(v6.271) const struct pl_vulkan_queue *queues; + PL_DEPRECATED_IN(v6.271) int num_queues; +}; + +struct pl_vulkan_params { + // The vulkan instance. Optional, if NULL then libplacebo will internally + // create a VkInstance with the settings from `instance_params`. + // + // Note: The VkInstance provided by the user *MUST* be created with a + // VkApplicationInfo.apiVersion of PL_VK_MIN_VERSION or higher. + VkInstance instance; + + // Pointer to `vkGetInstanceProcAddr`. If this is NULL, libplacebo will + // use the directly linked version (if available). + // + // Note: This overwrites the same value from `instance_params`. + PFN_vkGetInstanceProcAddr get_proc_addr; + + // Configures the settings used for creating an internal vulkan instance. + // May be NULL. Ignored if `instance` is set. + const struct pl_vk_inst_params *instance_params; + + // When choosing the device, rule out all devices that don't support + // presenting to this surface. When creating a device, enable all extensions + // needed to ensure we can present to this surface. Optional. Only legal + // when specifying an existing VkInstance to use. + VkSurfaceKHR surface; + + // --- Physical device selection options + + // The vulkan physical device. May be set by the caller to indicate the + // physical device to use. Otherwise, libplacebo will pick the "best" + // available GPU, based on the advertised device type. (i.e., it will + // prefer discrete GPUs over integrated GPUs). Only legal when specifying + // an existing VkInstance to use. + VkPhysicalDevice device; + + // When choosing the device, only choose a device with this exact name. + // This overrides `allow_software`. No effect if `device` is set. Note: A + // list of devices and their names are logged at level PL_LOG_INFO. + const char *device_name; + + // When choosing the device, only choose a device with this exact UUID. + // This overrides `allow_software` and `device_name`. No effect if `device` + // is set. + uint8_t device_uuid[16]; + + // When choosing the device, controls whether or not to also allow software + // GPUs. No effect if `device` or `device_name` are set. + bool allow_software; + + // --- Logical device creation options + + // Controls whether or not to allow asynchronous transfers, using transfer + // queue families, if supported by the device. This can be significantly + // faster and more power efficient, and also allows streaming uploads in + // parallel with rendering commands. Enabled by default. + bool async_transfer; + + // Controls whether or not to allow asynchronous compute, using dedicated + // compute queue families, if supported by the device. On some devices, + // these can allow the GPU to schedule compute shaders in parallel with + // fragment shaders. Enabled by default. + bool async_compute; + + // Limits the number of queues to use. If left as 0, libplacebo will use as + // many queues as the device supports. Multiple queues can result in + // improved efficiency when submitting multiple commands that can entirely + // or partially execute in parallel. Defaults to 1, since using more queues + // can actually decrease performance. + // + // Note: libplacebo will always *create* logical devices with all available + // queues for a given QF enabled, regardless of this setting. + int queue_count; + + // Disables the use of compute shaders. Some devices/drivers perform better + // without them. This may also help prevent image corruption in cases where + // the driver is misbehaving. Some features may be disabled if this is set. + bool no_compute; + + // Bitmask of extra queue families to enable. If set, then *all* queue + // families matching *any* of these flags will be enabled at device + // creation time. Setting this to VK_QUEUE_FLAG_BITS_MAX_ENUM effectively + // enables all queue families supported by the device. + VkQueueFlags extra_queues; + + // Enables extra device extensions. Device creation will fail if these + // extensions are not all supported. The user may use this to enable e.g. + // interop extensions. + const char * const *extensions; + int num_extensions; + + // Enables extra optional device extensions. These are opportunistically + // enabled if supported by the device, but otherwise skipped. + const char * const *opt_extensions; + int num_opt_extensions; + + // Optional extra features to enable at device creation time. These are + // opportunistically enabled if supported by the physical device, but + // otherwise kept disabled. + const VkPhysicalDeviceFeatures2 *features; + + // --- Misc/debugging options + + // Restrict specific features to e.g. work around driver bugs, or simply + // for testing purposes + int max_glsl_version; // limit the maximum GLSL version + uint32_t max_api_version; // limit the maximum vulkan API version +}; + +// Default/recommended parameters. Should generally be safe and efficient. +#define PL_VULKAN_DEFAULTS \ + .async_transfer = true, \ + .async_compute = true, \ + /* enabling multiple queues often decreases perf */ \ + .queue_count = 1, + +#define pl_vulkan_params(...) (&(struct pl_vulkan_params) { PL_VULKAN_DEFAULTS __VA_ARGS__ }) +PL_API extern const struct pl_vulkan_params pl_vulkan_default_params; + +// Creates a new vulkan device based on the given parameters and initializes +// a new GPU. If `params` is left as NULL, it defaults to +// &pl_vulkan_default_params. +// +// Thread-safety: Safe +PL_API pl_vulkan pl_vulkan_create(pl_log log, const struct pl_vulkan_params *params); + +// Destroys the vulkan device and all associated objects, except for the +// VkInstance provided by the user. +// +// Note that all resources allocated from this vulkan object (e.g. via the +// `vk->ra` or using `pl_vulkan_create_swapchain`) *must* be explicitly +// destroyed by the user before calling this. +// +// Also note that this function will block until all in-flight GPU commands are +// finished processing. You can avoid this by manually calling `pl_gpu_finish` +// before `pl_vulkan_destroy`. +PL_API void pl_vulkan_destroy(pl_vulkan *vk); + +// For a `pl_gpu` backed by `pl_vulkan`, this function can be used to retrieve +// the underlying `pl_vulkan`. Returns NULL for any other type of `gpu`. +PL_API pl_vulkan pl_vulkan_get(pl_gpu gpu); + +struct pl_vulkan_device_params { + // The instance to use. Required! + // + // Note: The VkInstance provided by the user *must* be created with a + // VkApplicationInfo.apiVersion of PL_VK_MIN_VERSION or higher. + VkInstance instance; + + // Mirrored from `pl_vulkan_params`. All of these fields are optional. + PFN_vkGetInstanceProcAddr get_proc_addr; + VkSurfaceKHR surface; + const char *device_name; + uint8_t device_uuid[16]; + bool allow_software; +}; + +#define pl_vulkan_device_params(...) (&(struct pl_vulkan_device_params) { __VA_ARGS__ }) + +// Helper function to choose the best VkPhysicalDevice, given a VkInstance. +// This uses the same logic as `pl_vulkan_create` uses internally. If no +// matching device was found, this returns VK_NULL_HANDLE. +PL_API VkPhysicalDevice pl_vulkan_choose_device(pl_log log, + const struct pl_vulkan_device_params *params); + +struct pl_vulkan_swapchain_params { + // The surface to use for rendering. Required, the user is in charge of + // creating this. Must belong to the same VkInstance as `vk->instance`. + VkSurfaceKHR surface; + + // The preferred presentation mode. See the vulkan documentation for more + // information about these. If the device/surface combination does not + // support this mode, libplacebo will fall back to VK_PRESENT_MODE_FIFO_KHR. + // + // Warning: Leaving this zero-initialized is the same as having specified + // VK_PRESENT_MODE_IMMEDIATE_KHR, which is probably not what the user + // wants! + VkPresentModeKHR present_mode; + + // Allow up to N in-flight frames. This essentially controls how many + // rendering commands may be queued up at the same time. See the + // documentation for `pl_swapchain_get_latency` for more information. For + // vulkan specifically, we are only able to wait until the GPU has finished + // rendering a frame - we are unable to wait until the display has actually + // finished displaying it. So this only provides a rough guideline. + // Optional, defaults to 3. + int swapchain_depth; + + // This suppresses automatic recreation of the swapchain when any call + // returns VK_SUBOPTIMAL_KHR. Normally, libplacebo will recreate the + // swapchain internally on the next `pl_swapchain_start_frame`. If enabled, + // clients are assumed to take care of swapchain recreations themselves, by + // calling `pl_swapchain_resize` as appropriate. libplacebo will tolerate + // the "suboptimal" status indefinitely. + bool allow_suboptimal; + + // Do not request VK_IMAGE_USAGE_STORAGE_BIT for swapchain images. This + // may allow the presentation engine to choose a more compositable image + // layout at the cost of preventing direct compute shader output. + bool disable_storage; + + // Disable high-bit (10 or more) SDR formats. May help work around buggy + // drivers which don't dither properly when outputting high bit depth + // SDR backbuffers to 8-bit screens. + bool disable_10bit_sdr; + + // Minimum number of alpha bits requested in the swapchain format. In + // practice, this can be used to prefer formats with higher alpha bit depth + // (e.g. rgba8/rgba16 over rgb10a2), potentially trading 2 bits per color + // channel for increased alpha precision. This is a hint, if no matching + // format is found, lower bit depths will be accepted. + uint8_t alpha_bits; + + // Minimum number of color bits requested in the swapchain format. This can + // be used to prefer formats with higher color bit depth. This is a hint, + // if no matching format is found, lower bit depths will be accepted. + uint8_t color_bits; +}; + +#define pl_vulkan_swapchain_params(...) (&(struct pl_vulkan_swapchain_params) { __VA_ARGS__ }) + +// Creates a new vulkan swapchain based on an existing VkSurfaceKHR. Using this +// function requires that the vulkan device was created with the +// VK_KHR_swapchain extension. The easiest way of accomplishing this is to set +// the `pl_vulkan_params.surface` explicitly at creation time. +PL_API pl_swapchain pl_vulkan_create_swapchain(pl_vulkan vk, + const struct pl_vulkan_swapchain_params *params); + +// This will return true if the vulkan swapchain is internally detected +// as being suboptimal (VK_SUBOPTIMAL_KHR). This might be of use to clients +// who have `params->allow_suboptimal` enabled. +PL_API bool pl_vulkan_swapchain_suboptimal(pl_swapchain sw); + +// Vulkan interop API, for sharing a single VkDevice (and associated vulkan +// resources) directly with the API user. The use of this API is a bit sketchy +// and requires careful communication of Vulkan API state. + +struct pl_vulkan_import_params { + // The vulkan instance. Required. + // + // Note: The VkInstance provided by the user *must* be created with a + // VkApplicationInfo.apiVersion of PL_VK_MIN_VERSION or higher. + VkInstance instance; + + // Pointer to `vkGetInstanceProcAddr`. If this is NULL, libplacebo will + // use the directly linked version (if available). + PFN_vkGetInstanceProcAddr get_proc_addr; + + // The physical device selected by the user. Required. + VkPhysicalDevice phys_device; + + // The logical device created by the user. Required. + VkDevice device; + + // --- Logical device parameters + + // List of all device-level extensions that were enabled. (Instance-level + // extensions need not be re-specified here, since it's guaranteed that any + // instance-level extensions that device-level extensions depend on were + // enabled at the instance level) + const char * const *extensions; + int num_extensions; + + // Enabled queue families. At least `queue_graphics` is required. + // + // It's okay for multiple queue families to be specified with the same + // index, e.g. in the event that a dedicated compute queue also happens to + // be the dedicated transfer queue. + // + // It's also okay to leave the queue struct as {0} in the event that no + // dedicated queue exists for a given operation type. libplacebo will + // automatically fall back to using e.g. the graphics queue instead. + struct pl_vulkan_queue queue_graphics; // must support VK_QUEUE_GRAPHICS_BIT + struct pl_vulkan_queue queue_compute; // must support VK_QUEUE_COMPUTE_BIT + struct pl_vulkan_queue queue_transfer; // must support VK_QUEUE_TRANSFER_BIT + + // Enabled VkPhysicalDeviceFeatures. The device *must* be created with + // all of the features in `pl_vulkan_required_features` enabled. + const VkPhysicalDeviceFeatures2 *features; + + // Functions for locking a queue. If set, these will be used instead of + // libplacebo's internal functions for `pl_vulkan.(un)lock_queue`. + // If not set, libplacebo will use its own internal locking, unless the + // device was created with VK_KHR_internally_synchronized_queues enabled + // (as indicated by `features`), in which case locking is skipped. + void (*lock_queue)(void *ctx, uint32_t qf, uint32_t qidx); + void (*unlock_queue)(void *ctx, uint32_t qf, uint32_t qidx); + void *queue_ctx; + + // --- Misc/debugging options + + // Restrict specific features to e.g. work around driver bugs, or simply + // for testing purposes. See `pl_vulkan_params` for a description of these. + bool no_compute; + int max_glsl_version; + uint32_t max_api_version; +}; + +#define pl_vulkan_import_params(...) (&(struct pl_vulkan_import_params) { __VA_ARGS__ }) + +// For purely informative reasons, this contains a list of extensions and +// device features that libplacebo *can* make use of. These are all strictly +// optional, but provide a hint to the API user as to what might be worth +// enabling at device creation time. +// +// Note: This also includes physical device features provided by extensions. +// They are all provided using extension-specific features structs, rather +// than the more general purpose VkPhysicalDeviceVulkan11Features etc. +PL_API extern const char * const pl_vulkan_recommended_extensions[]; +PL_API extern const int pl_vulkan_num_recommended_extensions; +PL_API extern const VkPhysicalDeviceFeatures2 pl_vulkan_recommended_features; + +// A list of device features that are required by libplacebo. These +// *must* be provided by imported Vulkan devices. +// +// Note: `pl_vulkan_recommended_features` does not include this list. +PL_API extern const VkPhysicalDeviceFeatures2 pl_vulkan_required_features; + +// Import an existing VkDevice instead of creating a new one, and wrap it into +// a `pl_vulkan` abstraction. It's safe to `pl_vulkan_destroy` this, which will +// destroy application state related to libplacebo but leave the underlying +// VkDevice intact. +PL_API pl_vulkan pl_vulkan_import(pl_log log, const struct pl_vulkan_import_params *params); + +struct pl_vulkan_ycbcr_params; + +struct pl_vulkan_wrap_params { + // The image itself. It *must* be usable concurrently by all of the queue + // family indices listed in `pl_vulkan->queues`. Note that this requires + // the use of VK_SHARING_MODE_CONCURRENT if `pl_vulkan->num_queues` is + // greater than 1. If this is difficult to achieve for the user, then + // `async_transfer` / `async_compute` should be turned off, which + // guarantees the use of only one queue family. + VkImage image; + + // Which aspect of `image` to wrap. Only useful for wrapping individual + // sub-planes of planar images. If left as 0, it defaults to the entire + // image (i.e. the union of VK_IMAGE_ASPECT_PLANE_N_BIT for planar formats, + // and VK_IMAGE_ASPECT_COLOR_BIT otherwise). YCbCr conversion requires 0 + // or VK_IMAGE_ASPECT_COLOR_BIT. + VkImageAspectFlags aspect; + + // The image's dimensions (unused dimensions must be 0) + int width; + int height; + int depth; + + // The image's format. libplacebo will try to map this to an equivalent + // pl_fmt. If no compatible pl_fmt is found, wrapping will fail. When + // `ycbcr` is set, this may be a concrete multi-planar format or + // VK_FORMAT_UNDEFINED for an Android external format. + VkFormat format; + + // The usage flags the image was created with. libplacebo will set the + // pl_tex capabilities to include whatever it can, as determined by the set + // of enabled usage flags. For YCbCr images this must exactly match the + // image creation usage so libplacebo can query descriptor requirements. + VkImageUsageFlags usage; + + // See `pl_tex_params` + void *user_data; + pl_debug_tag debug_tag; + + // Optional YCbCr sampling configuration. When set, the wrapped image is + // exposed as a normalized four-component texture backed by an immutable + // VkSamplerYcbcrConversion sampler. The selected conversion model + // determines whether shaders receive converted RGB or reconstructed source + // components. The pointed-to data is consumed during this call and does + // not need to remain alive afterwards. + const struct pl_vulkan_ycbcr_params *ycbcr; +}; + +struct pl_vulkan_ycbcr_params { + // Android external-format identifier. Must be non-zero exactly when the + // wrapped image format is VK_FORMAT_UNDEFINED. + uint64_t external_format; + VkComponentMapping components; + VkSamplerYcbcrModelConversion model; + VkSamplerYcbcrRange range; + VkChromaLocation x_chroma_offset; + VkChromaLocation y_chroma_offset; + VkFilter chroma_filter; + bool separate_reconstruction_filter; + bool force_explicit_reconstruction; + + // Effective component precision of the samples returned to shaders. + int sample_depth; +}; + +#define pl_vulkan_wrap_params(...) (&(struct pl_vulkan_wrap_params) { \ + .debug_tag = PL_DEBUG_TAG, \ + __VA_ARGS__ \ + }) + +// Wraps an external VkImage into a pl_tex abstraction. By default, the image +// is considered "held" by the user and must be released before calling any +// pl_tex_* API calls on it (see `pl_vulkan_release_ex`). +// +// This wrapper can be destroyed by simply calling `pl_tex_destroy` on it, +// which will not destroy the underlying VkImage. If a pl_tex wrapper is +// destroyed while an image is not currently being held by the user, that +// image is left in an undefined state. +// +// Wrapping the same VkImage multiple times is undefined behavior, as is trying +// to wrap an image belonging to a different VkDevice than the one in use by +// `gpu`. +// +// This function may fail, in which case it returns NULL. +PL_API pl_tex pl_vulkan_wrap(pl_gpu gpu, const struct pl_vulkan_wrap_params *params); + +// Analogous to `pl_vulkan_wrap`, this function takes any `pl_tex` (including +// ones created by `pl_tex_create`) and unwraps it to expose the underlying +// VkImage to the user. Unlike `pl_vulkan_wrap`, this `pl_tex` is *not* +// considered held after calling this function - the user must explicitly +// `pl_vulkan_hold_ex` before accessing the VkImage. +// +// `out_format` and `out_flags` will be updated to hold the VkImage's +// format and usage flags. (Optional) +PL_API VkImage pl_vulkan_unwrap(pl_gpu gpu, pl_tex tex, + VkFormat *out_format, VkImageUsageFlags *out_flags); + +// Represents a vulkan semaphore/value pair (for compatibility with timeline +// semaphores). When using normal, binary semaphores, `value` may be ignored. +typedef struct pl_vulkan_sem { + VkSemaphore sem; + uint64_t value; +} pl_vulkan_sem; + +struct pl_vulkan_hold_params { + // The Vulkan image to hold. It will be marked as held. Attempting to + // perform any pl_tex_* operation (except pl_tex_destroy) on a held image + // is undefined behavior. + pl_tex tex; + + // The layout to transition the image to when holding. Alternatively, a + // pointer to receive the current image layout. If `out_layout` is + // provided, `layout` is ignored. + VkImageLayout layout; + VkImageLayout *out_layout; + + // The queue family index to transition the image to. This can be used with + // VK_QUEUE_FAMILY_EXTERNAL to transition the image to an external API. As + // a special case, if set to VK_QUEUE_FAMILY_IGNORED, libplacebo will not + // transition the image, even if this image was not set up for concurrent + // usage. Ignored for concurrent images. + uint32_t qf; + + // The semaphore to fire when the image is available for use. (Required) + pl_vulkan_sem semaphore; +}; + +#define pl_vulkan_hold_params(...) (&(struct pl_vulkan_hold_params) { __VA_ARGS__ }) + +// "Hold" a shared image, transferring control over the image to the user. +// Returns whether successful. +PL_API bool pl_vulkan_hold_ex(pl_gpu gpu, const struct pl_vulkan_hold_params *params); + +struct pl_vulkan_release_params { + // The image to be released. It must be marked as "held". Performing any + // operation on the VkImage underlying this `pl_tex` while it is not being + // held by the user is undefined behavior. + pl_tex tex; + + // The current layout of the image at the point in time when `semaphore` + // fires, or if no semaphore is specified, at the time of call. + VkImageLayout layout; + + // The queue family index to transition the image to. This can be used with + // VK_QUEUE_FAMILY_EXTERNAL to transition the image rom an external API. As + // a special case, if set to VK_QUEUE_FAMILY_IGNORED, libplacebo will not + // transition the image, even if this image was not set up for concurrent + // usage. Ignored for concurrent images. + uint32_t qf; + + // The semaphore to wait on before libplacebo will actually use or modify + // the image. (Optional) + // + // Note: the lifetime of `semaphore` is indeterminate, and destroying it + // while the texture is still depending on that semaphore is undefined + // behavior. + // + // Technically, the only way to be sure that it's safe to free is to use + // `pl_gpu_finish()` or similar (e.g. `pl_vulkan_destroy` or + // `vkDeviceWaitIdle`) after another operation involving `tex` has been + // emitted (or the texture has been destroyed). + // + // + // Warning: If `tex` is a planar image (`pl_fmt.num_planes > 0`), and + // `semaphore` is specified, it *must* be a timeline semaphore! Failure to + // respect this will result in undefined behavior. This warning does not + // apply to individual planes (as exposed by `pl_tex.planes`). + pl_vulkan_sem semaphore; +}; + +#define pl_vulkan_release_params(...) (&(struct pl_vulkan_release_params) { __VA_ARGS__ }) + +// "Release" a shared image, transferring control to libplacebo. +PL_API void pl_vulkan_release_ex(pl_gpu gpu, const struct pl_vulkan_release_params *params); + +struct pl_vulkan_sem_params { + // The type of semaphore to create. + VkSemaphoreType type; + + // For VK_SEMAPHORE_TYPE_TIMELINE, sets the initial timeline value. + uint64_t initial_value; + + // If set, exports this VkSemaphore to the handle given in `out_handle`. + // The user takes over ownership, and should manually close it before + // destroying this VkSemaphore (via `pl_vulkan_sem_destroy`). + enum pl_handle_type export_handle; + union pl_handle *out_handle; + + // Optional debug tag to identify this semaphore. + pl_debug_tag debug_tag; +}; + +#define pl_vulkan_sem_params(...) (&(struct pl_vulkan_sem_params) { \ + .debug_tag = PL_DEBUG_TAG, \ + __VA_ARGS__ \ + }) + +// Helper functions to create and destroy vulkan semaphores. Returns +// VK_NULL_HANDLE on failure. +PL_API VkSemaphore pl_vulkan_sem_create(pl_gpu gpu, const struct pl_vulkan_sem_params *params); +PL_API void pl_vulkan_sem_destroy(pl_gpu gpu, VkSemaphore *semaphore); + +PL_API_END + +#endif // LIBPLACEBO_VULKAN_H_ diff --git a/third_party/exo-dv5-native/licenses/LICENSE.libdovi b/third_party/exo-dv5-native/licenses/LICENSE.libdovi new file mode 100644 index 0000000000..1bef6207b9 --- /dev/null +++ b/third_party/exo-dv5-native/licenses/LICENSE.libdovi @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 quietvoid + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/third_party/exo-dv5-native/licenses/LICENSE.libplacebo b/third_party/exo-dv5-native/licenses/LICENSE.libplacebo new file mode 100644 index 0000000000..20fb9c7da2 --- /dev/null +++ b/third_party/exo-dv5-native/licenses/LICENSE.libplacebo @@ -0,0 +1,458 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS diff --git a/third_party/exo-dv5-native/licenses/NOTICE.shaderc-toolchain b/third_party/exo-dv5-native/licenses/NOTICE.shaderc-toolchain new file mode 100644 index 0000000000..f0b69486cc --- /dev/null +++ b/third_party/exo-dv5-native/licenses/NOTICE.shaderc-toolchain @@ -0,0 +1,15179 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. + + GNU LIBRARY GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1991 Free Software Foundation, Inc. + 51 Franklin St, Fifth Floor, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the library GPL. It is + numbered 2 because it goes with version 2 of the ordinary GPL.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Library General Public License, applies to some +specially designated Free Software Foundation software, and to any +other libraries whose authors decide to use it. You can use it for +your libraries, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if +you distribute copies of the library, or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link a program with the library, you must provide +complete object files to the recipients so that they can relink them +with the library, after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + Our method of protecting your rights has two steps: (1) copyright +the library, and (2) offer you this license which gives you legal +permission to copy, distribute and/or modify the library. + + Also, for each distributor's protection, we want to make certain +that everyone understands that there is no warranty for this free +library. If the library is modified by someone else and passed on, we +want its recipients to know that what they have is not the original +version, so that any problems introduced by others will not reflect on +the original authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that companies distributing free +software will individually obtain patent licenses, thus in effect +transforming the program into proprietary software. To prevent this, +we have made it clear that any patent must be licensed for everyone's +free use or not licensed at all. + + Most GNU software, including some libraries, is covered by the ordinary +GNU General Public License, which was designed for utility programs. This +license, the GNU Library General Public License, applies to certain +designated libraries. This license is quite different from the ordinary +one; be sure to read it in full, and don't assume that anything in it is +the same as in the ordinary license. + + The reason we have a separate public license for some libraries is that +they blur the distinction we usually make between modifying or adding to a +program and simply using it. Linking a program with a library, without +changing the library, is in some sense simply using the library, and is +analogous to running a utility program or application program. However, in +a textual and legal sense, the linked executable is a combined work, a +derivative of the original library, and the ordinary General Public License +treats it as such. + + Because of this blurred distinction, using the ordinary General +Public License for libraries did not effectively promote software +sharing, because most developers did not use the libraries. We +concluded that weaker conditions might promote sharing better. + + However, unrestricted linking of non-free programs would deprive the +users of those programs of all benefit from the free status of the +libraries themselves. This Library General Public License is intended to +permit developers of non-free programs to use free libraries, while +preserving your freedom as a user of such programs to change the free +libraries that are incorporated in them. (We have not seen how to achieve +this as regards changes in header files, but we have achieved it as regards +changes in the actual functions of the Library.) The hope is that this +will lead to faster development of free libraries. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, while the latter only +works together with the library. + + Note that it is possible for a library to be covered by the ordinary +General Public License rather than by this special one. + + GNU LIBRARY GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library which +contains a notice placed by the copyright holder or other authorized +party saying it may be distributed under the terms of this Library +General Public License (also called "this License"). Each licensee is +addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also compile or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + c) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + d) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the source code distributed need not include anything that is normally +distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Library General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + + + + + The "Artistic License" + + Preamble + +The intent of this document is to state the conditions under which a +Package may be copied, such that the Copyright Holder maintains some +semblance of artistic control over the development of the package, +while giving the users of the package the right to use and distribute +the Package in a more-or-less customary fashion, plus the right to make +reasonable modifications. + +Definitions: + + "Package" refers to the collection of files distributed by the + Copyright Holder, and derivatives of that collection of files + created through textual modification. + + "Standard Version" refers to such a Package if it has not been + modified, or has been modified in accordance with the wishes + of the Copyright Holder as specified below. + + "Copyright Holder" is whoever is named in the copyright or + copyrights for the package. + + "You" is you, if you're thinking about copying or distributing + this Package. + + "Reasonable copying fee" is whatever you can justify on the + basis of media cost, duplication charges, time of people involved, + and so on. (You will not be required to justify it to the + Copyright Holder, but only to the computing community at large + as a market that must bear the fee.) + + "Freely Available" means that no fee is charged for the item + itself, though there may be fees involved in handling the item. + It also means that recipients of the item may redistribute it + under the same conditions they received it. + +1. You may make and give away verbatim copies of the source form of the +Standard Version of this Package without restriction, provided that you +duplicate all of the original copyright notices and associated disclaimers. + +2. You may apply bug fixes, portability fixes and other modifications +derived from the Public Domain or from the Copyright Holder. A Package +modified in such a way shall still be considered the Standard Version. + +3. You may otherwise modify your copy of this Package in any way, provided +that you insert a prominent notice in each changed file stating how and +when you changed that file, and provided that you do at least ONE of the +following: + + a) place your modifications in the Public Domain or otherwise make them + Freely Available, such as by posting said modifications to Usenet or + an equivalent medium, or placing the modifications on a major archive + site such as uunet.uu.net, or by allowing the Copyright Holder to include + your modifications in the Standard Version of the Package. + + b) use the modified Package only within your corporation or organization. + + c) rename any non-standard executables so the names do not conflict + with standard executables, which must also be provided, and provide + a separate manual page for each non-standard executable that clearly + documents how it differs from the Standard Version. + + d) make other distribution arrangements with the Copyright Holder. + +4. You may distribute the programs of this Package in object code or +executable form, provided that you do at least ONE of the following: + + a) distribute a Standard Version of the executables and library files, + together with instructions (in the manual page or equivalent) on where + to get the Standard Version. + + b) accompany the distribution with the machine-readable source of + the Package with your modifications. + + c) give non-standard executables non-standard names, and clearly + document the differences in manual pages (or equivalent), together + with instructions on where to get the Standard Version. + + d) make other distribution arrangements with the Copyright Holder. + +5. You may charge a reasonable copying fee for any distribution of this +Package. You may charge any fee you choose for support of this +Package. You may not charge a fee for this Package itself. However, +you may distribute this Package in aggregate with other (possibly +commercial) programs as part of a larger (possibly commercial) software +distribution provided that you do not advertise this Package as a +product of your own. You may embed this Package's interpreter within +an executable of yours (by linking); this shall be construed as a mere +form of aggregation, provided that the complete Standard Version of the +interpreter is so embedded. + +6. The scripts and library files supplied as input to or produced as +output from the programs of this Package do not automatically fall +under the copyright of this Package, but belong to whoever generated +them, and may be sold commercially, and may be aggregated with this +Package. If such scripts or library files are aggregated with this +Package via the so-called "undump" or "unexec" methods of producing a +binary executable image, then distribution of such an image shall +neither be construed as a distribution of this Package nor shall it +fall under the restrictions of Paragraphs 3 and 4, provided that you do +not represent such an executable image as a Standard Version of this +Package. + +7. C subroutines (or comparably compiled subroutines in other +languages) supplied by you and linked into this Package in order to +emulate subroutines and variables of the language defined by this +Package shall not be considered part of this Package, but are the +equivalent of input as in Paragraph 6, provided these subroutines do +not change the language in any way that would cause it to fail the +regression tests for the language. + +8. Aggregation of this Package with a commercial distribution is always +permitted provided that the use of this Package is embedded; that is, +when no overt attempt is made to make this Package's interfaces visible +to the end user of the commercial distribution. Such use shall not be +construed as a distribution of this Package. + +9. The name of the Copyright Holder may not be used to endorse or promote +products derived from this software without specific prior written permission. + +10. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED +WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + + The End + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. + +============================================================================== +The LLVM Project is under the Apache License v2.0 with LLVM Exceptions: +============================================================================== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +---- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. + +============================================================================== +Software from third parties included in the LLVM Project: +============================================================================== +The LLVM Project contains third party software which is under different license +terms. All such code will be identified clearly using at least one of two +mechanisms: +1) It will be in a separate directory tree with its own `LICENSE.txt` or + `LICENSE` file at the top containing the specific license and restrictions + which apply to that software, or +2) It will contain specific license and restriction terms at the top of every + file. + +============================================================================== +Legacy LLVM License (https://llvm.org/docs/DeveloperPolicy.html#legacy): +============================================================================== +University of Illinois/NCSA +Open Source License + +Copyright (c) 2003-2019 University of Illinois at Urbana-Champaign. +All rights reserved. + +Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal with +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at + Urbana-Champaign, nor the names of its contributors may be used to + endorse or promote products derived from this Software without specific + prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE +SOFTWARE. + + +============================================================================== +The LLVM Project is under the Apache License v2.0 with LLVM Exceptions: +============================================================================== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +---- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. + +============================================================================== +Software from third parties included in the LLVM Project: +============================================================================== +The LLVM Project contains third party software which is under different license +terms. All such code will be identified clearly using at least one of two +mechanisms: +1) It will be in a separate directory tree with its own `LICENSE.txt` or + `LICENSE` file at the top containing the specific license and restrictions + which apply to that software, or +2) It will contain specific license and restriction terms at the top of every + file. + +============================================================================== +Legacy LLVM License (https://llvm.org/docs/DeveloperPolicy.html#legacy): +============================================================================== + +The compiler_rt library is dual licensed under both the University of Illinois +"BSD-Like" license and the MIT license. As a user of this code you may choose +to use it under either license. As a contributor, you agree to allow your code +to be used under both. + +Full text of the relevant licenses is included below. + +============================================================================== + +University of Illinois/NCSA +Open Source License + +Copyright (c) 2009-2019 by the contributors listed in CREDITS.TXT + +All rights reserved. + +Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal with +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at + Urbana-Champaign, nor the names of its contributors may be used to + endorse or promote products derived from this Software without specific + prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE +SOFTWARE. + +============================================================================== + +Copyright (c) 2009-2015 by the contributors listed in CREDITS.TXT + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +============================================================================== +The LLVM Project is under the Apache License v2.0 with LLVM Exceptions: +============================================================================== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +---- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. + +============================================================================== +Software from third parties included in the LLVM Project: +============================================================================== +The LLVM Project contains third party software which is under different license +terms. All such code will be identified clearly using at least one of two +mechanisms: +1) It will be in a separate directory tree with its own `LICENSE.txt` or + `LICENSE` file at the top containing the specific license and restrictions + which apply to that software, or +2) It will contain specific license and restriction terms at the top of every + file. + +============================================================================== +Legacy LLVM License (https://llvm.org/docs/DeveloperPolicy.html#legacy): +============================================================================== + +The libc++ library is dual licensed under both the University of Illinois +"BSD-Like" license and the MIT license. As a user of this code you may choose +to use it under either license. As a contributor, you agree to allow your code +to be used under both. + +Full text of the relevant licenses is included below. + +============================================================================== + +University of Illinois/NCSA +Open Source License + +Copyright (c) 2009-2019 by the contributors listed in CREDITS.TXT + +All rights reserved. + +Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal with +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at + Urbana-Champaign, nor the names of its contributors may be used to + endorse or promote products derived from this Software without specific + prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE +SOFTWARE. + +============================================================================== + +Copyright (c) 2009-2014 by the contributors listed in CREDITS.TXT + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +============================================================================== +The LLVM Project is under the Apache License v2.0 with LLVM Exceptions: +============================================================================== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +---- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. + +============================================================================== +Software from third parties included in the LLVM Project: +============================================================================== +The LLVM Project contains third party software which is under different license +terms. All such code will be identified clearly using at least one of two +mechanisms: +1) It will be in a separate directory tree with its own `LICENSE.txt` or + `LICENSE` file at the top containing the specific license and restrictions + which apply to that software, or +2) It will contain specific license and restriction terms at the top of every + file. + +============================================================================== +Legacy LLVM License (https://llvm.org/docs/DeveloperPolicy.html#legacy): +============================================================================== + +The libc++abi library is dual licensed under both the University of Illinois +"BSD-Like" license and the MIT license. As a user of this code you may choose +to use it under either license. As a contributor, you agree to allow your code +to be used under both. + +Full text of the relevant licenses is included below. + +============================================================================== + +University of Illinois/NCSA +Open Source License + +Copyright (c) 2009-2019 by the contributors listed in CREDITS.TXT + +All rights reserved. + +Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal with +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at + Urbana-Champaign, nor the names of its contributors may be used to + endorse or promote products derived from this Software without specific + prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE +SOFTWARE. + +============================================================================== + +Copyright (c) 2009-2014 by the contributors listed in CREDITS.TXT + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +============================================================================== +The LLVM Project is under the Apache License v2.0 with LLVM Exceptions: +============================================================================== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +---- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. + +============================================================================== +Software from third parties included in the LLVM Project: +============================================================================== +The LLVM Project contains third party software which is under different license +terms. All such code will be identified clearly using at least one of two +mechanisms: +1) It will be in a separate directory tree with its own `LICENSE.txt` or + `LICENSE` file at the top containing the specific license and restrictions + which apply to that software, or +2) It will contain specific license and restriction terms at the top of every + file. + +============================================================================== +Legacy LLVM License (https://llvm.org/docs/DeveloperPolicy.html#legacy): +============================================================================== + +The software contained in this directory tree is dual licensed under both the +University of Illinois "BSD-Like" license and the MIT license. As a user of +this code you may choose to use it under either license. As a contributor, +you agree to allow your code to be used under both. The full text of the +relevant licenses is included below. + +In addition, a license agreement from the copyright/patent holders of the +software contained in this directory tree is included below. + +============================================================================== + +University of Illinois/NCSA +Open Source License + +Copyright (c) 1997-2019 Intel Corporation + +All rights reserved. + +Developed by: + OpenMP Runtime Team + Intel Corporation + http://www.openmprtl.org + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal with +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of Intel Corporation OpenMP Runtime Team nor the + names of its contributors may be used to endorse or promote products + derived from this Software without specific prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE +SOFTWARE. + +============================================================================== + +Copyright (c) 1997-2019 Intel Corporation + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +============================================================================== + +Intel Corporation + +Software Grant License Agreement ("Agreement") + +Except for the license granted herein to you, Intel Corporation ("Intel") reserves +all right, title, and interest in and to the Software (defined below). + +Definition + +"Software" means the code and documentation as well as any original work of +authorship, including any modifications or additions to an existing work, that +is intentionally submitted by Intel to llvm.org (http://llvm.org) ("LLVM") for +inclusion in, or documentation of, any of the products owned or managed by LLVM +(the "Work"). For the purposes of this definition, "submitted" means any form of +electronic, verbal, or written communication sent to LLVM or its +representatives, including but not limited to communication on electronic +mailing lists, source code control systems, and issue tracking systems that are +managed by, or on behalf of, LLVM for the purpose of discussing and improving +the Work, but excluding communication that is conspicuously marked otherwise. + +1. Grant of Copyright License. Subject to the terms and conditions of this + Agreement, Intel hereby grants to you and to recipients of the Software + distributed by LLVM a perpetual, worldwide, non-exclusive, no-charge, + royalty-free, irrevocable copyright license to reproduce, prepare derivative + works of, publicly display, publicly perform, sublicense, and distribute the + Software and such derivative works. + +2. Grant of Patent License. Subject to the terms and conditions of this + Agreement, Intel hereby grants you and to recipients of the Software + distributed by LLVM a perpetual, worldwide, non-exclusive, no-charge, + royalty-free, irrevocable (except as stated in this section) patent license + to make, have made, use, offer to sell, sell, import, and otherwise transfer + the Work, where such license applies only to those patent claims licensable + by Intel that are necessarily infringed by Intel's Software alone or by + combination of the Software with the Work to which such Software was + submitted. If any entity institutes patent litigation against Intel or any + other entity (including a cross-claim or counterclaim in a lawsuit) alleging + that Intel's Software, or the Work to which Intel has contributed constitutes + direct or contributory patent infringement, then any patent licenses granted + to that entity under this Agreement for the Software or Work shall terminate + as of the date such litigation is filed. + +Unless required by applicable law or agreed to in writing, the software is +provided on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +either express or implied, including, without limitation, any warranties or +conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A +PARTICULAR PURPOSE. + +============================================================================== + +============================================================================== +The LLVM Project is under the Apache License v2.0 with LLVM Exceptions: +============================================================================== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +---- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. + +============================================================================== +Software from third parties included in the LLVM Project: +============================================================================== +The LLVM Project contains third party software which is under different license +terms. All such code will be identified clearly using at least one of two +mechanisms: +1) It will be in a separate directory tree with its own `LICENSE.txt` or + `LICENSE` file at the top containing the specific license and restrictions + which apply to that software, or +2) It will contain specific license and restriction terms at the top of every + file. + +============================================================================== +Legacy LLVM License (https://llvm.org/docs/DeveloperPolicy.html#legacy): +============================================================================== +University of Illinois/NCSA +Open Source License + +Copyright (c) 2007-2019 University of Illinois at Urbana-Champaign. +All rights reserved. + +Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal with +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at + Urbana-Champaign, nor the names of its contributors may be used to + endorse or promote products derived from this Software without specific + prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE +SOFTWARE. + +============================================================================== +The LLVM Project is under the Apache License v2.0 with LLVM Exceptions: +============================================================================== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +---- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. + +============================================================================== +Software from third parties included in the LLVM Project: +============================================================================== +The LLVM Project contains third party software which is under different license +terms. All such code will be identified clearly using at least one of two +mechanisms: +1) It will be in a separate directory tree with its own `LICENSE.txt` or + `LICENSE` file at the top containing the specific license and restrictions + which apply to that software, or +2) It will contain specific license and restriction terms at the top of every + file. + +============================================================================== +Legacy LLVM License (https://llvm.org/docs/DeveloperPolicy.html#legacy): +============================================================================== +University of Illinois/NCSA +Open Source License + +Copyright (c) 2007-2019 University of Illinois at Urbana-Champaign. +All rights reserved. + +Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal with +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at + Urbana-Champaign, nor the names of its contributors may be used to + endorse or promote products derived from this Software without specific + prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE +SOFTWARE. + +============================================================================== +The LLVM Project is under the Apache License v2.0 with LLVM Exceptions: +============================================================================== + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +---- LLVM Exceptions to the Apache 2.0 License ---- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into an Object form of such source code, you +may redistribute such embedded portions in such Object form without complying +with the conditions of Sections 4(a), 4(b) and 4(d) of the License. + +In addition, if you combine or link compiled forms of this Software with +software that is licensed under the GPLv2 ("Combined Software") and if a +court of competent jurisdiction determines that the patent provision (Section +3), the indemnity provision (Section 9) or other Section of the License +conflicts with the conditions of the GPLv2, you may retroactively and +prospectively choose to deem waived or otherwise exclude such Section(s) of +the License, but only in their entirety and only with respect to the Combined +Software. + +============================================================================== +Software from third parties included in the LLVM Project: +============================================================================== +The LLVM Project contains third party software which is under different license +terms. All such code will be identified clearly using at least one of two +mechanisms: +1) It will be in a separate directory tree with its own `LICENSE.txt` or + `LICENSE` file at the top containing the specific license and restrictions + which apply to that software, or +2) It will contain specific license and restriction terms at the top of every + file. + +============================================================================== +Legacy LLVM License (https://llvm.org/docs/DeveloperPolicy.html#legacy): +============================================================================== +University of Illinois/NCSA +Open Source License + +Copyright (c) 2011-2019 by the contributors listed in CREDITS.TXT +All rights reserved. + +Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal with +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at + Urbana-Champaign, nor the names of its contributors may be used to + endorse or promote products derived from this Software without specific + prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE +SOFTWARE. + +Copyright (C) 2009 The Android Open Source Project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + * +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + + + +Copyright (C) 2008 The Android Open Source Project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + + + +Copyright (c) 1994 +Hewlett-Packard Company + +Permission to use, copy, modify, distribute and sell this software +and its documentation for any purpose is hereby granted without fee, +provided that the above copyright notice appear in all copies and +that both that copyright notice and this permission notice appear +in supporting documentation. Hewlett-Packard Company makes no +representations about the suitability of this software for any +purpose. It is provided "as is" without express or implied warranty. + + + +Copyright (c) 1996,1997 +Silicon Graphics Computer Systems, Inc. + +Permission to use, copy, modify, distribute and sell this software +and its documentation for any purpose is hereby granted without fee, +provided that the above copyright notice appear in all copies and +that both that copyright notice and this permission notice appear +in supporting documentation. Silicon Graphics makes no +representations about the suitability of this software for any +purpose. It is provided "as is" without express or implied warranty. + +Copyright (C) 2016 The Android Open Source Project + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Copyright (C) 2018 The Android Open Source Project + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + Copyright (c) 1993 John Brezak + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. The name of the author may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, +INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + + Copyright (c) 2009-2013 The Linux Foundation. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of The Linux Foundation nor the names of its contributors may + be used to endorse or promote products derived from this software + without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +==================================================== +Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + +Developed at SunPro, a Sun Microsystems, Inc. business. +Permission to use, copy, modify, and distribute this +software is freely granted, provided that this notice +is preserved. + +------------------------------------------------------------------- + +Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the project nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (C) 2004, 2005, 2008 Internet Systems Consortium, Inc. ("ISC") +Copyright (C) 1995-1999, 2001, 2003 Internet Software Consortium. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (C) 2004, 2005, 2008 Internet Systems Consortium, Inc. ("ISC") +Copyright (C) 1997-2001 Internet Software Consortium. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (C) 2006 The Android Open Source Project + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +------------------------------------------------------------------- + +Copyright (C) 2006 The Android Open Source Project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (C) 2008 The Android Open Source Project + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +------------------------------------------------------------------- + +Copyright (C) 2008 The Android Open Source Project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (C) 2008 The Android Open Source Project +All rights reserved. +Copyright (c) 2013-2014, NVIDIA Corporation. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (C) 2009 The Android Open Source Project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (C) 2010 The Android Open Source Project + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +------------------------------------------------------------------- + +Copyright (C) 2010 The Android Open Source Project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (C) 2010 The Android Open Source Project +Copyright (c) 2008 ARM Ltd +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the company may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY ARM LTD ``AS IS'' AND ANY EXPRESS OR IMPLIED +WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL ARM LTD BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Android adaptation and tweak by Jim Huang . + +------------------------------------------------------------------- + +Copyright (C) 2011 The Android Open Source Project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (C) 2012 The Android Open Source Project + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +------------------------------------------------------------------- + +Copyright (C) 2012 The Android Open Source Project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (C) 2013 Pietro Cerutti + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (C) 2013 The Android Open Source Project + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +------------------------------------------------------------------- + +Copyright (C) 2013 The Android Open Source Project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (C) 2013 The Android Open Source Project +All rights reserved. +Copyright (c) 2013-2014 NVIDIA Corporation. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (C) 2014 The Android Open Source Project + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +------------------------------------------------------------------- + +Copyright (C) 2014 The Android Open Source Project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (C) 2015 The Android Open Source Project + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +------------------------------------------------------------------- + +Copyright (C) 2015 The Android Open Source Project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (C) 2016 The Android Open Source Project + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +------------------------------------------------------------------- + +Copyright (C) 2016 The Android Open Source Project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (C) 2017 The Android Open Source Project + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +------------------------------------------------------------------- + +Copyright (C) 2017 The Android Open Source Project +All rights reserved. + +Copyright (c) 2009-2011, Code Aurora Forum. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (C) 2017 The Android Open Source Project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (C) 2018 The Android Open Source Project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (C) 2019 The Android Open Source Project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (C) 2020 The Android Open Source Project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (C) 2021 The Android Open Source Project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (C) 2022 The Android Open Source Project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (C) 2023 The Android Open Source Project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (C) 2024 The Android Open Source Project + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +------------------------------------------------------------------- + +Copyright (C) 2024 The Android Open Source Project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1980, 1983, 1988, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. All advertising materials mentioning features or use of this software + must display the following acknowledgement: + This product includes software developed by the University of + California, Berkeley and its contributors. +4. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + + +Portions Copyright (c) 1993 by Digital Equipment Corporation. + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies, and that +the name of Digital Equipment Corporation not be used in advertising or +publicity pertaining to distribution of the document or software without +specific, written prior permission. + +THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL +WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT +CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL +DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR +PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS +ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS +SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 1982, 1986, 1988, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1982, 1986, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1982, 1986, 1993 + The Regents of the University of California. All rights reserved. +(c) UNIX System Laboratories, Inc. +All or some portions of this file are derived from material licensed +to the University of California by American Telephone and Telegraph +Co. or Unix System Laboratories, Inc. and are reproduced herein with +the permission of UNIX System Laboratories, Inc. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1983, 1987, 1989 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1983, 1989 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. All advertising materials mentioning features or use of this software + must display the following acknowledgement: + This product includes software developed by the University of + California, Berkeley and its contributors. +4. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1983, 1989, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1983, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1985 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. All advertising materials mentioning features or use of this software + must display the following acknowledgement: + This product includes software developed by the University of + California, Berkeley and its contributors. +4. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1985 Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1985, 1988, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +Portions Copyright (c) 1993 by Digital Equipment Corporation. + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies, and that +the name of Digital Equipment Corporation not be used in advertising or +publicity pertaining to distribution of the document or software without +specific, written prior permission. + +THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL +WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT +CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL +DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR +PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS +ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS +SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 1985, 1989, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. All advertising materials mentioning features or use of this software + must display the following acknowledgement: + This product includes software developed by the University of + California, Berkeley and its contributors. +4. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1985, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. All advertising materials mentioning features or use of this software + must display the following acknowledgement: + This product includes software developed by the University of + California, Berkeley and its contributors. +4. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1985, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1987 Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1987, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. All advertising materials mentioning features or use of this software + must display the following acknowledgement: + This product includes software developed by the University of + California, Berkeley and its contributors. +4. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1987, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1988 Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1988 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1988, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. All advertising materials mentioning features or use of this software + must display the following acknowledgement: + This product includes software developed by the University of + California, Berkeley and its contributors. +4. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1988, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1989 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1989 The Regents of the University of California. +All rights reserved. +(c) UNIX System Laboratories, Inc. +All or some portions of this file are derived from material licensed +to the University of California by American Telephone and Telegraph +Co. or Unix System Laboratories, Inc. and are reproduced herein with +the permission of UNIX System Laboratories, Inc. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1989, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1989, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +4. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1989, 1993 + The Regents of the University of California. All rights reserved. + +This code is derived from software contributed to Berkeley by +Guido van Rossum. + +Copyright (c) 2011 The FreeBSD Foundation +All rights reserved. +Portions of this software were developed by David Chisnall +under sponsorship from the FreeBSD Foundation. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1989, 1993 + The Regents of the University of California. All rights reserved. + +This code is derived from software contributed to Berkeley by +Guido van Rossum. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1989, 1993 + The Regents of the University of California. All rights reserved. + +This code is derived from software contributed to Berkeley by +Roger L. Snyder. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1989, 1993 + The Regents of the University of California. All rights reserved. +(c) UNIX System Laboratories, Inc. +All or some portions of this file are derived from material licensed +to the University of California by American Telephone and Telegraph +Co. or Unix System Laboratories, Inc. and are reproduced herein with +the permission of UNIX System Laboratories, Inc. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1990 Regents of the University of California. +All rights reserved. + +This code is derived from software contributed to Berkeley by +Chris Torek. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1990 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1990 The Regents of the University of California. +All rights reserved. + +This code is derived from software contributed to Berkeley by +Chris Torek. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1990 The Regents of the University of California. +All rights reserved. + +This code is derived from software contributed to Berkeley by +William Jolitz. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1990, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1990, 1993 + The Regents of the University of California. All rights reserved. + +This code is derived from software contributed to Berkeley by +Chris Torek. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1990, 1993 + The Regents of the University of California. All rights reserved. + +This code is derived from software contributed to Berkeley by +Donn Seeley at UUNET Technologies, Inc. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1990, 1993 + The Regents of the University of California. All rights reserved. + +This code is derived from software contributed to Berkeley by +Donn Seeley at UUNET Technologies, Inc. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +4. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1990, 1993 + The Regents of the University of California. All rights reserved. +(c) UNIX System Laboratories, Inc. +All or some portions of this file are derived from material licensed +to the University of California by American Telephone and Telegraph +Co. or Unix System Laboratories, Inc. and are reproduced herein with +the permission of UNIX System Laboratories, Inc. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1990, 1993, 1994 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1991 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1991, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1991, 1993 + The Regents of the University of California. All rights reserved. + +This code is derived from software contributed to Berkeley by +Berkeley Software Design, Inc. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1991, 1993 + The Regents of the University of California. All rights reserved. +(c) UNIX System Laboratories, Inc. +All or some portions of this file are derived from material licensed +to the University of California by American Telephone and Telegraph +Co. or Unix System Laboratories, Inc. and are reproduced herein with +the permission of UNIX System Laboratories, Inc. + +This code is derived from software contributed to Berkeley by +Hugh Smith at The University of Guelph. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1992 Henry Spencer. +Copyright (c) 1992, 1993 + The Regents of the University of California. All rights reserved. + +This code is derived from software contributed to Berkeley by +Henry Spencer of the University of Toronto. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1992 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1992, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1992, 1993 + The Regents of the University of California. All rights reserved. + +This software was developed by the Computer Systems Engineering group +at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and +contributed to Berkeley. + +All advertising materials mentioning features or use of this software +must display the following acknowledgement: + This product includes software developed by the University of + California, Lawrence Berkeley Laboratory. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. All advertising materials mentioning features or use of this software + must display the following acknowledgement: + This product includes software developed by the University of + California, Berkeley and its contributors. +4. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1992, 1993 + The Regents of the University of California. All rights reserved. +(c) UNIX System Laboratories, Inc. +All or some portions of this file are derived from material licensed +to the University of California by American Telephone and Telegraph +Co. or Unix System Laboratories, Inc. and are reproduced herein with +the permission of UNIX System Laboratories, Inc. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1993 Martin Birgmeier +All rights reserved. + +You may redistribute unmodified or modified versions of this source +code provided that the above copyright notice and this and the +following conditions are retained. + +This software is provided ``as is'', and comes with no warranties +of any kind. I shall in no event be liable for anything that happens +to anyone/anything when using this software. + +------------------------------------------------------------------- + +Copyright (c) 1994 SigmaSoft, Th. Lockert +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1994 Winning Strategies, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. All advertising materials mentioning features or use of this software + must display the following acknowledgement: + This product includes software developed by Winning Strategies, Inc. +4. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1996 by Internet Software Consortium. + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS +ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE +CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL +DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR +PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS +ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS +SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 1996, David Mazieres +Copyright (c) 2008, Damien Miller +Copyright (c) 2013, Markus Friedl + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 1996, David Mazieres +Copyright (c) 2008, Damien Miller +Copyright (c) 2013, Markus Friedl +Copyright (c) 2014, Theo de Raadt + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 1996-1998, 2008 Theo de Raadt +Copyright (c) 1997, 2008-2009 Todd C. Miller + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 1997 Mark Brinicombe +Copyright (C) 2010 The Android Open Source Project +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. All advertising materials mentioning features or use of this software + must display the following acknowledgement: + This product includes software developed by Mark Brinicombe +4. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1997 Niklas Hallqvist. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1997 The NetBSD Foundation, Inc. +All rights reserved. + +This code is derived from software contributed to The NetBSD Foundation +by Neil A. Carson and Mark Brinicombe + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1997 Todd C. Miller + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 1997 Todd C. Miller +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1997, 1998, 1999, 2004 The NetBSD Foundation, Inc. +All rights reserved. + +This code is derived from software contributed to The NetBSD Foundation +by Luke Mewburn. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1997, 1998, 1999, 2004 The NetBSD Foundation, Inc. +All rights reserved. + +This code is derived from software contributed to The NetBSD Foundation +by Luke Mewburn; and by Jason R. Thorpe. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. All advertising materials mentioning features or use of this software + must display the following acknowledgement: + This product includes software developed by the NetBSD + Foundation, Inc. and its contributors. +4. Neither the name of The NetBSD Foundation nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1997, 1998, 2005, 2008 The NetBSD Foundation, Inc. +All rights reserved. + +This code was contributed to The NetBSD Foundation by Klaus Klein. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1997, 2005 Todd C. Miller + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 1998 The NetBSD Foundation, Inc. +All rights reserved. + +This code is derived from software contributed to The NetBSD Foundation +by Klaus Klein. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. All advertising materials mentioning features or use of this software + must display the following acknowledgement: + This product includes software developed by the NetBSD + Foundation, Inc. and its contributors. +4. Neither the name of The NetBSD Foundation nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 1998, 2015 Todd C. Miller + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 2000 Ben Harris. +Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the project nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2000 The NetBSD Foundation, Inc. +All rights reserved. + +This code is derived from software contributed to The NetBSD Foundation +by Dieter Baron and Thomas Klausner. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2001 Wasabi Systems, Inc. +All rights reserved. + +Written by Frank van der Linden for Wasabi Systems, Inc. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. All advertising materials mentioning features or use of this software + must display the following acknowledgement: + This product includes software developed for the NetBSD Project by + Wasabi Systems, Inc. +4. The name of Wasabi Systems, Inc. may not be used to endorse + or promote products derived from this software without specific prior + written permission. + +THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL WASABI SYSTEMS, INC +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2001-2011 The FreeBSD Project. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2002 Daniel Hartmeier +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2002 Tim J. Robbins. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2002 Todd C. Miller + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +Sponsored in part by the Defense Advanced Research Projects +Agency (DARPA) and Air Force Research Laboratory, Air Force +Materiel Command, USAF, under agreement number F39502-99-1-0512. + +------------------------------------------------------------------- + +Copyright (c) 2002, 2003 Tim J. Robbins. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2002-2004 Tim J. Robbins +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2002-2004 Tim J. Robbins. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2003 David Schultz +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2003 Networks Associates Technology, Inc. +All rights reserved. + +Portions of this software were developed for the FreeBSD Project by +Jacques A. Vidrine, Safeport Network Services, and Network +Associates Laboratories, the Security Research Division of Network +Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035 +("CBOSS"), as part of the DARPA CHATS research program. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2003 Todd C. Miller + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +Sponsored in part by the Defense Advanced Research Projects +Agency (DARPA) and Air Force Research Laboratory, Air Force +Materiel Command, USAF, under agreement number F39502-99-1-0512. + +------------------------------------------------------------------- + +Copyright (c) 2003, 2004 Todd C. Miller + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +Sponsored in part by the Defense Advanced Research Projects +Agency (DARPA) and Air Force Research Laboratory, Air Force +Materiel Command, USAF, under agreement number F39502-99-1-0512. + +------------------------------------------------------------------- + +Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") +Copyright (c) 1995,1999 by Internet Software Consortium. + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") +Copyright (c) 1995-1999 by Internet Software Consortium + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") +Copyright (c) 1995-1999 by Internet Software Consortium. + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") +Copyright (c) 1996,1999 by Internet Software Consortium. + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") +Copyright (c) 1996-1999 by Internet Software Consortium + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") +Copyright (c) 1996-1999 by Internet Software Consortium. + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") +Copyright (c) 1997,1999 by Internet Software Consortium. + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") +Copyright (c) 1999 by Internet Software Consortium. + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") +Portions Copyright (c) 1996-1999 by Internet Software Consortium. + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 2004, 2005 David Schultz +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2004-2005 David Schultz +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2004-2005 David Schultz +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2005 by Internet Systems Consortium, Inc. ("ISC") +Copyright (c) 1995-1999 by Internet Software Consortium + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 2005-2018 Rich Felker + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 2005-2020 Rich Felker, et al. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 2007-2008 Michael G Schwern + +This software originally derived from Paul Sheer's pivotal_gmtime_r.c. + +The MIT License: + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 2008, 2016 Todd C. Miller + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 2008, 2017 Otto Moerbeek + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 2008, Damien Miller + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 2009 David Schultz +All rights reserved. + +Copyright (c) 2011 The FreeBSD Foundation +All rights reserved. +Portions of this software were developed by David Chisnall +under sponsorship from the FreeBSD Foundation. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2009 The NetBSD Foundation, Inc. + +This code is derived from software contributed to The NetBSD Foundation +by Roy Marples. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2010 The NetBSD Foundation, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2010 Todd C. Miller + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 2010, 2011, 2012, 2013 Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + + * Neither the name of Intel Corporation nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2010, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + + * Neither the name of Intel Corporation nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2011 Ed Schouten + David Chisnall +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2011 Martin Pieuchot + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 2011 The Android Open Source Project +Copyright (c) 2008 ARM Ltd +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the company may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY ARM LTD ``AS IS'' AND ANY EXPRESS OR IMPLIED +WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL ARM LTD BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2011, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + + * Neither the name of Intel Corporation nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2011, VMware, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the VMware, Inc. nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2012, Linaro Limited + All rights reserved. + Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the Linaro nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2012-2014 ARM Ltd +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the company may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY ARM LTD ``AS IS'' AND ANY EXPRESS OR IMPLIED +WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL ARM LTD BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2013 ARM Ltd +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the company may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY ARM LTD ``AS IS'' AND ANY EXPRESS OR IMPLIED +WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL ARM LTD BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2013 Antoine Jacoutot + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Copyright (c) 2013 The NetBSD Foundation, Inc. +All rights reserved. + +This code is derived from software contributed to The NetBSD Foundation +by Christos Zoulas. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2014, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + + * Neither the name of Intel Corporation nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2015 Nuxi, https://nuxi.nl/ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c) 2023 SiFive, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the company may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY SIFIVE INC ``AS IS'' AND ANY EXPRESS OR IMPLIED +WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL SIFIVE INC BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c)1999 Citrus Project, +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c)2001 Citrus Project, +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright (c)2003 Citrus Project, +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +Copyright 1989 The Regents of the University of California. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + +------------------------------------------------------------------- + +Copyright 1997 Niels Provos +Copyright 2008 Damien Miller +All rights reserved. + +Theo de Raadt came up with the idea of using +such a mathematical system to generate more random (yet non-repeating) +ids to solve the resolver/named problem. But Niels designed the +actual system based on the constraints. + +Later modified by Damien Miller to wrap the LCG output in a 15-bit +permutation generator based on a Luby-Rackoff block cipher. This +ensures the output is non-repeating and preserves the MSB twiddle +trick, but makes it more resistant to LCG prediction. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT +NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF +THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +Portions Copyright (C) 2004, 2005, 2008, 2009 Internet Systems Consortium, Inc. ("ISC") +Portions Copyright (C) 1996-2003 Internet Software Consortium. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + +------------------------------------------------------------------- + +Portions Copyright (c) 1993 by Digital Equipment Corporation. + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies, and that +the name of Digital Equipment Corporation not be used in advertising or +publicity pertaining to distribution of the document or software without +specific, written prior permission. + +THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL +WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT +CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL +DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR +PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS +ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS +SOFTWARE. + +------------------------------------------------------------------- + +Portions Copyright (c) 1995 by International Business Machines, Inc. + +International Business Machines, Inc. (hereinafter called IBM) grants +permission under its copyrights to use, copy, modify, and distribute this +Software with or without fee, provided that the above copyright notice and +all paragraphs of this notice appear in all copies, and that the name of IBM +not be used in connection with the marketing of any product incorporating +the Software or modifications thereof, without specific, written prior +permission. + +To the extent it has a right to do so, IBM grants an immunity from suit +under its patents, if any, for the use, sale or manufacture of products to +the extent that such products are used for performing Domain Name System +dynamic updates in TCP/IP networks by means of the Software. No immunity is +granted for any product per se or for any other function of any product. + +THE SOFTWARE IS PROVIDED "AS IS", AND IBM DISCLAIMS ALL WARRANTIES, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE. IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL, +DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER ARISING +OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE, EVEN +IF IBM IS APPRISED OF THE POSSIBILITY OF SUCH DAMAGES. + +------------------------------------------------------------------- + +Portions Copyright(C) 1995, Jason Downs. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS +OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, +INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +SPDX-License-Identifier: BSD-2-Clause + +Copyright (c) 2002 Tim J. Robbins +All rights reserved. + +Copyright (c) 2011 The FreeBSD Foundation + +Portions of this software were developed by David Chisnall +under sponsorship from the FreeBSD Foundation. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +SPDX-License-Identifier: BSD-2-Clause + +Copyright (c) 2002 Tim J. Robbins +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +SPDX-License-Identifier: BSD-2-Clause + +Copyright (c) 2005 Tim J. Robbins. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +SPDX-License-Identifier: BSD-2-Clause + +Copyright (c) 2009 David Schultz +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +SPDX-License-Identifier: BSD-2-Clause + +Copyright (c) 2011 David Chisnall +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +SPDX-License-Identifier: BSD-2-Clause + +Copyright (c) 2015 Nuxi, https://nuxi.nl/ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +SPDX-License-Identifier: BSD-2-Clause + +Copyright (c) 2017, 2018 Dell EMC +Copyright (c) 2000, 2001, 2008, 2011, David E. O'Brien +Copyright (c) 1998 John D. Polstra. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +SPDX-License-Identifier: BSD-2-Clause + +Copyright (c)1999 Citrus Project, +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +SPDX-License-Identifier: BSD-3-Clause + +Copyright (c) 1989, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +SPDX-License-Identifier: BSD-3-Clause + +Copyright (c) 1990, 1993 + The Regents of the University of California. All rights reserved. + +This code is derived from software contributed to Berkeley by +Chris Torek. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +SPDX-License-Identifier: BSD-3-Clause + +Copyright (c) 1992, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +SPDX-License-Identifier: BSD-3-Clause + +Copyright (c) 1992, 1993, 1994 Henry Spencer. +Copyright (c) 1992, 1993, 1994 + The Regents of the University of California. All rights reserved. + +Copyright (c) 2011 The FreeBSD Foundation +All rights reserved. +Portions of this software were developed by David Chisnall +under sponsorship from the FreeBSD Foundation. + +This code is derived from software contributed to Berkeley by +Henry Spencer. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +SPDX-License-Identifier: BSD-3-Clause + +Copyright (c) 1992, 1993, 1994 Henry Spencer. +Copyright (c) 1992, 1993, 1994 + The Regents of the University of California. All rights reserved. + +This code is derived from software contributed to Berkeley by +Henry Spencer. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +SPDX-License-Identifier: BSD-3-Clause + +Copyright (c) 1998 Softweyr LLC. All rights reserved. + +strtok_r, from Berkeley strtok +Oct 13, 1998 by Wes Peters + +Copyright (c) 1988, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notices, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notices, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY SOFTWEYR LLC, THE REGENTS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SOFTWEYR LLC, THE +REGENTS, OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +SPDX-License-Identifier: BSD-3-Clause + +Copyright (c) 1998 Todd C. Miller +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the author may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------- + +SPDX-License-Identifier: BSD-3-Clause + +Copyright (c) 1999 + David E. O'Brien +Copyright (c) 1988, 1993 + The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. + +------------------------------------------------------------------- + +The author of this software is David M. Gay. + +Copyright (C) 1998 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +------------------------------------------------------------------- + +The author of this software is David M. Gay. + +Copyright (C) 1998, 1999 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +------------------------------------------------------------------- + +The author of this software is David M. Gay. + +Copyright (C) 1998, 2000 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +------------------------------------------------------------------- + +The author of this software is David M. Gay. + +Copyright (C) 1998-2000 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +------------------------------------------------------------------- + +The author of this software is David M. Gay. + +Copyright (C) 1998-2001 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +------------------------------------------------------------------- + +The author of this software is David M. Gay. + +Copyright (C) 2000 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +------------------------------------------------------------------- + +memcpy - copy memory area + +Copyright (c) 2012-2022, Arm Limited. +Copyright (c) 2024 Qualcomm Innovation Center, Inc. All rights reserved. +SPDX-License-Identifier: MIT OR Apache-2.0 WITH LLVM-exception + +------------------------------------------------------------------- + +Copyright (c) 2008-2009 The Khronos Group Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and/or associated documentation files (the +"Materials"), to deal in the Materials without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Materials, and to +permit persons to whom the Materials are furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Materials. + +THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +Copyright (C) 2016 The Android Open Source Project + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +Copyright (c) 2007-2017 The Khronos Group Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and/or associated documentation files (the +"Materials"), to deal in the Materials without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Materials, and to +permit persons to whom the Materials are furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Materials. + +THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +Copyright (c) 2017 The Khronos Group Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Copyright (c) 2013-2017 The Khronos Group Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and/or associated documentation files (the +"Materials"), to deal in the Materials without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Materials, and to +permit persons to whom the Materials are furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Materials. + +THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + +Copyright (c) 2017 The Khronos Group Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Copyright (c) 2013-2017 The Khronos Group Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and/or associated documentation files (the +"Materials"), to deal in the Materials without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Materials, and to +permit persons to whom the Materials are furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Materials. + +THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + +This document is licensed under the SGI Free Software B License Version +2.0. For details, see http://oss.sgi.com/projects/FreeB/ . + +Copyright (c) 2017 The Khronos Group Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Copyright (c) 2013-2017 The Khronos Group Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and/or associated documentation files (the +"Materials"), to deal in the Materials without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Materials, and to +permit persons to whom the Materials are furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Materials. + +THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + +Copyright (c) 2007-2010 The Khronos Group Inc. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and/or associated documentation files (the +"Materials "), to deal in the Materials without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Materials, and to +permit persons to whom the Materials are furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Materials. + +THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +Copyright (c) 2007-2009 The Khronos Group Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and /or associated documentation files (the "Materials "), to +deal in the Materials without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Materials, and to permit persons to whom the Materials are +furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Materials. + +THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS IN THE +MATERIALS. + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for the Android-specific code. == + ========================================================================= + +Android Code +Copyright 2005-2008 The Android Open Source Project + +This product includes software developed as part of +The Android Open Source Project (http://source.android.com). + + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for Apache Commons code. == + ========================================================================= + +Apache Commons +Copyright 1999-2006 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). + + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for Jakarta Commons Logging. == + ========================================================================= + +Jakarta Commons Logging (JCL) +Copyright 2005,2006 The Apache Software Foundation. + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). + + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for the Nuance code. == + ========================================================================= + +These files are Copyright 2007 Nuance Communications, but released under +the Apache2 License. + + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for the Media Codecs code. == + ========================================================================= + +Media Codecs +These files are Copyright 1998 - 2009 PacketVideo, but released under +the Apache2 License. + + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for the TagSoup code. == + ========================================================================= + +This file is part of TagSoup and is Copyright 2002-2008 by John Cowan. + +TagSoup is licensed under the Apache License, +Version 2.0. You may obtain a copy of this license at +http://www.apache.org/licenses/LICENSE-2.0 . You may also have +additional legal rights not granted by this license. + +TagSoup is distributed in the hope that it will be useful, but +unless required by applicable law or agreed to in writing, TagSoup +is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS +OF ANY KIND, either express or implied; not even the implied warranty +of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for Additional Codecs code. == + ========================================================================= + +Additional Codecs +These files are Copyright 2003-2010 VisualOn, but released under +the Apache2 License. + + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for the Audio Effects code. == + ========================================================================= + +Audio Effects +These files are Copyright (C) 2004-2010 NXP Software and +Copyright (C) 2010 The Android Open Source Project, but released under +the Apache2 License. + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + + +UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE + +Unicode Data Files include all data files under the directories +http://www.unicode.org/Public/, http://www.unicode.org/reports/, +and http://www.unicode.org/cldr/data/ . Unicode Software includes any +source code published in the Unicode Standard or under the directories +http://www.unicode.org/Public/, http://www.unicode.org/reports/, and +http://www.unicode.org/cldr/data/. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S DATA +FILES ("DATA FILES"), AND/OR SOFTWARE ("SOFTWARE"), YOU UNEQUIVOCALLY +ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE TERMS AND CONDITIONS OF +THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY, +DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 1991-2008 Unicode, Inc. All rights reserved. Distributed +under the Terms of Use in http://www.unicode.org/copyright.html. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Unicode data files and any associated documentation (the +"Data Files") or Unicode software and any associated documentation (the +"Software") to deal in the Data Files or Software without restriction, +including without limitation the rights to use, copy, modify, merge, +publish, distribute, and/or sell copies of the Data Files or Software, +and to permit persons to whom the Data Files or Software are furnished to +do so, provided that (a) the above copyright notice(s) and this permission +notice appear with all copies of the Data Files or Software, (b) both the +above copyright notice(s) and this permission notice appear in associated +documentation, and (c) there is clear notice in each modified Data File +or in the Software as well as in the documentation associated with the +Data File(s) or Software that the data or software has been modified. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS +INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT +OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE +OR PERFORMANCE OF THE DATA FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder +shall not be used in advertising or otherwise to promote the sale, use +or other dealings in these Data Files or Software without prior written +authorization of the copyright holder. + + Copyright (c) 2005-2008, The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + + Copyright (c) 2018, The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for the Android-specific code. == + ========================================================================= + +Android Code +Copyright 2005-2008 The Android Open Source Project + +This product includes software developed as part of +The Android Open Source Project (http://source.android.com). + + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for Apache Commons code. == + ========================================================================= + +Apache Commons +Copyright 1999-2006 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). + + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for Jakarta Commons Logging. == + ========================================================================= + +Jakarta Commons Logging (JCL) +Copyright 2005,2006 The Apache Software Foundation. + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). + + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for the Nuance code. == + ========================================================================= + +These files are Copyright 2007 Nuance Communications, but released under +the Apache2 License. + + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for the Media Codecs code. == + ========================================================================= + +Media Codecs +These files are Copyright 1998 - 2009 PacketVideo, but released under +the Apache2 License. + + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for the TagSoup code. == + ========================================================================= + +This file is part of TagSoup and is Copyright 2002-2008 by John Cowan. + +TagSoup is licensed under the Apache License, +Version 2.0. You may obtain a copy of this license at +http://www.apache.org/licenses/LICENSE-2.0 . You may also have +additional legal rights not granted by this license. + +TagSoup is distributed in the hope that it will be useful, but +unless required by applicable law or agreed to in writing, TagSoup +is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS +OF ANY KIND, either express or implied; not even the implied warranty +of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for Additional Codecs code. == + ========================================================================= + +Additional Codecs +These files are Copyright 2003-2010 VisualOn, but released under +the Apache2 License. + + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for the Audio Effects code. == + ========================================================================= + +Audio Effects +These files are Copyright (C) 2004-2010 NXP Software and +Copyright (C) 2010 The Android Open Source Project, but released under +the Apache2 License. + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + + +UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE + +Unicode Data Files include all data files under the directories +http://www.unicode.org/Public/, http://www.unicode.org/reports/, +and http://www.unicode.org/cldr/data/ . Unicode Software includes any +source code published in the Unicode Standard or under the directories +http://www.unicode.org/Public/, http://www.unicode.org/reports/, and +http://www.unicode.org/cldr/data/. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S DATA +FILES ("DATA FILES"), AND/OR SOFTWARE ("SOFTWARE"), YOU UNEQUIVOCALLY +ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE TERMS AND CONDITIONS OF +THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY, +DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 1991-2008 Unicode, Inc. All rights reserved. Distributed +under the Terms of Use in http://www.unicode.org/copyright.html. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Unicode data files and any associated documentation (the +"Data Files") or Unicode software and any associated documentation (the +"Software") to deal in the Data Files or Software without restriction, +including without limitation the rights to use, copy, modify, merge, +publish, distribute, and/or sell copies of the Data Files or Software, +and to permit persons to whom the Data Files or Software are furnished to +do so, provided that (a) the above copyright notice(s) and this permission +notice appear with all copies of the Data Files or Software, (b) both the +above copyright notice(s) and this permission notice appear in associated +documentation, and (c) there is clear notice in each modified Data File +or in the Software as well as in the documentation associated with the +Data File(s) or Software that the data or software has been modified. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS +INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT +OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE +OR PERFORMANCE OF THE DATA FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder +shall not be used in advertising or otherwise to promote the sale, use +or other dealings in these Data Files or Software without prior written +authorization of the copyright holder. +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 2016-2023 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in the +Data Files or Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, and/or sell +copies of the Data Files or Software, and to permit persons to whom the +Data Files or Software are furnished to do so, provided that either (a) +this copyright and permission notice appear with all copies of the Data +Files or Software, or (b) this copyright and permission notice appear in +associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. + +---------------------------------------------------------------------- + +Third-Party Software Licenses + +This section contains third-party software notices and/or additional +terms for licensed third-party software components included within ICU +libraries. + +---------------------------------------------------------------------- + +ICU License - ICU 1.8.1 to ICU 57.1 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright (c) 1995-2016 International Business Machines Corporation and others +All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, and/or sell copies of the Software, and to permit persons +to whom the Software is furnished to do so, provided that the above +copyright notice(s) and this permission notice appear in all copies of +the Software and that both the above copyright notice(s) and this +permission notice appear in supporting documentation. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY +SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER +RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF +CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +Except as contained in this notice, the name of a copyright holder +shall not be used in advertising or otherwise to promote the sale, use +or other dealings in this Software without prior written authorization +of the copyright holder. + +All trademarks and registered trademarks mentioned herein are the +property of their respective owners. + +---------------------------------------------------------------------- + +Chinese/Japanese Word Break Dictionary Data (cjdict.txt) + + # The Google Chrome software developed by Google is licensed under + # the BSD license. Other software included in this distribution is + # provided under other licenses, as set forth below. + # + # The BSD License + # http://opensource.org/licenses/bsd-license.php + # Copyright (C) 2006-2008, Google Inc. + # + # All rights reserved. + # + # Redistribution and use in source and binary forms, with or without + # modification, are permitted provided that the following conditions are met: + # + # Redistributions of source code must retain the above copyright notice, + # this list of conditions and the following disclaimer. + # Redistributions in binary form must reproduce the above + # copyright notice, this list of conditions and the following + # disclaimer in the documentation and/or other materials provided with + # the distribution. + # Neither the name of Google Inc. nor the names of its + # contributors may be used to endorse or promote products derived from + # this software without specific prior written permission. + # + # + # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND + # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + # BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + # + # + # The word list in cjdict.txt are generated by combining three word lists + # listed below with further processing for compound word breaking. The + # frequency is generated with an iterative training against Google web + # corpora. + # + # * Libtabe (Chinese) + # - https://sourceforge.net/project/?group_id=1519 + # - Its license terms and conditions are shown below. + # + # * IPADIC (Japanese) + # - http://chasen.aist-nara.ac.jp/chasen/distribution.html + # - Its license terms and conditions are shown below. + # + # ---------COPYING.libtabe ---- BEGIN-------------------- + # + # /* + # * Copyright (c) 1999 TaBE Project. + # * Copyright (c) 1999 Pai-Hsiang Hsiao. + # * All rights reserved. + # * + # * Redistribution and use in source and binary forms, with or without + # * modification, are permitted provided that the following conditions + # * are met: + # * + # * . Redistributions of source code must retain the above copyright + # * notice, this list of conditions and the following disclaimer. + # * . Redistributions in binary form must reproduce the above copyright + # * notice, this list of conditions and the following disclaimer in + # * the documentation and/or other materials provided with the + # * distribution. + # * . Neither the name of the TaBE Project nor the names of its + # * contributors may be used to endorse or promote products derived + # * from this software without specific prior written permission. + # * + # * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + # * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + # * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + # * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + # * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + # * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + # * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + # * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + # * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + # * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + # * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + # * OF THE POSSIBILITY OF SUCH DAMAGE. + # */ + # + # /* + # * Copyright (c) 1999 Computer Systems and Communication Lab, + # * Institute of Information Science, Academia + # * Sinica. All rights reserved. + # * + # * Redistribution and use in source and binary forms, with or without + # * modification, are permitted provided that the following conditions + # * are met: + # * + # * . Redistributions of source code must retain the above copyright + # * notice, this list of conditions and the following disclaimer. + # * . Redistributions in binary form must reproduce the above copyright + # * notice, this list of conditions and the following disclaimer in + # * the documentation and/or other materials provided with the + # * distribution. + # * . Neither the name of the Computer Systems and Communication Lab + # * nor the names of its contributors may be used to endorse or + # * promote products derived from this software without specific + # * prior written permission. + # * + # * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + # * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + # * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + # * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + # * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + # * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + # * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + # * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + # * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + # * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + # * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + # * OF THE POSSIBILITY OF SUCH DAMAGE. + # */ + # + # Copyright 1996 Chih-Hao Tsai @ Beckman Institute, + # University of Illinois + # c-tsai4@uiuc.edu http://casper.beckman.uiuc.edu/~c-tsai4 + # + # ---------------COPYING.libtabe-----END-------------------------------- + # + # + # ---------------COPYING.ipadic-----BEGIN------------------------------- + # + # Copyright 2000, 2001, 2002, 2003 Nara Institute of Science + # and Technology. All Rights Reserved. + # + # Use, reproduction, and distribution of this software is permitted. + # Any copy of this software, whether in its original form or modified, + # must include both the above copyright notice and the following + # paragraphs. + # + # Nara Institute of Science and Technology (NAIST), + # the copyright holders, disclaims all warranties with regard to this + # software, including all implied warranties of merchantability and + # fitness, in no event shall NAIST be liable for + # any special, indirect or consequential damages or any damages + # whatsoever resulting from loss of use, data or profits, whether in an + # action of contract, negligence or other tortuous action, arising out + # of or in connection with the use or performance of this software. + # + # A large portion of the dictionary entries + # originate from ICOT Free Software. The following conditions for ICOT + # Free Software applies to the current dictionary as well. + # + # Each User may also freely distribute the Program, whether in its + # original form or modified, to any third party or parties, PROVIDED + # that the provisions of Section 3 ("NO WARRANTY") will ALWAYS appear + # on, or be attached to, the Program, which is distributed substantially + # in the same form as set out herein and that such intended + # distribution, if actually made, will neither violate or otherwise + # contravene any of the laws and regulations of the countries having + # jurisdiction over the User or the intended distribution itself. + # + # NO WARRANTY + # + # The program was produced on an experimental basis in the course of the + # research and development conducted during the project and is provided + # to users as so produced on an experimental basis. Accordingly, the + # program is provided without any warranty whatsoever, whether express, + # implied, statutory or otherwise. The term "warranty" used herein + # includes, but is not limited to, any warranty of the quality, + # performance, merchantability and fitness for a particular purpose of + # the program and the nonexistence of any infringement or violation of + # any right of any third party. + # + # Each user of the program will agree and understand, and be deemed to + # have agreed and understood, that there is no warranty whatsoever for + # the program and, accordingly, the entire risk arising from or + # otherwise connected with the program is assumed by the user. + # + # Therefore, neither ICOT, the copyright holder, or any other + # organization that participated in or was otherwise related to the + # development of the program and their respective officials, directors, + # officers and other employees shall be held liable for any and all + # damages, including, without limitation, general, special, incidental + # and consequential damages, arising out of or otherwise in connection + # with the use or inability to use the program or any product, material + # or result produced or otherwise obtained by using the program, + # regardless of whether they have been advised of, or otherwise had + # knowledge of, the possibility of such damages at any time during the + # project or thereafter. Each user will be deemed to have agreed to the + # foregoing by his or her commencement of use of the program. The term + # "use" as used herein includes, but is not limited to, the use, + # modification, copying and distribution of the program and the + # production of secondary products from the program. + # + # In the case where the program, whether in its original form or + # modified, was distributed or delivered to or received by a user from + # any person, organization or entity other than ICOT, unless it makes or + # grants independently of ICOT any specific warranty to the user in + # writing, such person, organization or entity, will also be exempted + # from and not be held liable to the user for any such damages as noted + # above as far as the program is concerned. + # + # ---------------COPYING.ipadic-----END---------------------------------- + +---------------------------------------------------------------------- + +Lao Word Break Dictionary Data (laodict.txt) + + # Copyright (C) 2016 and later: Unicode, Inc. and others. + # License & terms of use: http://www.unicode.org/copyright.html + # Copyright (c) 2015 International Business Machines Corporation + # and others. All Rights Reserved. + # + # Project: https://github.com/rober42539/lao-dictionary + # Dictionary: https://github.com/rober42539/lao-dictionary/laodict.txt + # License: https://github.com/rober42539/lao-dictionary/LICENSE.txt + # (copied below) + # + # This file is derived from the above dictionary version of Nov 22, 2020 + # ---------------------------------------------------------------------- + # Copyright (C) 2013 Brian Eugene Wilson, Robert Martin Campbell. + # All rights reserved. + # + # Redistribution and use in source and binary forms, with or without + # modification, are permitted provided that the following conditions are met: + # + # Redistributions of source code must retain the above copyright notice, this + # list of conditions and the following disclaimer. Redistributions in binary + # form must reproduce the above copyright notice, this list of conditions and + # the following disclaimer in the documentation and/or other materials + # provided with the distribution. + # + # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + # OF THE POSSIBILITY OF SUCH DAMAGE. + # -------------------------------------------------------------------------- + +---------------------------------------------------------------------- + +Burmese Word Break Dictionary Data (burmesedict.txt) + + # Copyright (c) 2014 International Business Machines Corporation + # and others. All Rights Reserved. + # + # This list is part of a project hosted at: + # github.com/kanyawtech/myanmar-karen-word-lists + # + # -------------------------------------------------------------------------- + # Copyright (c) 2013, LeRoy Benjamin Sharon + # All rights reserved. + # + # Redistribution and use in source and binary forms, with or without + # modification, are permitted provided that the following conditions + # are met: Redistributions of source code must retain the above + # copyright notice, this list of conditions and the following + # disclaimer. Redistributions in binary form must reproduce the + # above copyright notice, this list of conditions and the following + # disclaimer in the documentation and/or other materials provided + # with the distribution. + # + # Neither the name Myanmar Karen Word Lists, nor the names of its + # contributors may be used to endorse or promote products derived + # from this software without specific prior written permission. + # + # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND + # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS + # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + # TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + # THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + # SUCH DAMAGE. + # -------------------------------------------------------------------------- + +---------------------------------------------------------------------- + +Time Zone Database + + ICU uses the public domain data and code derived from Time Zone +Database for its time zone support. The ownership of the TZ database +is explained in BCP 175: Procedure for Maintaining the Time Zone +Database section 7. + + # 7. Database Ownership + # + # The TZ database itself is not an IETF Contribution or an IETF + # document. Rather it is a pre-existing and regularly updated work + # that is in the public domain, and is intended to remain in the + # public domain. Therefore, BCPs 78 [RFC5378] and 79 [RFC3979] do + # not apply to the TZ Database or contributions that individuals make + # to it. Should any claims be made and substantiated against the TZ + # Database, the organization that is providing the IANA + # Considerations defined in this RFC, under the memorandum of + # understanding with the IETF, currently ICANN, may act in accordance + # with all competent court orders. No ownership claims will be made + # by ICANN or the IETF Trust on the database or the code. Any person + # making a contribution to the database or code waives all rights to + # future claims in that contribution or in the TZ Database. + +---------------------------------------------------------------------- + +Google double-conversion + +Copyright 2006-2011, the V8 project authors. All rights reserved. +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of Google Inc. nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +---------------------------------------------------------------------- + +File: aclocal.m4 (only for ICU4C) +Section: pkg.m4 - Macros to locate and utilise pkg-config. + + +Copyright © 2004 Scott James Remnant . +Copyright © 2012-2015 Dan Nicholson + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 2 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +02111-1307, USA. + +As a special exception to the GNU General Public License, if you +distribute this file as part of a program that contains a +configuration script generated by Autoconf, you may include it under +the same distribution terms that you use for the rest of that +program. + + +(The condition for the exception is fulfilled because +ICU4C includes a configuration script generated by Autoconf, +namely the `configure` script.) + +---------------------------------------------------------------------- + +File: config.guess (only for ICU4C) + + +This file is free software; you can redistribute it and/or modify it +under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, see . + +As a special exception to the GNU General Public License, if you +distribute this file as part of a program that contains a +configuration script generated by Autoconf, you may include it under +the same distribution terms that you use for the rest of that +program. This Exception is an additional permission under section 7 +of the GNU General Public License, version 3 ("GPLv3"). + + +(The condition for the exception is fulfilled because +ICU4C includes a configuration script generated by Autoconf, +namely the `configure` script.) + +---------------------------------------------------------------------- + +File: install-sh (only for ICU4C) + + +Copyright 1991 by the Massachusetts Institute of Technology + +Permission to use, copy, modify, distribute, and sell this software and its +documentation for any purpose is hereby granted without fee, provided that +the above copyright notice appear in all copies and that both that +copyright notice and this permission notice appear in supporting +documentation, and that the name of M.I.T. not be used in advertising or +publicity pertaining to distribution of the software without specific, +written prior permission. M.I.T. makes no representations about the +suitability of this software for any purpose. It is provided "as is" +without express or implied warranty. + +---------------------------------------------------------------------- + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2024 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + Copyright (c) 2005-2014, The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for the Android-specific code. == + ========================================================================= + +Android Code +Copyright 2005-2008 The Android Open Source Project + +This product includes software developed as part of +The Android Open Source Project (http://source.android.com). + + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for Apache Commons code. == + ========================================================================= + +Apache Commons +Copyright 1999-2006 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). + + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for Jakarta Commons Logging. == + ========================================================================= + +Jakarta Commons Logging (JCL) +Copyright 2005,2006 The Apache Software Foundation. + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). + + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for the Nuance code. == + ========================================================================= + +These files are Copyright 2007 Nuance Communications, but released under +the Apache2 License. + + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for the Media Codecs code. == + ========================================================================= + +Media Codecs +These files are Copyright 1998 - 2009 PacketVideo, but released under +the Apache2 License. + + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for the TagSoup code. == + ========================================================================= + +This file is part of TagSoup and is Copyright 2002-2008 by John Cowan. + +TagSoup is licensed under the Apache License, +Version 2.0. You may obtain a copy of this license at +http://www.apache.org/licenses/LICENSE-2.0 . You may also have +additional legal rights not granted by this license. + +TagSoup is distributed in the hope that it will be useful, but +unless required by applicable law or agreed to in writing, TagSoup +is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS +OF ANY KIND, either express or implied; not even the implied warranty +of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for Additional Codecs code. == + ========================================================================= + +Additional Codecs +These files are Copyright 2003-2010 VisualOn, but released under +the Apache2 License. + + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for the Audio Effects code. == + ========================================================================= + +Audio Effects +These files are Copyright (C) 2004-2010 NXP Software and +Copyright (C) 2010 The Android Open Source Project, but released under +the Apache2 License. + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + + +UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE + +Unicode Data Files include all data files under the directories +http://www.unicode.org/Public/, http://www.unicode.org/reports/, +and http://www.unicode.org/cldr/data/ . Unicode Software includes any +source code published in the Unicode Standard or under the directories +http://www.unicode.org/Public/, http://www.unicode.org/reports/, and +http://www.unicode.org/cldr/data/. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S DATA +FILES ("DATA FILES"), AND/OR SOFTWARE ("SOFTWARE"), YOU UNEQUIVOCALLY +ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE TERMS AND CONDITIONS OF +THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY, +DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 1991-2008 Unicode, Inc. All rights reserved. Distributed +under the Terms of Use in http://www.unicode.org/copyright.html. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Unicode data files and any associated documentation (the +"Data Files") or Unicode software and any associated documentation (the +"Software") to deal in the Data Files or Software without restriction, +including without limitation the rights to use, copy, modify, merge, +publish, distribute, and/or sell copies of the Data Files or Software, +and to permit persons to whom the Data Files or Software are furnished to +do so, provided that (a) the above copyright notice(s) and this permission +notice appear with all copies of the Data Files or Software, (b) both the +above copyright notice(s) and this permission notice appear in associated +documentation, and (c) there is clear notice in each modified Data File +or in the Software as well as in the documentation associated with the +Data File(s) or Software that the data or software has been modified. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS +INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT +OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE +OR PERFORMANCE OF THE DATA FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder +shall not be used in advertising or otherwise to promote the sale, use +or other dealings in these Data Files or Software without prior written +authorization of the copyright holder. + + Copyright (c) 2005-2008, The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + + Copyright (c) 2005-2008, The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright (c) 2017, The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + +------------------------------------------------------------------- +* License for Tensorflow: +------------------------------------------------------------------- +Copyright 2018 The TensorFlow Authors. All rights reserved. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2017, The TensorFlow Authors. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ------------------------------------------------------------------- + +------------------------------------------------------------------- +* License for Eigen: +------------------------------------------------------------------- +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. + + +------------------------------------------------------------------- +* License for Caffe2 (Some ops are derived from caffe2) +------------------------------------------------------------------- + +Copyright (c) 2016-present, Facebook Inc. All rights reserved. + +All contributions by Facebook: +Copyright (c) 2016 Facebook Inc. + +All contributions by Google: +Copyright (c) 2015 Google Inc. +All rights reserved. + +All contributions by Yangqing Jia: +Copyright (c) 2015 Yangqing Jia +All rights reserved. + +All contributions from Caffe: +Copyright(c) 2013, 2014, 2015, the respective contributors +All rights reserved. + +All other contributions: +Copyright(c) 2015, 2016 the respective contributors +All rights reserved. + +Caffe2 uses a copyright model similar to Caffe: each contributor holds +copyright over their contributions to Caffe2. The project versioning records +all such contribution and copyright details. If a contributor wants to further +mark their specific copyright on a particular contribution, they should +indicate their copyright solely in the commit message of the change when it is +committed. + +======================================================================= +Software under third_party +======================================================================= +Software libraries under third_party are provided as github submodule +links, and their content is not part of the Caffe2 codebase. Their +licences can be found under the respective software repositories. + +======================================================================= +Earlier BSD License +======================================================================= +Early development of Caffe2 in 2015 and early 2016 is licensed under the +BSD license. The license is attached below: + +All contributions by Facebook: +Copyright (c) 2016 Facebook Inc. + +All contributions by Google: +Copyright (c) 2015 Google Inc. +All rights reserved. + +All contributions by Yangqing Jia: +Copyright (c) 2015 Yangqing Jia +All rights reserved. + +All other contributions: +Copyright(c) 2015, 2016 the respective contributors +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +======================================================================= +Caffe's BSD License +======================================================================= +Some parts of the caffe2 code is derived from the original Caffe code, which is +created by Yangqing Jia and is now a BSD-licensed open-source project. The Caffe +license is as follows: + +COPYRIGHT + +All contributions by the University of California: +Copyright (c) 2014, The Regents of the University of California (Regents) +All rights reserved. + +All other contributions: +Copyright (c) 2014, the respective contributors +All rights reserved. + +Caffe uses a shared copyright model: each contributor holds copyright over +their contributions to Caffe. The project versioning records all such +contribution and copyright details. If a contributor wants to further mark +their specific copyright on a particular contribution, they should indicate +their copyright solely in the commit message of the change when it is +committed. + +LICENSE + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +CONTRIBUTION AGREEMENT + +By contributing to the BVLC/caffe repository through pull-request, comment, +or otherwise, the contributor releases their content to the +license and copyright terms herein. + + +------------------------------------------------------------------- +* License for gemmlowp & libtextclassifier +------------------------------------------------------------------- + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + Copyright (c) 2012-2017, The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + +version 1.2.12, March 27th, 2022 + +Copyright (C) 1995-2022 Jean-loup Gailly and Mark Adler + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +Copyright (c) 2015-2018 The Khronos Group Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and/or associated documentation files (the +"Materials"), to deal in the Materials without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Materials, and to +permit persons to whom the Materials are furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Materials. + +MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS +KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS +SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT + https://www.khronos.org/registry/ + +THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + +Here, glslang proper means core GLSL parsing, HLSL parsing, and SPIR-V code +generation. Glslang proper requires use of a number of licenses, one that covers +preprocessing and others that covers non-preprocessing. + +Bison was removed long ago. You can build glslang from the source grammar, +using tools of your choice, without using bison or any bison files. + +Other parts, outside of glslang proper, include: + +- gl_types.h, only needed for OpenGL-like reflection, and can be left out of + a parse and codegen project. See it for its license. + +- update_glslang_sources.py, which is not part of the project proper and does + not need to be used. + +- the SPIR-V "remapper", which is optional, but has the same license as + glslang proper + +- Google tests and SPIR-V tools, and anything in the external subdirectory + are external and optional; see them for their respective licenses. + +-------------------------------------------------------------------------------- + +The core of glslang-proper, minus the preprocessor is licenced as follows: + +-------------------------------------------------------------------------------- +3-Clause BSD License +-------------------------------------------------------------------------------- + +// +// Copyright (C) 2015-2018 Google, Inc. +// Copyright (C) +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// +// Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// +// Neither the name of 3Dlabs Inc. Ltd. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// + + +-------------------------------------------------------------------------------- +2-Clause BSD License +-------------------------------------------------------------------------------- + +Copyright 2020 The Khronos Group Inc + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +-------------------------------------------------------------------------------- +The MIT License +-------------------------------------------------------------------------------- + +Copyright 2020 The Khronos Group Inc + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +-------------------------------------------------------------------------------- +APACHE LICENSE, VERSION 2.0 +-------------------------------------------------------------------------------- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +-------------------------------------------------------------------------------- +GPL 3 with special bison exception +-------------------------------------------------------------------------------- + + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + +Bison Exception + +As a special exception, you may create a larger work that contains part or all +of the Bison parser skeleton and distribute that work under terms of your +choice, so long as that work isn't itself a parser generator using the skeleton +or a modified version thereof as a parser skeleton. Alternatively, if you +modify or redistribute the parser skeleton itself, you may (at your option) +remove this special exception, which will cause the skeleton and the resulting +Bison output files to be licensed under the GNU General Public License without +this special exception. + +This special exception was added by the Free Software Foundation in version +2.2 of Bison. + + END OF TERMS AND CONDITIONS + +-------------------------------------------------------------------------------- +================================================================================ +-------------------------------------------------------------------------------- + +The preprocessor has the core licenses stated above, plus additional licences: + +/****************************************************************************\ +Copyright (c) 2002, NVIDIA Corporation. + +NVIDIA Corporation("NVIDIA") supplies this software to you in +consideration of your agreement to the following terms, and your use, +installation, modification or redistribution of this NVIDIA software +constitutes acceptance of these terms. If you do not agree with these +terms, please do not use, install, modify or redistribute this NVIDIA +software. + +In consideration of your agreement to abide by the following terms, and +subject to these terms, NVIDIA grants you a personal, non-exclusive +license, under NVIDIA's copyrights in this original NVIDIA software (the +"NVIDIA Software"), to use, reproduce, modify and redistribute the +NVIDIA Software, with or without modifications, in source and/or binary +forms; provided that if you redistribute the NVIDIA Software, you must +retain the copyright notice of NVIDIA, this notice and the following +text and disclaimers in all such redistributions of the NVIDIA Software. +Neither the name, trademarks, service marks nor logos of NVIDIA +Corporation may be used to endorse or promote products derived from the +NVIDIA Software without specific prior written permission from NVIDIA. +Except as expressly stated in this notice, no other rights or licenses +express or implied, are granted by NVIDIA herein, including but not +limited to any patent rights that may be infringed by your derivative +works or by other works in which the NVIDIA Software may be +incorporated. No hardware is licensed hereunder. + +THE NVIDIA SOFTWARE IS BEING PROVIDED ON AN "AS IS" BASIS, WITHOUT +WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, +INCLUDING WITHOUT LIMITATION, WARRANTIES OR CONDITIONS OF TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR +ITS USE AND OPERATION EITHER ALONE OR IN COMBINATION WITH OTHER +PRODUCTS. + +IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT, +INCIDENTAL, EXEMPLARY, CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, LOST PROFITS; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF +USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) OR ARISING IN ANY WAY +OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE +NVIDIA SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, +TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF +NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +\****************************************************************************/ + +/* +** Copyright (c) 2014-2016 The Khronos Group Inc. +** +** Permission is hereby granted, free of charge, to any person obtaining a copy +** of this software and/or associated documentation files (the "Materials"), +** to deal in the Materials without restriction, including without limitation +** the rights to use, copy, modify, merge, publish, distribute, sublicense, +** and/or sell copies of the Materials, and to permit persons to whom the +** Materials are furnished to do so, subject to the following conditions: +** +** The above copyright notice and this permission notice shall be included in +** all copies or substantial portions of the Materials. +** +** MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS +** STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND +** HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/ +** +** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +** OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +** THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +** FROM,OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS +** IN THE MATERIALS. +*/ + +Note: The license for SPIRV-Tools changed to Apache 2.0 via this commit: +https://github.com/KhronosGroup/SPIRV-Tools/commit/9fc8658ef301b0f03b2173d274c52f011b5c73e5 + + +// Copyright (c) 2015-2016 The Khronos Group Inc. +// Copyright (c) 2015-2016 Google Inc. +// Copyright (c) 2016 LunarG Inc. + + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND OTHER CONTRIBUTORS ``AS IS'' +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR OTHER CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +------------------------------------------------------------------------------- +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the author nor the names of other contributors + may be used to endorse or promote products derived from this + software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND OTHER CONTRIBUTORS ``AS IS'' +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR OTHER CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. +------------------------------------------------------------------------------- +NASM is now licensed under the 2-clause BSD license, also known as the +simplified BSD license. + + Copyright 1996-2009 the NASM Authors - All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following + conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND + CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Yasm is Copyright (c) 2001-2014 Peter Johnson and other Yasm developers. + +Yasm developers and/or contributors include: + Peter Johnson + Michael Urman + Brian Gladman (Visual Studio build files, other fixes) + Stanislav Karchebny (options parser) + Mathieu Monnier (SSE4 instruction patches, NASM preprocessor additions) + Anonymous "NASM64" developer (NASM preprocessor fixes) + Stephen Polkowski (x86 instruction patches) + Henryk Richter (Mach-O object format) + Ben Skeggs (patches, bug reports) + Alexei Svitkine (GAS preprocessor) + Samuel Thibault (TASM parser and frontend) + +----------------------------------- +Yasm licensing overview and summary +----------------------------------- + +Note: This document does not provide legal advice nor is it the actual +license of any part of Yasm. See the individual licenses for complete +details. Consult a lawyer for legal advice. + +The primary license of Yasm is the 2-clause BSD license. Please use this +license if you plan on submitting code to the project. + +Yasm has absolutely no warranty; not even for merchantibility or fitness +for a particular purpose. + +------- +Libyasm +------- +Libyasm is 2-clause or 3-clause BSD licensed, with the exception of +bitvect, which is triple-licensed under the Artistic license, GPL, and +LGPL. Libyasm is thus GPL and LGPL compatible. In addition, this also +means that libyasm is free for binary-only distribution as long as the +terms of the 3-clause BSD license and Artistic license (as it applies to +bitvect) are fulfilled. + +------- +Modules +------- +The modules are 2-clause or 3-clause BSD licensed. + +--------- +Frontends +--------- +The frontends are 2-clause BSD licensed. + +------------- +License Texts +------------- +The full text of all licenses are provided in separate files in the source +distribution. Each source file may include the entire license (in the case +of the BSD and Artistic licenses), or may reference the GPL or LGPL license +file. + +BSD.txt - 2-clause and 3-clause BSD licenses +Artistic.txt - Artistic license +GNU_GPL-2.0 - GNU General Public License +GNU_LGPL-2.0 - GNU Library General Public License diff --git a/third_party/exo-dv5-native/prebuilt/arm64-v8a/libdovi.a b/third_party/exo-dv5-native/prebuilt/arm64-v8a/libdovi.a new file mode 100644 index 0000000000..ed8f0cd3e7 Binary files /dev/null and b/third_party/exo-dv5-native/prebuilt/arm64-v8a/libdovi.a differ diff --git a/third_party/exo-dv5-native/prebuilt/arm64-v8a/libplacebo.a b/third_party/exo-dv5-native/prebuilt/arm64-v8a/libplacebo.a new file mode 100644 index 0000000000..655b6fb11b Binary files /dev/null and b/third_party/exo-dv5-native/prebuilt/arm64-v8a/libplacebo.a differ diff --git a/third_party/exo-dv5-native/prebuilt/arm64-v8a/libshaderc.a b/third_party/exo-dv5-native/prebuilt/arm64-v8a/libshaderc.a new file mode 100644 index 0000000000..e32ba7b494 Binary files /dev/null and b/third_party/exo-dv5-native/prebuilt/arm64-v8a/libshaderc.a differ diff --git a/third_party/exo-dv5-native/prebuilt/armeabi-v7a/libdovi.a b/third_party/exo-dv5-native/prebuilt/armeabi-v7a/libdovi.a new file mode 100644 index 0000000000..e774eeb2e6 Binary files /dev/null and b/third_party/exo-dv5-native/prebuilt/armeabi-v7a/libdovi.a differ diff --git a/third_party/exo-dv5-native/prebuilt/armeabi-v7a/libplacebo.a b/third_party/exo-dv5-native/prebuilt/armeabi-v7a/libplacebo.a new file mode 100644 index 0000000000..291595406c Binary files /dev/null and b/third_party/exo-dv5-native/prebuilt/armeabi-v7a/libplacebo.a differ diff --git a/third_party/exo-dv5-native/prebuilt/armeabi-v7a/libshaderc.a b/third_party/exo-dv5-native/prebuilt/armeabi-v7a/libshaderc.a new file mode 100644 index 0000000000..ad24abeb53 Binary files /dev/null and b/third_party/exo-dv5-native/prebuilt/armeabi-v7a/libshaderc.a differ diff --git a/third_party/fongmi-repositories-lock.json b/third_party/fongmi-repositories-lock.json index 89d5e41868..623a56c5cc 100644 --- a/third_party/fongmi-repositories-lock.json +++ b/third_party/fongmi-repositories-lock.json @@ -41,7 +41,7 @@ "ffmpeg": { "repo": "https://github.com/FongMi/FFmpeg.git", "selected_branch": "release-9.0-fongmi", - "selected_commit": "04482c8d13ac27b2a9fe93f5d388929eef8af5f4", + "selected_commit": "177f090e0503b7e013922ca903bde14b1c375f18", "default_branch": "master", "default_commit": "f947bc9c1532e7bcc95da11d9574cac3543490b3", "usage": "MPV native stack; mirrored by third_party/mpv-native-lock.json" diff --git a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi-sources.jar b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi-sources.jar index db1778069e..8b6f88aa3b 100644 Binary files a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi-sources.jar and b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi-sources.jar differ diff --git a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi-sources.jar.md5 b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi-sources.jar.md5 index a84b8958ef..9ed36fe826 100644 --- a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi-sources.jar.md5 +++ b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi-sources.jar.md5 @@ -1 +1 @@ -7e337848d01786a74c5fa614ae893ce1 \ No newline at end of file +78e3a5ef59878ba5d16fe230581327b2 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi-sources.jar.sha1 b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi-sources.jar.sha1 index a01b7a9001..ea40127a16 100644 --- a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi-sources.jar.sha1 +++ b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi-sources.jar.sha1 @@ -1 +1 @@ -56cc2cbd470501a89514a9ce45145d35e49a9c5d \ No newline at end of file +1e7aa72657bb5c99b0f75d03674d32044b8239cd \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi-sources.jar.sha256 b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi-sources.jar.sha256 index a16331aef2..aa8622366c 100644 --- a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi-sources.jar.sha256 +++ b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi-sources.jar.sha256 @@ -1 +1 @@ -e804d5738f0aa01c302da0a409ac5e671373a4d600f699da82ba0f96f30a82b3 \ No newline at end of file +31c38835a729f422ba25835733aa94ac23d8fe6445df2d725a71e46a11d86bfc \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi-sources.jar.sha512 b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi-sources.jar.sha512 index 4716abb5e0..42b3937ac2 100644 --- a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi-sources.jar.sha512 +++ b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi-sources.jar.sha512 @@ -1 +1 @@ -a471274690ed3320a17e97a1cd0e149ab0c8ae89ff8656cccad012b4584aa4666a2f00168d46faf93c50b3e03a96b576e31590d32ebc01d6768c24c54ec3fc6b \ No newline at end of file +745d8f304af5d44c21b084e365f354dd25bcf23af65b14d079610651650ddab0489fecc9c72ef8633aecff71839fa5fb7944d8fd4527ac3c63e30d2c2951aa0f \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.aar b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.aar index a422226372..c4b8934768 100644 Binary files a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.aar and b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.aar differ diff --git a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.aar.md5 b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.aar.md5 index a886f0eecc..203fe3c6e4 100644 --- a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.aar.md5 +++ b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.aar.md5 @@ -1 +1 @@ -84972610c112e067654a699bb2658415 \ No newline at end of file +790b1e8cd57a82b0a648a3feba5cf700 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.aar.sha1 b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.aar.sha1 index 136c0a2fce..68b837f363 100644 --- a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.aar.sha1 +++ b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.aar.sha1 @@ -1 +1 @@ -2f5ee41bba9b2a5f88791ffb7a2aa991d4ac25e5 \ No newline at end of file +cbf650d7141d66da74e9298917753cb672af68e8 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.aar.sha256 b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.aar.sha256 index 68f111a3d7..74d8bbf8cb 100644 --- a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.aar.sha256 +++ b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.aar.sha256 @@ -1 +1 @@ -edb69a279767791058e95f89b707b2e387c276d15edec0af995696ae0e033c13 \ No newline at end of file +5a4815ab415c0650bc8adaa60e518f32df548ddcfafb43e02381281a96dac6e5 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.aar.sha512 b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.aar.sha512 index 7511f9c936..b30215a1ff 100644 --- a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.aar.sha512 +++ b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.aar.sha512 @@ -1 +1 @@ -b28305349c13c55e99c3657924338a6c2a111e0861b2b1e97de62a9f138c1f246bafdff885a762806325b224233a1bec7d54557bbb50105a493bf3d9d5c91618 \ No newline at end of file +26933fe234b641c5538f8fc368ca442b4c46a616769f042b0d87d449c3518389b277e97fc032029a326c678cc62f75346a2ad6007e74fae9675426b0217ebc1d \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.module b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.module index 436e6f2054..5c85a6b1c0 100644 --- a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.module +++ b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.module @@ -68,11 +68,11 @@ { "name": "media3-common-1.11.0-alpha01-fongmi.aar", "url": "media3-common-1.11.0-alpha01-fongmi.aar", - "size": 653976, - "sha512": "b28305349c13c55e99c3657924338a6c2a111e0861b2b1e97de62a9f138c1f246bafdff885a762806325b224233a1bec7d54557bbb50105a493bf3d9d5c91618", - "sha256": "edb69a279767791058e95f89b707b2e387c276d15edec0af995696ae0e033c13", - "sha1": "2f5ee41bba9b2a5f88791ffb7a2aa991d4ac25e5", - "md5": "84972610c112e067654a699bb2658415" + "size": 656215, + "sha512": "26933fe234b641c5538f8fc368ca442b4c46a616769f042b0d87d449c3518389b277e97fc032029a326c678cc62f75346a2ad6007e74fae9675426b0217ebc1d", + "sha256": "5a4815ab415c0650bc8adaa60e518f32df548ddcfafb43e02381281a96dac6e5", + "sha1": "cbf650d7141d66da74e9298917753cb672af68e8", + "md5": "790b1e8cd57a82b0a648a3feba5cf700" } ] }, @@ -433,11 +433,11 @@ { "name": "media3-common-1.11.0-alpha01-fongmi.aar", "url": "media3-common-1.11.0-alpha01-fongmi.aar", - "size": 653976, - "sha512": "b28305349c13c55e99c3657924338a6c2a111e0861b2b1e97de62a9f138c1f246bafdff885a762806325b224233a1bec7d54557bbb50105a493bf3d9d5c91618", - "sha256": "edb69a279767791058e95f89b707b2e387c276d15edec0af995696ae0e033c13", - "sha1": "2f5ee41bba9b2a5f88791ffb7a2aa991d4ac25e5", - "md5": "84972610c112e067654a699bb2658415" + "size": 656215, + "sha512": "26933fe234b641c5538f8fc368ca442b4c46a616769f042b0d87d449c3518389b277e97fc032029a326c678cc62f75346a2ad6007e74fae9675426b0217ebc1d", + "sha256": "5a4815ab415c0650bc8adaa60e518f32df548ddcfafb43e02381281a96dac6e5", + "sha1": "cbf650d7141d66da74e9298917753cb672af68e8", + "md5": "790b1e8cd57a82b0a648a3feba5cf700" } ] }, @@ -453,11 +453,11 @@ { "name": "media3-common-1.11.0-alpha01-fongmi-sources.jar", "url": "media3-common-1.11.0-alpha01-fongmi-sources.jar", - "size": 532590, - "sha512": "a471274690ed3320a17e97a1cd0e149ab0c8ae89ff8656cccad012b4584aa4666a2f00168d46faf93c50b3e03a96b576e31590d32ebc01d6768c24c54ec3fc6b", - "sha256": "e804d5738f0aa01c302da0a409ac5e671373a4d600f699da82ba0f96f30a82b3", - "sha1": "56cc2cbd470501a89514a9ce45145d35e49a9c5d", - "md5": "7e337848d01786a74c5fa614ae893ce1" + "size": 534370, + "sha512": "745d8f304af5d44c21b084e365f354dd25bcf23af65b14d079610651650ddab0489fecc9c72ef8633aecff71839fa5fb7944d8fd4527ac3c63e30d2c2951aa0f", + "sha256": "31c38835a729f422ba25835733aa94ac23d8fe6445df2d725a71e46a11d86bfc", + "sha1": "1e7aa72657bb5c99b0f75d03674d32044b8239cd", + "md5": "78e3a5ef59878ba5d16fe230581327b2" } ] } diff --git a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.module.md5 b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.module.md5 index 133c6efec5..0854a5e128 100644 --- a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.module.md5 +++ b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.module.md5 @@ -1 +1 @@ -7abbd422ee282a473a65b7cc4150e831 \ No newline at end of file +2ca0e4395eee071f6c062595e716a5f1 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.module.sha1 b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.module.sha1 index 39b3abe68f..916f202dea 100644 --- a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.module.sha1 +++ b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.module.sha1 @@ -1 +1 @@ -429199469101da0cfc3f0861a6f3f407ac7968ae \ No newline at end of file +8ad9703ed5014ca3e86dd5c643a1c7140bbb151f \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.module.sha256 b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.module.sha256 index e4815a5fe5..a1ff101079 100644 --- a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.module.sha256 +++ b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.module.sha256 @@ -1 +1 @@ -82c4df657bd40382a929b64be64da1d66a3a71945dd9551116132ad5a1b327d9 \ No newline at end of file +e1bc887749ab6b69b1f8d5b56a129f5e2d6618f31ebe3db2a841b352b9f24c87 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.module.sha512 b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.module.sha512 index 0d552a0706..6894a8c546 100644 --- a/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.module.sha512 +++ b/third_party/maven/androidx/media3/media3-common/1.11.0-alpha01-fongmi/media3-common-1.11.0-alpha01-fongmi.module.sha512 @@ -1 +1 @@ -c2e4d8a4684cc5f069a7fcc34926a1f05eac59568330a2007b5c1aeaa1970ceef36dd36c4bd2c42255394e3ffe721af0a4cf87956bec9d5fa11aec7e7e3015db \ No newline at end of file +e6e11d1351c614a3d63dd9a900dbc85acb11deaa1e74610a2e0328f5f007478ac8744382a97762e46466c95b2a0c6ba8ae4f93ff1b3a1fc7d2229f8bbfd53927 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi-sources.jar b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi-sources.jar index 20707c3b9b..656987109a 100644 Binary files a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi-sources.jar and b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi-sources.jar differ diff --git a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi-sources.jar.md5 b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi-sources.jar.md5 index fa2f20aff1..6a56a32bd2 100644 --- a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi-sources.jar.md5 +++ b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi-sources.jar.md5 @@ -1 +1 @@ -69d4b0f429e82ce10175949bbbccad6d \ No newline at end of file +7ab9bb46dba7720c3571ae51af85760a \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi-sources.jar.sha1 b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi-sources.jar.sha1 index 747f809ea5..7c551e8775 100644 --- a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi-sources.jar.sha1 +++ b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi-sources.jar.sha1 @@ -1 +1 @@ -3e37f3e1dd1f2998b51802e43fb962dfcb2baed3 \ No newline at end of file +17a911e6516ee5057eeab7f8a24eab1dcbbe2ac1 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi-sources.jar.sha256 b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi-sources.jar.sha256 index 7122f0e587..d5bd0c74cd 100644 --- a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi-sources.jar.sha256 +++ b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi-sources.jar.sha256 @@ -1 +1 @@ -1389b973146391c7eb6cfb80d389cfb70f291a6fc092e1628af1886a6e00294c \ No newline at end of file +9aee6336465f59a29efcadd5c72b26fd8cdaa3ee4ee88a74ad99de003ddc43b6 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi-sources.jar.sha512 b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi-sources.jar.sha512 index 222262723f..661322f8e2 100644 --- a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi-sources.jar.sha512 +++ b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi-sources.jar.sha512 @@ -1 +1 @@ -2ea38b712c0fb3b03cf1e578c4e01647805b39171b40ae2088b6aab45bec4ebffcee027c452abeb2ec42678dbb37ac2007ae643e74a7e3065f49bd83ee449f05 \ No newline at end of file +be5fca3a8fe37b16aac1478593fbc9935653d4ec264db0afaa16517d374ed6248996813575076528a1adefd5330f8960a699e8725491ce26022c8d23d21d25d5 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.aar b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.aar index e0ff23fc16..6c4981e9d2 100644 Binary files a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.aar and b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.aar differ diff --git a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.aar.md5 b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.aar.md5 index 5b20bc8bb7..c91259f1d3 100644 --- a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.aar.md5 +++ b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.aar.md5 @@ -1 +1 @@ -01a9245692478ce5acfb68f639bdb5cc \ No newline at end of file +8cb5bdbde8e7c6b5c1d96182f29fc6b2 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.aar.sha1 b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.aar.sha1 index 1a570de7c3..4151052466 100644 --- a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.aar.sha1 +++ b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.aar.sha1 @@ -1 +1 @@ -ebcb9ea550740d908e97afa29ec5928a45af0492 \ No newline at end of file +c63c93debbc6b33401e4a19d115800e12a8b7cb3 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.aar.sha256 b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.aar.sha256 index 2b1f43f551..8dbc432f44 100644 --- a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.aar.sha256 +++ b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.aar.sha256 @@ -1 +1 @@ -da39f2ae8f637414365d95428ae61e0d1603d2eb9053f022e8ce8d6e36a915e2 \ No newline at end of file +32c54bcb6113499267fadd75385d1a69a04eec3fcc34edf11e9bf6012d81ed91 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.aar.sha512 b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.aar.sha512 index 45fa313a28..d05ede8a31 100644 --- a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.aar.sha512 +++ b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.aar.sha512 @@ -1 +1 @@ -552473b1a29563ce7d07ddfd9a09a0d7bfebe6d4d150153535a83409f6f0d263cbe745a749d39c23705301987f4367445d24095e5db1052e6bd97ff397338cbd \ No newline at end of file +5e88a9c902574f57dc71e78dc5134dcb5e07e7877b0e5c61fd47e46fccd4142e88630beb4d83c2fc8f8eac41696fccc16c727b14882f6d606000ef3b968ae10e \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.module b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.module index f22d23ca87..a8a3c941a5 100644 --- a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.module +++ b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.module @@ -35,11 +35,11 @@ { "name": "media3-container-1.11.0-alpha01-fongmi.aar", "url": "media3-container-1.11.0-alpha01-fongmi.aar", - "size": 67408, - "sha512": "552473b1a29563ce7d07ddfd9a09a0d7bfebe6d4d150153535a83409f6f0d263cbe745a749d39c23705301987f4367445d24095e5db1052e6bd97ff397338cbd", - "sha256": "da39f2ae8f637414365d95428ae61e0d1603d2eb9053f022e8ce8d6e36a915e2", - "sha1": "ebcb9ea550740d908e97afa29ec5928a45af0492", - "md5": "01a9245692478ce5acfb68f639bdb5cc" + "size": 67476, + "sha512": "5e88a9c902574f57dc71e78dc5134dcb5e07e7877b0e5c61fd47e46fccd4142e88630beb4d83c2fc8f8eac41696fccc16c727b14882f6d606000ef3b968ae10e", + "sha256": "32c54bcb6113499267fadd75385d1a69a04eec3fcc34edf11e9bf6012d81ed91", + "sha1": "c63c93debbc6b33401e4a19d115800e12a8b7cb3", + "md5": "8cb5bdbde8e7c6b5c1d96182f29fc6b2" } ] }, @@ -71,11 +71,11 @@ { "name": "media3-container-1.11.0-alpha01-fongmi.aar", "url": "media3-container-1.11.0-alpha01-fongmi.aar", - "size": 67408, - "sha512": "552473b1a29563ce7d07ddfd9a09a0d7bfebe6d4d150153535a83409f6f0d263cbe745a749d39c23705301987f4367445d24095e5db1052e6bd97ff397338cbd", - "sha256": "da39f2ae8f637414365d95428ae61e0d1603d2eb9053f022e8ce8d6e36a915e2", - "sha1": "ebcb9ea550740d908e97afa29ec5928a45af0492", - "md5": "01a9245692478ce5acfb68f639bdb5cc" + "size": 67476, + "sha512": "5e88a9c902574f57dc71e78dc5134dcb5e07e7877b0e5c61fd47e46fccd4142e88630beb4d83c2fc8f8eac41696fccc16c727b14882f6d606000ef3b968ae10e", + "sha256": "32c54bcb6113499267fadd75385d1a69a04eec3fcc34edf11e9bf6012d81ed91", + "sha1": "c63c93debbc6b33401e4a19d115800e12a8b7cb3", + "md5": "8cb5bdbde8e7c6b5c1d96182f29fc6b2" } ] }, @@ -91,11 +91,11 @@ { "name": "media3-container-1.11.0-alpha01-fongmi-sources.jar", "url": "media3-container-1.11.0-alpha01-fongmi-sources.jar", - "size": 55494, - "sha512": "2ea38b712c0fb3b03cf1e578c4e01647805b39171b40ae2088b6aab45bec4ebffcee027c452abeb2ec42678dbb37ac2007ae643e74a7e3065f49bd83ee449f05", - "sha256": "1389b973146391c7eb6cfb80d389cfb70f291a6fc092e1628af1886a6e00294c", - "sha1": "3e37f3e1dd1f2998b51802e43fb962dfcb2baed3", - "md5": "69d4b0f429e82ce10175949bbbccad6d" + "size": 55524, + "sha512": "be5fca3a8fe37b16aac1478593fbc9935653d4ec264db0afaa16517d374ed6248996813575076528a1adefd5330f8960a699e8725491ce26022c8d23d21d25d5", + "sha256": "9aee6336465f59a29efcadd5c72b26fd8cdaa3ee4ee88a74ad99de003ddc43b6", + "sha1": "17a911e6516ee5057eeab7f8a24eab1dcbbe2ac1", + "md5": "7ab9bb46dba7720c3571ae51af85760a" } ] } diff --git a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.module.md5 b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.module.md5 index 858861c33c..96cfc2255d 100644 --- a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.module.md5 +++ b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.module.md5 @@ -1 +1 @@ -06ebbd54511a804f7192d06ddf9de43c \ No newline at end of file +8cc61351853405dd636d226f7321473c \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.module.sha1 b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.module.sha1 index febb5bb0c2..94534e17e3 100644 --- a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.module.sha1 +++ b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.module.sha1 @@ -1 +1 @@ -38540d0ddbb35ec0b1197132e82d896686ecd184 \ No newline at end of file +c5aa224704b9bf73458b23aeaaf86998cc5a49ee \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.module.sha256 b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.module.sha256 index c87a319a4a..78647de11a 100644 --- a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.module.sha256 +++ b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.module.sha256 @@ -1 +1 @@ -a49ab08e381d3d57436e9b2e4b267a571a9dff5124cf8a3b7c6dd1aa28781c03 \ No newline at end of file +cad4ff5204c1d7f99c00d96a98c22f34241d38b56c99967595e14dd26b05f8fe \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.module.sha512 b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.module.sha512 index 3ab54efaef..8144fe9de4 100644 --- a/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.module.sha512 +++ b/third_party/maven/androidx/media3/media3-container/1.11.0-alpha01-fongmi/media3-container-1.11.0-alpha01-fongmi.module.sha512 @@ -1 +1 @@ -26aeed3f926e975fa7408f140cdcb4fb125b086fb66fb5383eeb9ba9dda146224889e4d521278c379bc35c7e05851d6d1d9a1ba76859cdfccb58d2062b8a4e9b \ No newline at end of file +72f979376e93605199255491c7a826907ede450c31cb6e61a925b0c181182472663148e67363fea12f394bce7d6fc77df468333499d4ba5aad76be9e0026a4d1 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi-sources.jar b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi-sources.jar index 0704b0e4f2..adab79ed82 100644 Binary files a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi-sources.jar and b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi-sources.jar differ diff --git a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi-sources.jar.md5 b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi-sources.jar.md5 index 19210cedab..5ffa62a79d 100644 --- a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi-sources.jar.md5 +++ b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi-sources.jar.md5 @@ -1 +1 @@ -9b66b7690d0cd32177be3e9b7d3540e2 \ No newline at end of file +577becc3a04bd5fb1824c58a2018b5ed \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi-sources.jar.sha1 b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi-sources.jar.sha1 index 08d2c36cf9..b24e0b618e 100644 --- a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi-sources.jar.sha1 +++ b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi-sources.jar.sha1 @@ -1 +1 @@ -9622b0a1ea08906a84bebe36199b02504e693bdb \ No newline at end of file +fb7ea599304e4c380f574595e1e4845d001ab6d9 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi-sources.jar.sha256 b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi-sources.jar.sha256 index 9b0907e8b8..ddb9ca9ab8 100644 --- a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi-sources.jar.sha256 +++ b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi-sources.jar.sha256 @@ -1 +1 @@ -de3b25ebf4d775e73a4f8636bddbd88753ae791f70cecb2a20e721344782ebf8 \ No newline at end of file +26306314752ff1b4297aea2f25e6ff0213497404564f23af95ec4bb5c25ada62 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi-sources.jar.sha512 b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi-sources.jar.sha512 index d5e30602ab..28db3de819 100644 --- a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi-sources.jar.sha512 +++ b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi-sources.jar.sha512 @@ -1 +1 @@ -86dbf27ac4d83af9c45a741816b038cd5d66fb96dc6e1b1e05ed928ec8dd3ca908984140d7e37b7ac9b7d5fa30a2ce73b595fb0057a3c16dc757949f52403aaf \ No newline at end of file +63424b3dc6e211aa24da7d3b092a0bea99a3d785348dbbc092593e577da0aa5c812408107a8e10fe777ab45fd33a0496be4ccf38fa9b5b50361df0b1cd20f338 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.aar b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.aar index 5381b2e39d..74f218f8dd 100644 Binary files a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.aar and b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.aar differ diff --git a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.aar.md5 b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.aar.md5 index ae5296fbfa..9e19c60948 100644 --- a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.aar.md5 +++ b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.aar.md5 @@ -1 +1 @@ -112e7b738775f8ec0f97fc454a454a09 \ No newline at end of file +612a2e8966d8724acbe3cd5e0d933c16 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.aar.sha1 b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.aar.sha1 index 7fb084675c..2b73561085 100644 --- a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.aar.sha1 +++ b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.aar.sha1 @@ -1 +1 @@ -230816246cefcbd3bb115aa3c84610b524ae13d2 \ No newline at end of file +aa934f24f1d53999e0e44efee739b4bd43ab69d7 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.aar.sha256 b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.aar.sha256 index c1b67974ce..0e53694dec 100644 --- a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.aar.sha256 +++ b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.aar.sha256 @@ -1 +1 @@ -4c27ca5604ce67438db14faf15f2a9aa106c50e74d666d5724af2fc551d8830d \ No newline at end of file +1b6b51e921577cb955db2ce05106a44001ad126b8f4cc67f997d1f3404ec3598 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.aar.sha512 b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.aar.sha512 index a26471dc00..7e22f553b0 100644 --- a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.aar.sha512 +++ b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.aar.sha512 @@ -1 +1 @@ -d2529406d190fa632e629497fdcc1aa030e24cd9415c054db47de26d00fbdee0c15ae3f0a1d445abc54e19038967868c80f1ab7bfec2de1b29f33ad301a1d81b \ No newline at end of file +b3d71d1e91ca066717a5b54d047597b2ab909b091a112a0cf454dd889459bb769d63b1df5f2c3f544a5620315205811051a5b62d5dbe610dcc19d55df3357cfc \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.module b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.module index 37aaa29eb7..80df35aee3 100644 --- a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.module +++ b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.module @@ -42,11 +42,11 @@ { "name": "media3-datasource-1.11.0-alpha01-fongmi.aar", "url": "media3-datasource-1.11.0-alpha01-fongmi.aar", - "size": 180166, - "sha512": "d2529406d190fa632e629497fdcc1aa030e24cd9415c054db47de26d00fbdee0c15ae3f0a1d445abc54e19038967868c80f1ab7bfec2de1b29f33ad301a1d81b", - "sha256": "4c27ca5604ce67438db14faf15f2a9aa106c50e74d666d5724af2fc551d8830d", - "sha1": "230816246cefcbd3bb115aa3c84610b524ae13d2", - "md5": "112e7b738775f8ec0f97fc454a454a09" + "size": 182221, + "sha512": "b3d71d1e91ca066717a5b54d047597b2ab909b091a112a0cf454dd889459bb769d63b1df5f2c3f544a5620315205811051a5b62d5dbe610dcc19d55df3357cfc", + "sha256": "1b6b51e921577cb955db2ce05106a44001ad126b8f4cc67f997d1f3404ec3598", + "sha1": "aa934f24f1d53999e0e44efee739b4bd43ab69d7", + "md5": "612a2e8966d8724acbe3cd5e0d933c16" } ] }, @@ -99,11 +99,11 @@ { "name": "media3-datasource-1.11.0-alpha01-fongmi.aar", "url": "media3-datasource-1.11.0-alpha01-fongmi.aar", - "size": 180166, - "sha512": "d2529406d190fa632e629497fdcc1aa030e24cd9415c054db47de26d00fbdee0c15ae3f0a1d445abc54e19038967868c80f1ab7bfec2de1b29f33ad301a1d81b", - "sha256": "4c27ca5604ce67438db14faf15f2a9aa106c50e74d666d5724af2fc551d8830d", - "sha1": "230816246cefcbd3bb115aa3c84610b524ae13d2", - "md5": "112e7b738775f8ec0f97fc454a454a09" + "size": 182221, + "sha512": "b3d71d1e91ca066717a5b54d047597b2ab909b091a112a0cf454dd889459bb769d63b1df5f2c3f544a5620315205811051a5b62d5dbe610dcc19d55df3357cfc", + "sha256": "1b6b51e921577cb955db2ce05106a44001ad126b8f4cc67f997d1f3404ec3598", + "sha1": "aa934f24f1d53999e0e44efee739b4bd43ab69d7", + "md5": "612a2e8966d8724acbe3cd5e0d933c16" } ] }, @@ -119,11 +119,11 @@ { "name": "media3-datasource-1.11.0-alpha01-fongmi-sources.jar", "url": "media3-datasource-1.11.0-alpha01-fongmi-sources.jar", - "size": 145178, - "sha512": "86dbf27ac4d83af9c45a741816b038cd5d66fb96dc6e1b1e05ed928ec8dd3ca908984140d7e37b7ac9b7d5fa30a2ce73b595fb0057a3c16dc757949f52403aaf", - "sha256": "de3b25ebf4d775e73a4f8636bddbd88753ae791f70cecb2a20e721344782ebf8", - "sha1": "9622b0a1ea08906a84bebe36199b02504e693bdb", - "md5": "9b66b7690d0cd32177be3e9b7d3540e2" + "size": 146418, + "sha512": "63424b3dc6e211aa24da7d3b092a0bea99a3d785348dbbc092593e577da0aa5c812408107a8e10fe777ab45fd33a0496be4ccf38fa9b5b50361df0b1cd20f338", + "sha256": "26306314752ff1b4297aea2f25e6ff0213497404564f23af95ec4bb5c25ada62", + "sha1": "fb7ea599304e4c380f574595e1e4845d001ab6d9", + "md5": "577becc3a04bd5fb1824c58a2018b5ed" } ] } diff --git a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.module.md5 b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.module.md5 index 6e04f1aee3..1bc87dbc9e 100644 --- a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.module.md5 +++ b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.module.md5 @@ -1 +1 @@ -b3f3f75cd243093f4da1bccc453d63e1 \ No newline at end of file +66816632c38358da630d8de1853ea6e3 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.module.sha1 b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.module.sha1 index 37eb94ac27..143950984c 100644 --- a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.module.sha1 +++ b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.module.sha1 @@ -1 +1 @@ -6e9cb289922ec5b2798d170778fd8136f51eb446 \ No newline at end of file +15b227bb645cf3c6017692d5352b157fb57bf3ab \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.module.sha256 b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.module.sha256 index d89341b530..805faf1821 100644 --- a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.module.sha256 +++ b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.module.sha256 @@ -1 +1 @@ -9181e576cfebff4978c8fbca1b43159799d0f4c23c0b5b9c464ae4b634d73999 \ No newline at end of file +7f50a6b1817a68d7ca57899765029fda3fe37d926ee69689a6116fa518d0903d \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.module.sha512 b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.module.sha512 index 0f6b9dd753..8b01b4bf9c 100644 --- a/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.module.sha512 +++ b/third_party/maven/androidx/media3/media3-datasource/1.11.0-alpha01-fongmi/media3-datasource-1.11.0-alpha01-fongmi.module.sha512 @@ -1 +1 @@ -90df0002ac0f27651ba25e02d25cdfc50660082dbe69bbdc6702e63d27ee8851d06380fdde3e701dcb850c3ce1ad30abf150e8539395f93000c1b14fbd761b7b \ No newline at end of file +f42e67227ce9f4f98f0c8c5ab543a17ef6caddcf9f5c85293bb72c48438f3961e115f65fd99afe1c8589f4975d161d0c05b893103f742c1971265314e3118e39 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi-sources.jar b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi-sources.jar index b8eb30c5df..6802de4bd9 100644 Binary files a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi-sources.jar and b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi-sources.jar differ diff --git a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi-sources.jar.md5 b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi-sources.jar.md5 index 4c81aabcd8..5eed516b09 100644 --- a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi-sources.jar.md5 +++ b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi-sources.jar.md5 @@ -1 +1 @@ -a5203a283d2566378e30d0e33e0be457 \ No newline at end of file +91530feabc5974359d52836a189a5f16 diff --git a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi-sources.jar.sha1 b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi-sources.jar.sha1 index 6c7768948b..2f9d45c660 100644 --- a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi-sources.jar.sha1 +++ b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi-sources.jar.sha1 @@ -1 +1 @@ -16afaeeaf7af9899c745fc618f1745ff7fa6777b \ No newline at end of file +5b7e931e9c27c6c6ef1b62dff37026685fa5e076 diff --git a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi-sources.jar.sha256 b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi-sources.jar.sha256 index 5a77acfaab..1fd86034d9 100644 --- a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi-sources.jar.sha256 +++ b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi-sources.jar.sha256 @@ -1 +1 @@ -8c29d18a91012c06c714238f7a44afa349c27afa9d2de16c7d4874a607ad603a \ No newline at end of file +83f4f83b4f44e621d52002c161f63fbcb77be6856af4b1e4a4cb0982b04549e1 diff --git a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi-sources.jar.sha512 b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi-sources.jar.sha512 index 3167099cce..b799e3e638 100644 --- a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi-sources.jar.sha512 +++ b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi-sources.jar.sha512 @@ -1 +1 @@ -bbe9650a315026f73c3f91e762c9cc4f7c47e22e1038a82e4a50f40d2fe8d52eebd7d0145bf3519af631566ee1241d2ed870eea07e3db6bbbb35936766b0ecbc \ No newline at end of file +075cd93a897634f00a163c93e085399a8975a2adb8a3266d239d07e90c9697c03849d47f9e551e313fb862cce0a3f10416955d00e09c9b59c197f3de543aa067 diff --git a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.aar b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.aar index 73cd1ba8a7..c006205879 100644 Binary files a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.aar and b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.aar differ diff --git a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.aar.md5 b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.aar.md5 index db7f72351d..ee22b86b0d 100644 --- a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.aar.md5 +++ b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.aar.md5 @@ -1 +1 @@ -7df342d5749464e4968974e1c972597a \ No newline at end of file +0850011bbcf5853700f69e7cac5539f8 diff --git a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.aar.sha1 b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.aar.sha1 index ebd3e2cd75..7fb5a46165 100644 --- a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.aar.sha1 +++ b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.aar.sha1 @@ -1 +1 @@ -ca06709a242cbf556c1960b2a586703da357e66a \ No newline at end of file +0436ffdcf3b77bb1109fc24c9dae68b1427a8e83 diff --git a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.aar.sha256 b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.aar.sha256 index 85a21c6d32..3a0ed4d211 100644 --- a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.aar.sha256 +++ b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.aar.sha256 @@ -1 +1 @@ -3de2a24439fdbf5ef1641b9f8a53bfca5fb1b72f6d3ecabfb0aeebf3d296d3c6 \ No newline at end of file +cfea29681799509923174cac7ce31b7e944e542db9df58fd56b7a86499a5c07e diff --git a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.aar.sha512 b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.aar.sha512 index f8292080aa..9fbaa468da 100644 --- a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.aar.sha512 +++ b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.aar.sha512 @@ -1 +1 @@ -88d8426be663504a1174a719eaa5286f42f8ef860dc63e0e3f7bae025b9657e670305c12b7e377738bae24731826deb874bfb8778a10ee945392d952c2376c8b \ No newline at end of file +6f47c9fdd2ee597d57c268f238cdeeb84d684169e36f2221b9737473ee19ccf1d5dbeb52502518e63c6b1920fa5bb2658e990dbea1cbb935b368562b70861912 diff --git a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.module b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.module index 16f473f7ec..6291f166f0 100644 --- a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.module +++ b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.module @@ -70,11 +70,11 @@ { "name": "media3-exoplayer-1.11.0-alpha01-fongmi.aar", "url": "media3-exoplayer-1.11.0-alpha01-fongmi.aar", - "size": 1740394, - "sha512": "88d8426be663504a1174a719eaa5286f42f8ef860dc63e0e3f7bae025b9657e670305c12b7e377738bae24731826deb874bfb8778a10ee945392d952c2376c8b", - "sha256": "3de2a24439fdbf5ef1641b9f8a53bfca5fb1b72f6d3ecabfb0aeebf3d296d3c6", - "sha1": "ca06709a242cbf556c1960b2a586703da357e66a", - "md5": "7df342d5749464e4968974e1c972597a" + "size": 1739181, + "sha512": "2662e693801b53298cbe0fd649a1748208e9483ab28da0bc91bc925067af4ddbc6d1bfbf0bc5237303fa91f156a44c9310c7b62214786c800bf678ec6bc2a257", + "sha256": "11d572f59f0404878353d9c85e022e153e114ecbb4d43cf61c910cd9e8c2536d", + "sha1": "c37019f592fe60cb9d0cb18c12040bbb82a2263c", + "md5": "a738184547695deabc648e55b7c207b2" } ] }, @@ -155,11 +155,11 @@ { "name": "media3-exoplayer-1.11.0-alpha01-fongmi.aar", "url": "media3-exoplayer-1.11.0-alpha01-fongmi.aar", - "size": 1740394, - "sha512": "88d8426be663504a1174a719eaa5286f42f8ef860dc63e0e3f7bae025b9657e670305c12b7e377738bae24731826deb874bfb8778a10ee945392d952c2376c8b", - "sha256": "3de2a24439fdbf5ef1641b9f8a53bfca5fb1b72f6d3ecabfb0aeebf3d296d3c6", - "sha1": "ca06709a242cbf556c1960b2a586703da357e66a", - "md5": "7df342d5749464e4968974e1c972597a" + "size": 1739181, + "sha512": "2662e693801b53298cbe0fd649a1748208e9483ab28da0bc91bc925067af4ddbc6d1bfbf0bc5237303fa91f156a44c9310c7b62214786c800bf678ec6bc2a257", + "sha256": "11d572f59f0404878353d9c85e022e153e114ecbb4d43cf61c910cd9e8c2536d", + "sha1": "c37019f592fe60cb9d0cb18c12040bbb82a2263c", + "md5": "a738184547695deabc648e55b7c207b2" } ] }, @@ -175,11 +175,11 @@ { "name": "media3-exoplayer-1.11.0-alpha01-fongmi-sources.jar", "url": "media3-exoplayer-1.11.0-alpha01-fongmi-sources.jar", - "size": 1252993, - "sha512": "bbe9650a315026f73c3f91e762c9cc4f7c47e22e1038a82e4a50f40d2fe8d52eebd7d0145bf3519af631566ee1241d2ed870eea07e3db6bbbb35936766b0ecbc", - "sha256": "8c29d18a91012c06c714238f7a44afa349c27afa9d2de16c7d4874a607ad603a", - "sha1": "16afaeeaf7af9899c745fc618f1745ff7fa6777b", - "md5": "a5203a283d2566378e30d0e33e0be457" + "size": 1253917, + "sha512": "6883079131cf97bf0d6ed5b8ebc5e08d8e507f02609aa62c0af5e62da2b1a9c3f883243e2bf182948af4f906fb5f2cdf55c5d8ea6b65e1e3e32a1469f173b578", + "sha256": "c2a74d177abff6e91de2b26d0680920a966672796a080572d6477a2e3c9aa6db", + "sha1": "acc179c1381092a419dff9568a5297416eba1fe9", + "md5": "a33bb2038a20dcb4f30a916f5672e85f" } ] } diff --git a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.module.md5 b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.module.md5 index b1fa2c5ae1..2aa506aca8 100644 --- a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.module.md5 +++ b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.module.md5 @@ -1 +1 @@ -31714429f6ce7b5331af47244e5bd6ff \ No newline at end of file +6700bf87b8028af9221e6b1af1622828 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.module.sha1 b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.module.sha1 index 40aeedc5b9..abf1068baa 100644 --- a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.module.sha1 +++ b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.module.sha1 @@ -1 +1 @@ -e1568069ed8269e8392ea01672a6be44aabb0201 \ No newline at end of file +ed5c2774a2a67c018e0d2b9588e1c7c730673879 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.module.sha256 b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.module.sha256 index 76274902ca..43182f6b3a 100644 --- a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.module.sha256 +++ b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.module.sha256 @@ -1 +1 @@ -5f7f014b5ef69c2de6347f2a1de617a44bb3d47b914e333be252f0a53d38fe68 \ No newline at end of file +f20106bb4c89f0b167dec34a2909daf427149800e14f11db130431e95523e95d \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.module.sha512 b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.module.sha512 index 2ced2b1779..847304a200 100644 --- a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.module.sha512 +++ b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.module.sha512 @@ -1 +1 @@ -9d53d6b9db11bd76686e0a0958874d98adea02af17ecea339e41165b5cb58f7090f1b3989108bdc79f3fddc69c8b4c026eb4878e2f1cacec85993ebc5c7068e3 \ No newline at end of file +0f312da1187d3228f61f772db3e4b8c56c99ce0f6b2945d9f5825c8f0932a6a5fc6adb1cf90c20fe19befbfec37ecbec1ce90555ff53b5677f3235114b136c42 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.pom.md5 b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.pom.md5 index 8c83e52500..05853d7a50 100644 --- a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.pom.md5 +++ b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.pom.md5 @@ -1 +1 @@ -8cbe57bc947c2159598aa03f3cedde7c \ No newline at end of file +d7f52bfbb57e853ed7c5726d832455ce \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.pom.sha1 b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.pom.sha1 index 6f08ce4dff..c9f5c308f0 100644 --- a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.pom.sha1 +++ b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.pom.sha1 @@ -1 +1 @@ -e75e26c575790abc82401760a40f6dfc99ea1c03 \ No newline at end of file +2a93c05f8f59a2c6d3b48f7a111e94af3a09274d \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.pom.sha256 b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.pom.sha256 index 682abd9f6a..e0fc0e2a40 100644 --- a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.pom.sha256 +++ b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.pom.sha256 @@ -1 +1 @@ -ca5be4f0911931b82df270917cb91d2f1d221a97bcecd11f0d78eeaa620308a5 \ No newline at end of file +d24224701e867501cf49b6e26bee4efa6a9678e24a91e48b4f86c012e6970501 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.pom.sha512 b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.pom.sha512 index 4f751d0b64..1ff69c4b80 100644 --- a/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.pom.sha512 +++ b/third_party/maven/androidx/media3/media3-exoplayer/1.11.0-alpha01-fongmi/media3-exoplayer-1.11.0-alpha01-fongmi.pom.sha512 @@ -1 +1 @@ -d7ffe1f41a7d4b262a042cbe6e342550bfe715fc076b0f3a6bc72cb3ddbc3037f2f99f7e54aca542479da99fa83359eba35e030cea8207a511a7c94c80614297 \ No newline at end of file +14536137ca0dbd82437eb9a3c4fc05ab19af9e4f82862d282604fb70d4d10b715cf2699f492fa0b82585e26f4764ba6385e1fc690bd1b2491d5b2824d6c47343 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-exoplayer/maven-metadata.xml b/third_party/maven/androidx/media3/media3-exoplayer/maven-metadata.xml index 169db6761a..d2a707be98 100644 --- a/third_party/maven/androidx/media3/media3-exoplayer/maven-metadata.xml +++ b/third_party/maven/androidx/media3/media3-exoplayer/maven-metadata.xml @@ -8,6 +8,6 @@ 1.11.0-alpha01-fongmi - 20260809152658 + 20260826171434 diff --git a/third_party/maven/androidx/media3/media3-exoplayer/maven-metadata.xml.md5 b/third_party/maven/androidx/media3/media3-exoplayer/maven-metadata.xml.md5 index 9925c22eed..0d404648da 100644 --- a/third_party/maven/androidx/media3/media3-exoplayer/maven-metadata.xml.md5 +++ b/third_party/maven/androidx/media3/media3-exoplayer/maven-metadata.xml.md5 @@ -1 +1 @@ -b075a8e949ea05fdf2c36c6bfcdd4f2c \ No newline at end of file +bfd220053b74a026892afc33daeb1784 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-exoplayer/maven-metadata.xml.sha1 b/third_party/maven/androidx/media3/media3-exoplayer/maven-metadata.xml.sha1 index 6b0a942550..d4aad4972b 100644 --- a/third_party/maven/androidx/media3/media3-exoplayer/maven-metadata.xml.sha1 +++ b/third_party/maven/androidx/media3/media3-exoplayer/maven-metadata.xml.sha1 @@ -1 +1 @@ -0e83570ae3f1fcb4403cb252cc4731d50cda6e34 \ No newline at end of file +49bd34c570d08ecae00a3020d3f2d650971806e9 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-exoplayer/maven-metadata.xml.sha256 b/third_party/maven/androidx/media3/media3-exoplayer/maven-metadata.xml.sha256 index b34eab7cff..21f243281f 100644 --- a/third_party/maven/androidx/media3/media3-exoplayer/maven-metadata.xml.sha256 +++ b/third_party/maven/androidx/media3/media3-exoplayer/maven-metadata.xml.sha256 @@ -1 +1 @@ -39e9ca0914bf3e20e8b3328e7b165df76fdaef44d152772f753c2ad64afa83eb \ No newline at end of file +976d633ae3345be73a74251a90c134aedf180b8b0f0aaaf18ee6dccb04f4ceab \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-exoplayer/maven-metadata.xml.sha512 b/third_party/maven/androidx/media3/media3-exoplayer/maven-metadata.xml.sha512 index 91acfd665c..b570372f39 100644 --- a/third_party/maven/androidx/media3/media3-exoplayer/maven-metadata.xml.sha512 +++ b/third_party/maven/androidx/media3/media3-exoplayer/maven-metadata.xml.sha512 @@ -1 +1 @@ -be65ff91745066632081ca10b2ede5c295b65ad39db02b9e04e8d3cdd899d80d31632a0a1180e17f7867511a9e6ae933afa9aea11641f6427e6a20e2505450d3 \ No newline at end of file +d73ad6354defd5e35d8fea73c0a93ce85788ff7722b0d60246d6bf7ee3d40db95d71001a3518feb2f106921089ab35d7be4d059debc64a62c3036db2a73c6c32 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi-sources.jar b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi-sources.jar index 923003d177..f486d3fbea 100644 Binary files a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi-sources.jar and b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi-sources.jar differ diff --git a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi-sources.jar.md5 b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi-sources.jar.md5 index ab91c30c7c..2737364245 100644 --- a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi-sources.jar.md5 +++ b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi-sources.jar.md5 @@ -1 +1 @@ -7d22ecf935b0e78dc955bf10d259ab3b \ No newline at end of file +f832babd94641c6cc371e0f12b4c9f9c \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi-sources.jar.sha1 b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi-sources.jar.sha1 index e01946e698..6940acc8a4 100644 --- a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi-sources.jar.sha1 +++ b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi-sources.jar.sha1 @@ -1 +1 @@ -5e6e83ae831456f1a95d25dab50fa724a9b0242d \ No newline at end of file +721767dccdf192727aa6d88666044743875c53aa \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi-sources.jar.sha256 b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi-sources.jar.sha256 index f36c4dbca6..22aefbe2f9 100644 --- a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi-sources.jar.sha256 +++ b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi-sources.jar.sha256 @@ -1 +1 @@ -a9a813622f10b4735f71ba3c8e535981adca4941bd0f6d832efe31e80b033295 \ No newline at end of file +9314a303f402e903dd075db5e9babf9be6474da539a4b76bb1ed765b95b6ef4e \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi-sources.jar.sha512 b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi-sources.jar.sha512 index a1589cd609..f9b067f677 100644 --- a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi-sources.jar.sha512 +++ b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi-sources.jar.sha512 @@ -1 +1 @@ -2655845bfb39a2ff339bf117ee8eff1ced21da01a5701b5ed72564489e7e27a7e5ebf922b5acf0b0a2f1e5d2cfc0969b1bc08fd78bb16f387ccaa3afded4efeb \ No newline at end of file +c03effbf8116bc5adebda3af3789c4dc734e9181ac4232755098e4f36356cca83a64008f6ba024150191ce7046bb1378e088fe23a69d83e8b7693f342fee3547 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.aar b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.aar index 9705cf3a34..e138ad3d54 100644 Binary files a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.aar and b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.aar differ diff --git a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.aar.md5 b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.aar.md5 index c64b3f0784..a5fc247a66 100644 --- a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.aar.md5 +++ b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.aar.md5 @@ -1 +1 @@ -94de73fc45aa5286a05ed16e371d3932 \ No newline at end of file +f6ef0358e9764d3adf09bbd5192240d0 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.aar.sha1 b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.aar.sha1 index 80e5b8020c..040f37aa22 100644 --- a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.aar.sha1 +++ b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.aar.sha1 @@ -1 +1 @@ -028c5e09f079080278628f5996422cbda45a88c9 \ No newline at end of file +cf2769361a8b4b97c77738f07920055dd45c9a30 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.aar.sha256 b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.aar.sha256 index 7b5bc46614..1342103b44 100644 --- a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.aar.sha256 +++ b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.aar.sha256 @@ -1 +1 @@ -ec3ac41088e496bdfe63925ca0751234e0178a9d92e8deedf8734dfe36fab8fe \ No newline at end of file +59a090bad8efc32552cf5a7ec1d2fb66444168bfbc97bd45e50764527f80c768 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.aar.sha512 b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.aar.sha512 index a566b6d583..963a9043c5 100644 --- a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.aar.sha512 +++ b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.aar.sha512 @@ -1 +1 @@ -dd1cff73b216d8ee4c09a438d9f43b0a3e5f8bb508ea7bbb0b350792e68b102720f111182f766e90c9becc6fc668a74571ba768a0b8f5a83b278a31655ed1fb8 \ No newline at end of file +733b82b29e7307e9df482fb32f81a8bf7b1711b61fa6b9d072223fb0a75aa2e74fa7c1df41240a7eeeff2da97dba7010d663e20bfdf7b1fb52e8386736dd27c0 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.module b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.module index 7216c7618e..39e0928033 100644 --- a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.module +++ b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.module @@ -42,11 +42,11 @@ { "name": "media3-extractor-1.11.0-alpha01-fongmi.aar", "url": "media3-extractor-1.11.0-alpha01-fongmi.aar", - "size": 1007640, - "sha512": "dd1cff73b216d8ee4c09a438d9f43b0a3e5f8bb508ea7bbb0b350792e68b102720f111182f766e90c9becc6fc668a74571ba768a0b8f5a83b278a31655ed1fb8", - "sha256": "ec3ac41088e496bdfe63925ca0751234e0178a9d92e8deedf8734dfe36fab8fe", - "sha1": "028c5e09f079080278628f5996422cbda45a88c9", - "md5": "94de73fc45aa5286a05ed16e371d3932" + "size": 1016886, + "sha512": "733b82b29e7307e9df482fb32f81a8bf7b1711b61fa6b9d072223fb0a75aa2e74fa7c1df41240a7eeeff2da97dba7010d663e20bfdf7b1fb52e8386736dd27c0", + "sha256": "59a090bad8efc32552cf5a7ec1d2fb66444168bfbc97bd45e50764527f80c768", + "sha1": "cf2769361a8b4b97c77738f07920055dd45c9a30", + "md5": "f6ef0358e9764d3adf09bbd5192240d0" } ] }, @@ -99,11 +99,11 @@ { "name": "media3-extractor-1.11.0-alpha01-fongmi.aar", "url": "media3-extractor-1.11.0-alpha01-fongmi.aar", - "size": 1007640, - "sha512": "dd1cff73b216d8ee4c09a438d9f43b0a3e5f8bb508ea7bbb0b350792e68b102720f111182f766e90c9becc6fc668a74571ba768a0b8f5a83b278a31655ed1fb8", - "sha256": "ec3ac41088e496bdfe63925ca0751234e0178a9d92e8deedf8734dfe36fab8fe", - "sha1": "028c5e09f079080278628f5996422cbda45a88c9", - "md5": "94de73fc45aa5286a05ed16e371d3932" + "size": 1016886, + "sha512": "733b82b29e7307e9df482fb32f81a8bf7b1711b61fa6b9d072223fb0a75aa2e74fa7c1df41240a7eeeff2da97dba7010d663e20bfdf7b1fb52e8386736dd27c0", + "sha256": "59a090bad8efc32552cf5a7ec1d2fb66444168bfbc97bd45e50764527f80c768", + "sha1": "cf2769361a8b4b97c77738f07920055dd45c9a30", + "md5": "f6ef0358e9764d3adf09bbd5192240d0" } ] }, @@ -119,11 +119,11 @@ { "name": "media3-extractor-1.11.0-alpha01-fongmi-sources.jar", "url": "media3-extractor-1.11.0-alpha01-fongmi-sources.jar", - "size": 849790, - "sha512": "2655845bfb39a2ff339bf117ee8eff1ced21da01a5701b5ed72564489e7e27a7e5ebf922b5acf0b0a2f1e5d2cfc0969b1bc08fd78bb16f387ccaa3afded4efeb", - "sha256": "a9a813622f10b4735f71ba3c8e535981adca4941bd0f6d832efe31e80b033295", - "sha1": "5e6e83ae831456f1a95d25dab50fa724a9b0242d", - "md5": "7d22ecf935b0e78dc955bf10d259ab3b" + "size": 854530, + "sha512": "c03effbf8116bc5adebda3af3789c4dc734e9181ac4232755098e4f36356cca83a64008f6ba024150191ce7046bb1378e088fe23a69d83e8b7693f342fee3547", + "sha256": "9314a303f402e903dd075db5e9babf9be6474da539a4b76bb1ed765b95b6ef4e", + "sha1": "721767dccdf192727aa6d88666044743875c53aa", + "md5": "f832babd94641c6cc371e0f12b4c9f9c" } ] } diff --git a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.module.md5 b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.module.md5 index 0d071b9b84..eed65991d6 100644 --- a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.module.md5 +++ b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.module.md5 @@ -1 +1 @@ -145f0d43567a9c70ffc4b70ea12b9963 \ No newline at end of file +1c896cb28ad17490dcb83d7e39d7f969 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.module.sha1 b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.module.sha1 index ac3d32158d..0bd6cdcde2 100644 --- a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.module.sha1 +++ b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.module.sha1 @@ -1 +1 @@ -cd669d7877c18c00676db35ca438686854dbf7fc \ No newline at end of file +c24561308324e7ce68d9f0846035e1284e18d643 \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.module.sha256 b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.module.sha256 index a95fb1ac30..c94caf4b68 100644 --- a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.module.sha256 +++ b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.module.sha256 @@ -1 +1 @@ -df853ed2f5ddcb7c151895c8cf98bc384448aea793c2ab47b04c1b68364590e6 \ No newline at end of file +d470cbc53d7aa03f3b5e036b02c3f78157109a5240963d52ea8f2fde2c5d7a7a \ No newline at end of file diff --git a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.module.sha512 b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.module.sha512 index 931c27f4c4..1fdf4a0f1d 100644 --- a/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.module.sha512 +++ b/third_party/maven/androidx/media3/media3-extractor/1.11.0-alpha01-fongmi/media3-extractor-1.11.0-alpha01-fongmi.module.sha512 @@ -1 +1 @@ -09066d21bb7ab2037895b5e2d78aebe272ce2a2f165f90c8b88d7bce2d1ccf06469c9ce522dfaac2c7a5ea079493fae1472051bdf8a5519f254344a8543e9416 \ No newline at end of file +1ad98b1c3168cf90f3ebc2d9d7aea9d1854446897f05d93bc813c03433a2075af0040a8793d6b88d073a17cba6a14b34fec73113fc6b227057c280fa0706f5de \ No newline at end of file diff --git a/third_party/media-lock.json b/third_party/media-lock.json index 8a564e696f..466cb91e9c 100644 --- a/third_party/media-lock.json +++ b/third_party/media-lock.json @@ -19,15 +19,75 @@ }, { "path": "third_party/patches/media3-deferred-cues.patch", - "sha256": "8bfcf98dadfd70e56ebec4c5fd49701ddc8ed66b02707a7f733b3aec1ed4b2c7" + "sha256": "ebbfbe0bcd1f002780b2db300bdcf42d9c3309c0738b43212ffa224eedcba8dd" + }, + { + "path": "third_party/patches/media3-exo-hdr-parser-safety.patch", + "sha256": "a6a8bbf95630e70938dacde7e36c97ed330c5c426644893090cfc3280dc6ed20" + }, + { + "path": "third_party/patches/media3-exo-eac3-joc-pixel-guard.patch", + "sha256": "f36790e77d65cd2638c14eb38f23dbdd3125a2aec09acb031fe6baaa06ab7c41" + }, + { + "path": "third_party/patches/media3-exo-dts-14bit-frame-size.patch", + "sha256": "328fe823b824fd36e359ea16eea4c77334ea707676e9a2803258f29b661e3d77" + }, + { + "path": "third_party/patches/media3-exo-subtitle-byte-safety.patch", + "sha256": "8ed566a26b70609262d6c49ada2e8912997f36d75a166825e368182b5b7f35bf" + }, + { + "path": "third_party/patches/media3-exo-cue-data-contract.patch", + "sha256": "a6389e0c34a9a3e895072f84c9ffd13d0c883c5909d8887873717c337066eb61" + }, + { + "path": "third_party/patches/media3-exo-bounded-cache-writer.patch", + "sha256": "1b591c618fdbba91b0880284126ac8bd5c55f6fe6532187d891b4225a87cc200" + }, + { + "path": "third_party/patches/media3-exo-iso-reader-safety.patch", + "sha256": "d042b6c177910604f7f251571909d018d0227abc4af7846b15a0b5d499be5893" + }, + { + "path": "third_party/patches/media3-exo-iso-multi-extent.patch", + "sha256": "b4954d32f5c98dc5caf2a3cbc8cd72f72d24f4fdeec9425e5061a252d1ccaf68" + }, + { + "path": "third_party/patches/media3-precache-hls-safety.patch", + "sha256": "9b48e895bd3923159f880152a54160e7c937b2b0369d717da559a7ad98fd14f7" } ], "artifact_overrides": [ + { + "coordinate": "androidx.media3:media3-common:1.11.0-alpha01-fongmi", + "aar_sha256": "5a4815ab415c0650bc8adaa60e518f32df548ddcfafb43e02381281a96dac6e5", + "sources_sha256": "31c38835a729f422ba25835733aa94ac23d8fe6445df2d725a71e46a11d86bfc", + "reason": "E4-J1 adds Cue collision/region fields and LetterSpacingSpan data contracts" + }, + { + "coordinate": "androidx.media3:media3-container:1.11.0-alpha01-fongmi", + "aar_sha256": "32c54bcb6113499267fadd75385d1a69a04eec3fcc34edf11e9bf6012d81ed91", + "sources_sha256": "9aee6336465f59a29efcadd5c72b26fd8cdaa3ee4ee88a74ad99de003ddc43b6", + "reason": "E2-1 adds Dolby Vision parser version/length safety" + }, { "coordinate": "androidx.media3:media3-extractor:1.11.0-alpha01-fongmi", - "aar_sha256": "ec3ac41088e496bdfe63925ca0751234e0178a9d92e8deedf8734dfe36fab8fe", - "sources_sha256": "a9a813622f10b4735f71ba3c8e535981adca4941bd0f6d832efe31e80b033295", - "reason": "E-SP2 defers tail Cues for known-length remote Matroska while preserving exact seek on demand" + "aar_sha256": "59a090bad8efc32552cf5a7ec1d2fb66444168bfbc97bd45e50764527f80c768", + "sources_sha256": "9314a303f402e903dd075db5e9babf9be6474da539a4b76bb1ed765b95b6ef4e", + "reason": "E-SP2 chained SeekHead/deferred Cues plus E2-1/E3-1b/E4-1/E7-2 extractor behavior" + }, + { + "coordinate": "androidx.media3:media3-exoplayer:1.11.0-alpha01-fongmi", + "aar_sha256": "cfea29681799509923174cac7ce31b7e944e542db9df58fd56b7a86499a5c07e", + "sources_sha256": "83f4f83b4f44e621d52002c161f63fbcb77be6856af4b1e4a4cb0982b04549e1", + "reason": "E3-1a/E4-1 baseline plus E7-2 Blu-ray/DVD logical multi-extent routing and E-SP3-B HLS pre-cache request safety" + }, + { + "coordinate": "androidx.media3:media3-datasource:1.11.0-alpha01-fongmi", + "aar_sha256": "1b6b51e921577cb955db2ce05106a44001ad126b8f4cc67f997d1f3404ec3598", + "sources_sha256": "26306314752ff1b4297aea2f25e6ff0213497404564f23af95ec4bb5c25ada62", + "reason": "E6-1/E7-1 baseline plus E7-2 multi-extent ISO/UDF virtual data source" } ], "upstream_repo": "https://github.com/FongMi/media.git", @@ -47,6 +107,16 @@ "commit": "2fcf67cc83b295f389c0c9c4c5b5c40615781dcf", "scope": "libraries/common Util.getSystemProperty public API hunk only", "reason": "Required by bb3d9921; the unrelated HE-AAC offload behavior is intentionally excluded" + }, + { + "commit": "dd00f94b58b7324ab29febb0b50f3a190d544a3b", + "scope": "libraries/datasource CacheWriter bounded read/count/end-position hunks and focused test only", + "reason": "E6-1 fixes bounded cache writes; progressive parallel download, DiskPreloadManager, priority setter, and factory/cancel changes are intentionally excluded" + }, + { + "commit": "990abc2368fd74779f525ee345734470659f3d53", + "scope": "libraries/datasource IsoDataReader zero-length, prefetch bound, open/close, and EOF hunks plus focused tests only", + "reason": "E7-1 hardens the existing single-extent ISO reader; multi-extent UDF, virtual data source, and App resolver changes remain isolated to E7-2" } ] }, diff --git a/third_party/mpv-native-build.md b/third_party/mpv-native-build.md index cf02520924..68d279fa5d 100644 --- a/third_party/mpv-native-build.md +++ b/third_party/mpv-native-build.md @@ -44,11 +44,11 @@ third_party/mpv-native-lock.json | MPV | `FongMi/mpv@cca559b41ceb0bb7731cf6ef2e1f33276cd30c42`(`0.41.0-940-gcca559b41`) | | MediaCodec/Vulkan | FongMi 分支内建 AImageReader/AHardwareBuffer OpenGL/Vulkan 后端、sync-fd、HDR/Dolby Vision 和双 Surface OSD;不再叠加旧 `fd679c81` 或 transient patch | | Dolby Vision双层硬解 | `third_party/patches/mpv-android-dovi-el-surface.patch`:把 GPU 杜比元数据处理与独立增强层解码拆成两项能力;Android AImageReader 只提供单路生产者 Surface,因此 `gpu-next` 保留 DV5 映射、DV 来源识别与 HDR10 基础层回退,但不启动第二个无 Surface 的 `mediacodec-copy`;非 Android 输出仍可显式声明 EL 合成能力 | -| AudioTrack音频直通 | 保留 FongMi MPV 的 passthrough carrier rate 修复:PCM 可跟随设备原生采样率,SPDIF/IEC61937 必须保留编码器声明的载波采样率;E-AC3、TrueHD、DTS-HD 使用 192 kHz,不能改写为常见的 48 kHz,否则 MPV 会判定格式不一致并回退 PCM。`mpv-audiotrack-truehd-channel-mask.patch` 参考 VLC 的成熟 Android AudioTrack 实现,为 TrueHD 的 8-channel carrier 使用 7.1 mask,其他 IEC61937 格式继续使用 stereo carrier mask。App 侧取 Media3、HDMI/ARC/eARC/USB 路由编码和 MPV 实际 IEC61937 载波探测的交集,载波不被系统接受时不启用该格式直通,由 MPV 回退 PCM 解码。 | +| AudioTrack音频直通 | 保留 FongMi MPV 的 passthrough carrier rate 修复:PCM 可跟随设备原生采样率,SPDIF/IEC61937 必须保留编码器声明的载波采样率;E-AC3、TrueHD、DTS-HD 使用 192 kHz,不能改写为常见的 48 kHz,否则 MPV 会判定格式不一致并回退 PCM。`mpv-audiotrack-truehd-channel-mask.patch` 保留 TrueHD 全 API 7.1 兼容规则,并在 Android 12+ 仅对实际 8-channel carrier 使用 7.1 mask;DTS-HD HRA/其它 2-channel carrier 仍使用 stereo。App 侧对 DTS-HD 同时验证 stereo/7.1,取 Media3、HDMI/ARC/eARC/USB 路由编码和 MPV IEC61937 载波探测的交集;任一所需载波不被系统接受时不启用该格式直通,由 MPV 回退 PCM 解码。 | | MediaCodec直出 | `mpv-mediacodec-embed-optional-osd.patch` 允许关闭字幕时不创建额外 OSD Surface;`mpv-mediacodec-embed-timed-release.patch` 按播放 PTS 将缓冲帧提交给 MediaCodec,避免立即释放导致持续掉帧;`mpv-mediacodec-output-timing-diagnostics.patch` 只增加有界的提交/迟到/掉帧时序诊断。 | | Vulkan硬解稳定性与功耗 | `auto` 通过 `mpv-android-vulkan-smart-backend.patch` 恢复优先 direct AHardwareBuffer 采样,避免 HDR 默认执行全分辨率转换;direct 不支持时回退 queue-safe stable pool,再回退通用 conversion。显式 `stable` 保留给问题驱动,App 在自动模式发生视频输出错误或已识别首帧超时时会重建为 stable,并按设备环境记忆。stable 额外尝试两种 packed RGB10 storage 格式,最后才扩大到 RGBA16F。 | | Matroska代理Seek | `third_party/patches/mpv-matroska-segment-end.patch`,可Seek但HTTP总长度未知时使用MKV自身声明的Segment边界读取SeekHead/Cues | -| FFmpeg | `FongMi/FFmpeg@04482c8d13ac27b2a9fe93f5d388929eef8af5f4`(9.0 fongmi) | +| FFmpeg | `FongMi/FFmpeg@177f090e0503b7e013922ca903bde14b1c375f18`(9.0.1 fongmi) | | 本地代理Range兼容 | `third_party/patches/ffmpeg-webhtv-proxy-range.patch`,识别App内部代理验证后的206起点标记,不把第三方未知长度伪装成完整文件长度 | | libplacebo | `FongMi/libplacebo@b694a21bf2dc176c1e98b8a13c6421a0de5f3da5`(7.375.0) | | curl | 8.21.0,MbedTLS,HTTP/HTTPS、HTTP/2 | @@ -169,9 +169,10 @@ scripts/build_mpv_native.sh --abi arm64-v8a --jobs 8 --work-dir /tmp/webhtv-mpv- - `mpv-android-vulkan-smart-backend.patch` - `mpv-android-vulkan-legacy-backend.patch` - `mpv-aimagereader-stable-flow.patch` + - `mpv-p2-generic-uv.patch` - `mpv-matroska-segment-end.patch` - Profile 7 HDR10 回退使用 FFmpeg 官方 `dovi_split` 的 `mode=bl` 在 demux 层移除 EL/RPU,GPU 与电视直出都只接收可独立解码的 HDR10 基础层。MediaCodec 直出允许无 OSD Surface,并按 PTS 调度缓冲帧释放。Vulkan `auto` 优先 direct,然后回退 stable 和通用 conversion;`legacy` 保留早期 compute 路径供兼容性验证。AImageReader 按回调序列领取图像,并在 conversion fence 完成前保持 AImage 生命周期。 + Profile 7 HDR10 回退使用 FFmpeg 官方 `dovi_split` 的 `mode=bl` 在 demux 层移除 EL/RPU,GPU 与电视直出都只接收可独立解码的 HDR10 基础层。MediaCodec 直出允许无 OSD Surface,并按 PTS 调度缓冲帧释放。Vulkan `auto` 优先 direct,然后回退 stable 和通用 conversion;`legacy` 保留早期 compute 路径供兼容性验证。AImageReader 按回调序列领取图像,并在 conversion fence 完成前保持 AImage 生命周期。P2 generic compute/fragment shader 的 crop 与归一化除法由 CPU 每帧预计算,两个 SPIR-V header 必须由锁定 NDK r29 `glslc` 从补丁后的 shader source 重新生成并通过 `spirv-val`,不能手工修改数组。 7. 按依赖顺序构建字符集/压缩库、MbedTLS、dav1d、libxml2、FreeType、libaribcaption、FFmpeg、字体栈、shaderc、libplacebo、curl+nghttp2、libbluray、libarchive、DVD 库、rubberband 和 MPV。 8. 把 FFmpeg 的文件名、ELF `SONAME` 和 `DT_NEEDED` 从 `libav*`/`libsw*` 等长修改为 `libmv*`/`libmw*`。 9. 使用 NDK `llvm-strip --strip-unneeded` 处理最终库。 @@ -229,6 +230,12 @@ scripts/build_mpv_player_jni.sh 以后若只重编完全相同 client API/JNI 源码的 MPV/FFmpeg,才可以复用 `libplayer.so`。 +## P2-2 DV7 metadata/codecpar 窄适配(2026-08-29) + +P2-2 在现有 `mpv-dovi-profile7-hdr10-base-layer.patch` 内完成 Profile 7 HDR10 fallback 的 metadata/codecpar/error 完整性修复:缺少 `dv_el_present` 时仍仅对显式 HDR10 fallback 创建 `dovi_split=mode=bl`,检查 codec parameter 转换、BSF option/init 返回值,将成功过滤后的 `par_out` 原子同步回 decoder 参数并清除 EL 标记,同时在 packet 长度转换前拒绝超过 `INT_MAX` 的输入。现有三态 packet ownership、精确零拷贝、Surface Direct、单 Surface EL gate、DV7 设置和 FFmpeg `libmv*` 命名空间均保留;未升级 lock、FFmpeg、libplacebo、JNI 或启用 Android EL。 + +本阶段使用 NDK r29 对 `arm64-v8a` 与 `armeabi-v7a` 完整重建并安装 native assets;一次 `scripts/verify_mpv_native_assets.sh --require-elf` 通过,APK `app-mobile-arm64_v8a-debug.apk` 内十个 arm64 MPV 资产与工作区完全一致,两个 `libplayer.so` 保持字节不变。用户在 USB 连接的 vivo V2453A 上确认安装后的 DV7 及邻接播放验证通过。实现提交为 `ba47756d7e463abeb9377088b819a2520e150935`,恢复 tag 为 `recovery/P2-2-MPV-DV7-METADATA-CODECPAR/20260829065811-ba47756d7e46`。完整来源、哈希、验证和回滚记录见 [P2-2-mpv-dv7-metadata-codecpar.md](../docs/P2-2-mpv-dv7-metadata-codecpar.md)。 + ## 提交前验证 至少构建一个快速 Release: @@ -246,7 +253,7 @@ bash gradlew :app:assembleMobileArm64_v8aRelease -PfastRelease=true - Dolby Vision Profile 7 REMUX 在 HDR10 回退下确认日志包含 `stripping EL/RPU before decoder`,OpenGL/Vulkan/电视直出均只有基础层进入 MediaCodec、`hwdec-current=mediacodec` 且能持续出帧;系统日志不得出现端口饥饿、`connect: already connected` 或 MediaCodec `-22`。 - 电视直出/Dolby Vision 使用独立视频 Surface;启用字幕/OSD 时透明 OSD Surface 可见,关闭字幕时允许不创建额外 OSD Surface,退出或换集不死锁。 - MediaCodec 直出需检查 timestamped release 统计、输出迟到和掉帧时间;不得因立即释放缓冲帧持续提前显示,也不得把有界调度等待扩大为主线程长时间阻塞。 -- MPV 音频直通在 HDMI 功放链路分别验证 AC3、E-AC3 与 TrueHD/Atmos,确认功放能锁定格式并亮灯;E-AC3、DTS-HD、TrueHD 日志应保持 IEC61937 的 192 kHz 载波采样率,不得改写为设备常见的 48 kHz,也不得回退为 PCM。 +- MPV 音频直通在 HDMI 功放链路分别验证 AC3、E-AC3、DTS-HD HRA/MA 与 TrueHD/Atmos,确认功放能锁定格式并亮灯;E-AC3、DTS-HD、TrueHD 日志应保持 IEC61937 的 192 kHz 载波采样率。DTS-HD HRA 保持 stereo carrier,Android 12+ 的 8-channel DTS-HD MA 使用 7.1 carrier;能力探测失败时允许明确回退 PCM,但不得循环重建 AudioTrack。 - MMT/TLV、TTML/ARIB 字幕、AV3A、Blu-ray/DVD ISO、压缩包播放入口分别做功能回归。 - 文本字幕、图形字幕以及播放中切换。 - 使用缺少部分中文字形的 SSA/ASS 字幕确认可逐字回退,不出现 `□`;同时确认媒体内嵌字体仍生效。 diff --git a/third_party/mpv-native-lock.json b/third_party/mpv-native-lock.json index bee3af5a17..92d5b384c4 100644 --- a/third_party/mpv-native-lock.json +++ b/third_party/mpv-native-lock.json @@ -51,8 +51,8 @@ }, "ffmpeg": { "repo": "https://github.com/FongMi/FFmpeg.git", - "commit": "04482c8d13ac27b2a9fe93f5d388929eef8af5f4", - "version": "9.0-fongmi" + "commit": "177f090e0503b7e013922ca903bde14b1c375f18", + "version": "9.0.1-fongmi" }, "freetype2": { "repo": "https://gitlab.freedesktop.org/freetype/freetype.git", diff --git a/third_party/mpv-native-overrides/depinfo.sh b/third_party/mpv-native-overrides/depinfo.sh index b5c39f22ce..df8c452946 100755 --- a/third_party/mpv-native-overrides/depinfo.sh +++ b/third_party/mpv-native-overrides/depinfo.sh @@ -57,5 +57,5 @@ dep_rubberband=() dep_mpv=(ffmpeg libass lua libplacebo curl libbluray libiconv uchardet libarchive libdvdnav rubberband) dep_mpv_android=(mpv) -v_ci_ffmpeg=04482c8d13ac27b2a9fe93f5d388929eef8af5f4 +v_ci_ffmpeg=177f090e0503b7e013922ca903bde14b1c375f18 ci_tarball="prefix-ndk-${v_ndk}-webhtv-fongmi-ffmpeg9.tgz" diff --git a/third_party/mpv-player-jni/src/main.cpp b/third_party/mpv-player-jni/src/main.cpp index fb4fdfc9b8..c8128ff41f 100644 --- a/third_party/mpv-player-jni/src/main.cpp +++ b/third_party/mpv-player-jni/src/main.cpp @@ -170,18 +170,7 @@ jni_func(jint, destroy) { return MPV_ERROR_SUCCESS; } - if (g_shutdown_requested.exchange(true)) - return MPV_ERROR_SUCCESS; - - const char *arguments[] = {"quit", NULL}; - int result = mpv_command_async(context, 0, arguments); - if (result < 0) { - ALOGE("failed to queue asynchronous mpv shutdown: %s", - mpv_error_string(result)); - g_force_shutdown = true; - mpv_wakeup(context); - } - return MPV_ERROR_SUCCESS; + return enqueue_shutdown(env); } static int run_command(JNIEnv *env, jobjectArray jarray, uint64_t request_id) { diff --git a/third_party/mpv-player-jni/src/request.cpp b/third_party/mpv-player-jni/src/request.cpp index c22a7f4462..002132d291 100644 --- a/third_party/mpv-player-jni/src/request.cpp +++ b/third_party/mpv-player-jni/src/request.cpp @@ -19,6 +19,7 @@ enum class RequestType { VIDEO_SURFACE, OSD_SURFACE, COMMAND, + SHUTDOWN, }; static constexpr uint64_t INTERNAL_REQUEST_ID = @@ -36,6 +37,10 @@ struct MpvRequest { MpvRequest(uint64_t request_id_, std::vector command_) : type(RequestType::COMMAND), request_id(request_id_), command(std::move(command_)), surface(NULL) {} + + MpvRequest() + : type(RequestType::SHUTDOWN), request_id(INTERNAL_REQUEST_ID), + command(1, "quit"), surface(NULL) {} }; struct RequestFailure { @@ -81,9 +86,13 @@ static const char *get_surface_property(RequestType type) { return NULL; } +static bool is_command_request(RequestType type) { + return type == RequestType::COMMAND || type == RequestType::SHUTDOWN; +} + static int get_reply_event_id(const MpvRequest *request) { - return request->type == RequestType::COMMAND ? MPV_EVENT_COMMAND_REPLY - : MPV_EVENT_SET_PROPERTY_REPLY; + return is_command_request(request->type) ? MPV_EVENT_COMMAND_REPLY + : MPV_EVENT_SET_PROPERTY_REPLY; } static int start_next_request_locked(JNIEnv *env, @@ -92,14 +101,14 @@ static int start_next_request_locked(JNIEnv *env, return MPV_ERROR_SUCCESS; mpv_handle *context = g_mpv.load(); - if (!context || !g_event_thread_started || g_shutdown_requested) + if (!context || !g_event_thread_started) return MPV_ERROR_UNINITIALIZED; std::unique_ptr request = std::move(pending_requests.front()); pending_requests.pop_front(); int result; - if (request->type == RequestType::COMMAND) { + if (is_command_request(request->type)) { std::vector arguments(request->command.size() + 1, NULL); for (size_t i = 0; i < request->command.size(); ++i) arguments[i] = request->command[i].c_str(); @@ -112,13 +121,18 @@ static int start_next_request_locked(JNIEnv *env, property, MPV_FORMAT_INT64, &wid); } if (result < 0) { - const char *action = request->type == RequestType::COMMAND + const char *action = is_command_request(request->type) ? "mpv_command_async" : "mpv_set_property_async"; - const char *target = request->type == RequestType::COMMAND + const char *target = is_command_request(request->type) ? (request->command.empty() ? "" : request->command[0].c_str()) : get_surface_property(request->type); ALOGE("%s(%s) returned error %s", action, target, mpv_error_string(result)); + if (request->type == RequestType::SHUTDOWN) { + g_force_shutdown = true; + mpv_wakeup(context); + return MPV_ERROR_SUCCESS; + } if (failures && request->request_id != INTERNAL_REQUEST_ID) failures->push_back({request->request_id, result}); clear_request_surface(env, request.get()); @@ -146,6 +160,25 @@ int enqueue_command(JNIEnv *env, uint64_t request_id, return enqueue_request(env, std::move(request)); } +int enqueue_shutdown(JNIEnv *env) { + std::lock_guard lock(request_mutex); + if (!g_mpv || !g_event_thread_started) + return MPV_ERROR_UNINITIALIZED; + if (g_shutdown_requested.exchange(true)) + return MPV_ERROR_SUCCESS; + + pending_requests.push_back(std::unique_ptr(new MpvRequest())); + const int result = start_next_request_locked(env, NULL); + if (result < 0) { + mpv_handle *context = g_mpv.load(); + if (context) { + g_force_shutdown = true; + mpv_wakeup(context); + } + } + return MPV_ERROR_SUCCESS; +} + static int enqueue_surface_request(JNIEnv *env, uint64_t request_id, SurfaceTarget target, jobject surface) { jobject surface_ref = surface ? env->NewGlobalRef(surface) : NULL; @@ -216,12 +249,27 @@ void handle_request_reply(JNIEnv *env, mpv_event *event) { } void release_requests(JNIEnv *env) { - std::lock_guard lock(request_mutex); - clear_surface(env, &video_surface); - clear_surface(env, &osd_surface); - clear_request_surface(env, request_in_flight.get()); - request_in_flight.reset(); - for (const std::unique_ptr &request : pending_requests) - clear_request_surface(env, request.get()); - pending_requests.clear(); + std::vector canceled_request_ids; + { + std::lock_guard lock(request_mutex); + if (request_in_flight && + request_in_flight->request_id != INTERNAL_REQUEST_ID) { + canceled_request_ids.push_back(request_in_flight->request_id); + } + for (const std::unique_ptr &request : pending_requests) { + if (request->request_id != INTERNAL_REQUEST_ID) + canceled_request_ids.push_back(request->request_id); + } + + clear_surface(env, &video_surface); + clear_surface(env, &osd_surface); + clear_request_surface(env, request_in_flight.get()); + request_in_flight.reset(); + for (const std::unique_ptr &request : pending_requests) + clear_request_surface(env, request.get()); + pending_requests.clear(); + } + + for (uint64_t request_id : canceled_request_ids) + send_command_reply_to_java(env, request_id, MPV_ERROR_UNINITIALIZED); } diff --git a/third_party/mpv-player-jni/src/request.h b/third_party/mpv-player-jni/src/request.h index fb8983030b..b7f81de20f 100644 --- a/third_party/mpv-player-jni/src/request.h +++ b/third_party/mpv-player-jni/src/request.h @@ -17,5 +17,6 @@ int enqueue_command(JNIEnv *env, uint64_t request_id, int enqueue_surface(JNIEnv *env, SurfaceTarget target, jobject surface); int enqueue_surface_async(JNIEnv *env, uint64_t request_id, SurfaceTarget target, jobject surface); +int enqueue_shutdown(JNIEnv *env); void handle_request_reply(JNIEnv *env, mpv_event *event); void release_requests(JNIEnv *env); diff --git a/third_party/patches/libplacebo-p1-alpha.patch b/third_party/patches/libplacebo-p1-alpha.patch new file mode 100644 index 0000000000..0d66367046 --- /dev/null +++ b/third_party/patches/libplacebo-p1-alpha.patch @@ -0,0 +1,13 @@ +diff --git a/src/shaders/colorspace.c b/src/shaders/colorspace.c +index 197f819f..b91e971a 100644 +--- a/src/shaders/colorspace.c ++++ b/src/shaders/colorspace.c +@@ -1472,7 +1472,7 @@ void pl_shader_extract_features(pl_shader sh, struct pl_color_space csp) + " / (vec3(1.0) + %f * lms); \n" + "lms = pow(lms, vec3(%f)); \n" + "float I = dot(vec3(%f, %f, %f), lms); \n" +- "color = vec4(I, 0.0, 0.0, 1.0); \n" ++ "color.rgb = vec3(I, 0.0, 0.0); \n" + "} \n", + PL_COLOR_SDR_WHITE / 10000, + SH_MAT3(pl_ipt_rgb2lms(pl_raw_primaries_get(csp.primaries))), diff --git a/third_party/patches/media3-deferred-cues.patch b/third_party/patches/media3-deferred-cues.patch index 20e5e1aa4c..73799f63b4 100644 --- a/third_party/patches/media3-deferred-cues.patch +++ b/third_party/patches/media3-deferred-cues.patch @@ -1,22 +1,15 @@ diff --git a/libraries/extractor/src/main/java/androidx/media3/extractor/mkv/MatroskaExtractor.java b/libraries/extractor/src/main/java/androidx/media3/extractor/mkv/MatroskaExtractor.java -index 1b24e3d976..5af42a7caa 100644 +index 78c969e459..f48fa42592 100644 --- a/libraries/extractor/src/main/java/androidx/media3/extractor/mkv/MatroskaExtractor.java +++ b/libraries/extractor/src/main/java/androidx/media3/extractor/mkv/MatroskaExtractor.java -@@ -130,7 +130,9 @@ public class MatroskaExtractor implements Extractor { - @Target(TYPE_USE) - @IntDef( - flag = true, +@@ -82,0 +83 @@ import java.util.HashMap; ++import java.util.HashSet; +@@ -133 +134,3 @@ public class MatroskaExtractor implements Extractor { - value = {FLAG_DISABLE_SEEK_FOR_CUES, FLAG_EMIT_RAW_SUBTITLE_DATA}) + value = { + FLAG_DISABLE_SEEK_FOR_CUES, FLAG_EMIT_RAW_SUBTITLE_DATA, FLAG_DEFER_SEEK_FOR_CUES + }) - public @interface Flags {} - - /** -@@ -149,6 +151,15 @@ public class MatroskaExtractor implements Extractor { - */ - public static final int FLAG_EMIT_RAW_SUBTITLE_DATA = 1 << 1; // 2 - +@@ -151,0 +155,9 @@ public class MatroskaExtractor implements Extractor { + /** + * Flag to defer reading a tail Cues element until a non-zero seek is requested. + * @@ -26,65 +19,44 @@ index 1b24e3d976..5af42a7caa 100644 + */ + public static final int FLAG_DEFER_SEEK_FOR_CUES = 1 << 2; // 4 + - /** - * @deprecated Use {@link #newFactory(SubtitleParser.Factory)} instead. - */ -@@ -162,6 +173,7 @@ public class MatroskaExtractor implements Extractor { - private static final String TAG = "MatroskaExtractor"; - - private static final int UNSET_ENTRY_ID = -1; +@@ -164,0 +177,2 @@ public class MatroskaExtractor implements Extractor { + private static final long MIN_DEFERRED_CUES_LENGTH_BYTES = 64L * 1024L * 1024L; - - private static final int BLOCK_STATE_START = 0; - private static final int BLOCK_STATE_HEADER = 1; -@@ -477,6 +489,7 @@ public class MatroskaExtractor implements Extractor { - private final SparseArray tracks; - private final LongSparseArray chapters; - private final boolean seekForCuesEnabled; ++ private static final int MAX_DEFERRED_SEEK_HEADS = 10; +@@ -479,0 +494 @@ public class MatroskaExtractor implements Extractor { + private final boolean deferSeekForCuesEnabled; - private final boolean parseSubtitlesDuringExtraction; - private final SubtitleParser.Factory subtitleParserFactory; - private final boolean emitDolbyVisionBlockAdditionalData; -@@ -514,6 +527,11 @@ public class MatroskaExtractor implements Extractor { - - // Whether a seek map has been sent to the output. - private boolean sentSeekMap; +@@ -516,0 +532,6 @@ public class MatroskaExtractor implements Extractor { + private boolean provisionalSeekMapSent; + private boolean deferredCuesEvaluated; + private boolean deferredCuesActive; ++ private boolean deferredSeekMapResolutionFailed; + private long deferredSeekTimeUs = C.TIME_UNSET; + @Nullable private SeekMap lastSeekMap; - - // Master seek entry related elements. - private int seekEntryId; -@@ -660,6 +678,7 @@ public class MatroskaExtractor implements Extractor { - this.emitDolbyVisionBlockAdditionalData = emitDolbyVisionBlockAdditionalData; - this.perTrackCues = new SparseArray<>(); - seekForCuesEnabled = (flags & FLAG_DISABLE_SEEK_FOR_CUES) == 0; +@@ -520,0 +542,2 @@ public class MatroskaExtractor implements Extractor { ++ private final ArrayList pendingSeekHeadPositions = new ArrayList<>(); ++ private final HashSet visitedSeekHeadPositions = new HashSet<>(); +@@ -530,0 +554 @@ public class MatroskaExtractor implements Extractor { ++ private boolean seekForSeekHead; +@@ -662,0 +687 @@ public class MatroskaExtractor implements Extractor { + deferSeekForCuesEnabled = (flags & FLAG_DEFER_SEEK_FOR_CUES) != 0; - parseSubtitlesDuringExtraction = (flags & FLAG_EMIT_RAW_SUBTITLE_DATA) == 0; - varintReader = new VarintReader(); - chapters = new LongSparseArray<>(); -@@ -695,6 +714,15 @@ public class MatroskaExtractor implements Extractor { - @CallSuper - @Override - public void seek(long position, long timeUs) { +@@ -697,0 +723,17 @@ public class MatroskaExtractor implements Extractor { ++ if (!sentSeekMap && position == 0 && timeUs == 0) { ++ pendingSeekHeadPositions.clear(); ++ visitedSeekHeadPositions.clear(); ++ seekForSeekHead = false; ++ deferredSeekMapResolutionFailed = false; ++ } + if (deferSeekForCuesEnabled && !sentSeekMap && timeUs > 0) { + deferredSeekTimeUs = timeUs; + seekPositionAfterBuildingCues = + deferredCuesActive && position == cuesContentPosition ? position : C.INDEX_UNSET; ++ markPendingSeekHeadVisited(position); + } else if (timeUs == 0 || sentSeekMap) { + deferredSeekTimeUs = C.TIME_UNSET; + seekPositionAfterBuildingCues = C.INDEX_UNSET; + } + seekForCues = false; - clusterTimecodeUs = C.TIME_UNSET; - blockState = BLOCK_STATE_START; - reader.reset(); -@@ -723,6 +751,14 @@ public class MatroskaExtractor implements Extractor { - - @Override - public final int read(ExtractorInput input, PositionHolder seekPosition) throws IOException { ++ seekForSeekHead = false; +@@ -725,0 +768,8 @@ public class MatroskaExtractor implements Extractor { + if (!deferredCuesEvaluated) { + long inputLength = input.getLength(); + deferredCuesActive = @@ -93,13 +65,13 @@ index 1b24e3d976..5af42a7caa 100644 + && inputLength >= MIN_DEFERRED_CUES_LENGTH_BYTES; + deferredCuesEvaluated = true; + } - haveOutputSample = false; - boolean continueReading = true; - while (continueReading && !haveOutputSample) { -@@ -928,18 +964,8 @@ public class MatroskaExtractor implements Extractor { - case ID_CLUSTER: - if (tracksContentPosition != C.INDEX_UNSET && !readTracks) { - seekForTracks = true; +@@ -730,3 +780,2 @@ public class MatroskaExtractor implements Extractor { +- if (continueReading +- && (maybeSeekForTracks(seekPosition, input.getPosition()) +- || maybeSeekForCues(seekPosition, input.getPosition()))) { ++ if (maybeSeekForTracks(seekPosition, input.getPosition()) ++ || maybeSeekForCues(seekPosition, input.getPosition())) { +@@ -931,12 +980,2 @@ public class MatroskaExtractor implements Extractor { - } - if (!sentSeekMap) { - // We need to build cues before parsing the cluster. @@ -114,50 +86,42 @@ index 1b24e3d976..5af42a7caa 100644 - } + } else { + maybePrepareSeekMap(); - } - break; - case ID_BLOCK_GROUP: -@@ -1009,22 +1035,24 @@ public class MatroskaExtractor implements Extractor { - break; - } - } +@@ -997 +1036,3 @@ public class MatroskaExtractor implements Extractor { +- if (seekEntryId == ID_CUES) { ++ if (seekEntryId == ID_SEEK_HEAD) { ++ addPendingSeekHeadPosition(seekEntryPosition); ++ } else if (seekEntryId == ID_CUES) { +@@ -1002,0 +1044,13 @@ public class MatroskaExtractor implements Extractor { ++ case ID_SEEK_HEAD: ++ if (deferredSeekTimeUs != C.TIME_UNSET && !sentSeekMap) { ++ long deferredIndexPosition = getDeferredIndexPosition(); ++ if (cuesContentPosition != C.INDEX_UNSET ++ && deferredIndexPosition == cuesContentPosition) { ++ seekForCues = true; ++ } else if (deferredIndexPosition != C.INDEX_UNSET) { ++ seekForSeekHead = true; ++ } else { ++ deferredSeekMapResolutionFailed = true; ++ } ++ } ++ break; +@@ -1011,0 +1066 @@ public class MatroskaExtractor implements Extractor { + SeekMap seekMap; - if (!hasAnyCues || durationUs == C.TIME_UNSET) { - // Cues are missing, empty, or duration is unknown. +@@ -1014 +1069 @@ public class MatroskaExtractor implements Extractor { - extractorOutput.seekMap(new SeekMap.Unseekable(durationUs)); + seekMap = new SeekMap.Unseekable(durationUs); - } else { - for (int i = 0; i < perTrackCues.size(); i++) { - Collections.sort(perTrackCues.valueAt(i)); - } +@@ -1019 +1074 @@ public class MatroskaExtractor implements Extractor { - MatroskaSeekMap seekMap = + seekMap = - new MatroskaSeekMap( - perTrackCues, - durationUs, - primarySeekTrackNumber, - segmentContentPosition, - segmentContentSize); +@@ -1026 +1080,0 @@ public class MatroskaExtractor implements Extractor { - extractorOutput.seekMap(seekMap); - } +@@ -1027,0 +1082,2 @@ public class MatroskaExtractor implements Extractor { + checkNotNull(extractorOutput).seekMap(seekMap); + lastSeekMap = seekMap; - sentSeekMap = true; - inCuesElement = false; - for (int i = 0; i < tracks.size(); i++) { -@@ -1032,7 +1060,7 @@ public class MatroskaExtractor implements Extractor { - if (!track.waitingForDtsAnalysis) { - updateTrackFormatWithMetadata(track); - track.assertOutputInitialized(); +@@ -1035 +1091 @@ public class MatroskaExtractor implements Extractor { - track.output.format(checkNotNull(track.format)); + maybeOutputTrackFormat(track); - } - } - maybeEndTracks(); -@@ -1075,7 +1103,12 @@ public class MatroskaExtractor implements Extractor { - break; - case ID_EDITION_ENTRY: - for (int i = 0; i < tracks.size(); i++) { +@@ -1078 +1134,6 @@ public class MatroskaExtractor implements Extractor { - updateTrackFormatWithMetadata(tracks.valueAt(i)); + Track track = tracks.valueAt(i); + updateTrackFormatWithMetadata(track); @@ -165,50 +129,37 @@ index 1b24e3d976..5af42a7caa 100644 + track.assertOutputInitialized(); + maybeOutputTrackFormat(track); + } - } - break; - case ID_BLOCK_GROUP: -@@ -1189,7 +1222,7 @@ public class MatroskaExtractor implements Extractor { - if (!trackItem.waitingForDtsAnalysis) { - updateTrackFormatWithMetadata(trackItem); - trackItem.assertOutputInitialized(); +@@ -1192 +1253 @@ public class MatroskaExtractor implements Extractor { - trackItem.output.format(checkNotNull(trackItem.format)); + maybeOutputTrackFormat(trackItem); - } - } - } -@@ -1207,6 +1240,9 @@ public class MatroskaExtractor implements Extractor { - } - - readTracks = true; +@@ -1209,0 +1271,3 @@ public class MatroskaExtractor implements Extractor { + if (seekPositionAfterReadingTracks != C.INDEX_UNSET) { + maybePrepareSeekMap(); + } - if (maybeSendFormatsEarly) { - maybeEndTracks(); - } -@@ -1965,7 +2001,7 @@ public class MatroskaExtractor implements Extractor { - if (track.waitingForDtsAnalysis) { - checkNotNull(track.format); - track.format = DtsUtil.updateFormatWithDtsHdInfo(input, size, track.format); +@@ -1968 +2032 @@ public class MatroskaExtractor implements Extractor { - track.output.format(track.format); + maybeOutputTrackFormat(track); - track.waitingForDtsAnalysis = false; - maybeEndTracks(); - } -@@ -2126,7 +2162,7 @@ public class MatroskaExtractor implements Extractor { - track.trueHdAtmosAnalysisComplete = true; - if (track.trueHdSampleRechunker.isAtmos()) { - track.format = checkNotNull(track.format).buildUpon().setCodecs("atmos").build(); +@@ -2129 +2193 @@ public class MatroskaExtractor implements Extractor { - track.output.format(track.format); + maybeOutputTrackFormat(track); - } - } - } -@@ -2327,7 +2363,15 @@ public class MatroskaExtractor implements Extractor { - // After parsing Cues, seek back to original position if available. We will not do this unless - // we seeked to get to the Cues in the first place. - if (sentSeekMap && seekPositionAfterBuildingCues != C.INDEX_UNSET) { +@@ -2320,0 +2385,16 @@ public class MatroskaExtractor implements Extractor { ++ if (deferredSeekMapResolutionFailed) { ++ publishUnseekableSeekMap(); ++ deferredSeekMapResolutionFailed = false; ++ deferredSeekTimeUs = C.TIME_UNSET; ++ seekPositionAfterBuildingCues = C.INDEX_UNSET; ++ seekPosition.position = 0; ++ return true; ++ } ++ if (seekForSeekHead) { ++ long nextSeekHeadPosition = takeNextPendingSeekHeadPosition(); ++ seekForSeekHead = false; ++ if (nextSeekHeadPosition != C.INDEX_UNSET) { ++ seekPosition.position = nextSeekHeadPosition; ++ return true; ++ } ++ } +@@ -2330 +2410,9 @@ public class MatroskaExtractor implements Extractor { - seekPosition.position = seekPositionAfterBuildingCues; + if (deferredSeekTimeUs != C.TIME_UNSET && lastSeekMap != null) { + seekPosition.position = @@ -219,20 +170,15 @@ index 1b24e3d976..5af42a7caa 100644 + } else { + seekPosition.position = seekPositionAfterBuildingCues; + } - seekPositionAfterBuildingCues = C.INDEX_UNSET; - return true; - } -@@ -2420,6 +2464,45 @@ public class MatroskaExtractor implements Extractor { - checkNotNull(extractorOutput); - } - +@@ -2422,0 +2511,89 @@ public class MatroskaExtractor implements Extractor { + private void maybePrepareSeekMap() { + if (sentSeekMap) { + return; + } ++ long deferredIndexPosition = getDeferredIndexPosition(); + if (deferredCuesActive + && seekForCuesEnabled -+ && cuesContentPosition != C.INDEX_UNSET) { ++ && deferredIndexPosition != C.INDEX_UNSET) { + if (!provisionalSeekMapSent) { + for (int i = 0; i < tracks.size(); i++) { + Track track = tracks.valueAt(i); @@ -244,11 +190,15 @@ index 1b24e3d976..5af42a7caa 100644 + } + maybeEndTracks(); + checkNotNull(extractorOutput) -+ .seekMap(new DeferredSeekMap(durationUs, cuesContentPosition)); ++ .seekMap(new DeferredSeekMap(durationUs, deferredIndexPosition)); + provisionalSeekMapSent = true; + } + if (deferredSeekTimeUs != C.TIME_UNSET) { -+ seekForCues = true; ++ if (deferredIndexPosition == cuesContentPosition) { ++ seekForCues = true; ++ } else { ++ seekForSeekHead = true; ++ } + } + return; + } @@ -259,19 +209,58 @@ index 1b24e3d976..5af42a7caa 100644 + } else { + // We don't know where the Cues element is located. It's most likely omitted. Allow + // playback, but disable seeking. -+ checkNotNull(extractorOutput).seekMap(new SeekMap.Unseekable(durationUs)); -+ sentSeekMap = true; -+ lastSeekMap = new SeekMap.Unseekable(durationUs); ++ publishUnseekableSeekMap(); + } + } + - private void maybeEndTracks() { - if (!pendingEndTracks) { - return; -@@ -2442,6 +2525,15 @@ public class MatroskaExtractor implements Extractor { - perTrackCues, durationUs, segmentContentPosition, segmentContentSize); - } - ++ private void addPendingSeekHeadPosition(long position) { ++ if (!deferSeekForCuesEnabled ++ || segmentContentPosition == C.INDEX_UNSET ++ || position <= segmentContentPosition ++ || (segmentContentSize != C.LENGTH_UNSET ++ && position - segmentContentPosition >= segmentContentSize) ++ || visitedSeekHeadPositions.contains(position) ++ || pendingSeekHeadPositions.contains(position) ++ || visitedSeekHeadPositions.size() + pendingSeekHeadPositions.size() ++ >= MAX_DEFERRED_SEEK_HEADS) { ++ return; ++ } ++ pendingSeekHeadPositions.add(position); ++ } ++ ++ private long getDeferredIndexPosition() { ++ if (cuesContentPosition != C.INDEX_UNSET) { ++ return cuesContentPosition; ++ } ++ return pendingSeekHeadPositions.isEmpty() ++ ? C.INDEX_UNSET ++ : pendingSeekHeadPositions.get(pendingSeekHeadPositions.size() - 1); ++ } ++ ++ private long takeNextPendingSeekHeadPosition() { ++ if (pendingSeekHeadPositions.isEmpty()) { ++ return C.INDEX_UNSET; ++ } ++ int lastIndex = pendingSeekHeadPositions.size() - 1; ++ long position = pendingSeekHeadPositions.remove(lastIndex); ++ visitedSeekHeadPositions.add(position); ++ return position; ++ } ++ ++ private void markPendingSeekHeadVisited(long position) { ++ if (pendingSeekHeadPositions.remove(Long.valueOf(position))) { ++ visitedSeekHeadPositions.add(position); ++ } ++ } ++ ++ private void publishUnseekableSeekMap() { ++ SeekMap seekMap = new SeekMap.Unseekable(durationUs); ++ checkNotNull(extractorOutput).seekMap(seekMap); ++ sentSeekMap = true; ++ lastSeekMap = seekMap; ++ } ++ +@@ -2444,0 +2622,9 @@ public class MatroskaExtractor implements Extractor { + @RequiresNonNull("#1.output") + private static void maybeOutputTrackFormat(Track track) { + Format format = checkNotNull(track.format); @@ -281,21 +270,15 @@ index 1b24e3d976..5af42a7caa 100644 + } + } + - /** Passes events through to the outer {@link MatroskaExtractor}. */ - private final class InnerEbmlProcessor implements EbmlProcessor { - -@@ -2588,6 +2680,7 @@ public class MatroskaExtractor implements Extractor { - // Set when the output is initialized. nalUnitLengthFieldLength is only set for H264/H265. - public @MonotonicNonNull TrackOutput output; - public @MonotonicNonNull Format format; +@@ -2512,0 +2699,2 @@ public class MatroskaExtractor implements Extractor { ++ // CTA-861.3 stores minimum mastering luminance in units of 0.0001 cd/m2. ++ private static final int MIN_MASTERING_LUMINANCE_SCALE = 10_000; +@@ -2590,0 +2779 @@ public class MatroskaExtractor implements Extractor { + @Nullable public Format lastOutputFormat; - public int nalUnitLengthFieldLength; - - /** Builds the {@link Format} for the track. */ -@@ -3309,6 +3402,34 @@ public class MatroskaExtractor implements Extractor { - } - } - +@@ -2605,2 +2793,0 @@ public class MatroskaExtractor implements Extractor { +- // CTA-861.3 stores minimum mastering luminance in units of 0.0001 cd/m2. +- private static final int MIN_MASTERING_LUMINANCE_SCALE = 10_000; +@@ -3314,0 +3502,28 @@ public class MatroskaExtractor implements Extractor { + private static final class DeferredSeekMap implements SeekMap { + + private final long durationUs; @@ -324,42 +307,41 @@ index 1b24e3d976..5af42a7caa 100644 + } + } + - private static final class MatroskaSeekMap implements TrackAwareSeekMap, ChunkIndexProvider { - - @Nullable private final ChunkIndex chunkIndex; diff --git a/libraries/extractor/src/test/java/androidx/media3/extractor/mkv/MatroskaExtractorNonParameterizedTest.java b/libraries/extractor/src/test/java/androidx/media3/extractor/mkv/MatroskaExtractorNonParameterizedTest.java -index 5df042682b..2c913b32ce 100644 +index f3e9309f08..ef004d2e7a 100644 --- a/libraries/extractor/src/test/java/androidx/media3/extractor/mkv/MatroskaExtractorNonParameterizedTest.java +++ b/libraries/extractor/src/test/java/androidx/media3/extractor/mkv/MatroskaExtractorNonParameterizedTest.java -@@ -18,12 +18,15 @@ package androidx.media3.extractor.mkv; - import static androidx.media3.extractor.Extractor.RESULT_SEEK; - import static com.google.common.truth.Truth.assertThat; - +@@ -21,0 +22 @@ import static com.google.common.truth.Truth.assertThat; +import androidx.media3.extractor.ForwardingExtractorInput; - import androidx.media3.extractor.PositionHolder; +@@ -22,0 +24 @@ import androidx.media3.extractor.PositionHolder; +import androidx.media3.extractor.SeekMap; - import androidx.media3.extractor.SeekPoint; - import androidx.media3.extractor.TrackAwareSeekMap; - import androidx.media3.extractor.text.SubtitleParser; - import androidx.media3.test.utils.FakeExtractorInput; - import androidx.media3.test.utils.FakeExtractorOutput; +@@ -27,0 +30 @@ import androidx.media3.test.utils.FakeExtractorOutput; +import androidx.media3.test.utils.FakeTrackOutput; - import androidx.media3.test.utils.TestUtil; - import androidx.test.core.app.ApplicationProvider; - import androidx.test.ext.junit.runners.AndroidJUnit4; -@@ -34,6 +37,8 @@ import org.junit.runner.RunWith; - @RunWith(AndroidJUnit4.class) - public class MatroskaExtractorNonParameterizedTest { - +@@ -30,0 +34,5 @@ import androidx.test.ext.junit.runners.AndroidJUnit4; ++import java.nio.ByteBuffer; ++import java.nio.ByteOrder; ++import java.util.ArrayList; ++import java.util.Arrays; ++import java.util.List; +@@ -34,2 +41,0 @@ import org.junit.runner.RunWith; +-import java.nio.ByteBuffer; +-import java.nio.ByteOrder; +@@ -41,3 +46,0 @@ public class MatroskaExtractorNonParameterizedTest { +- public void seek_afterSeekMapSent_seekMapRemainsValid() throws Exception { +- String fileName = "media/mkv/sample.mkv"; +- @Test +@@ -79,0 +83,10 @@ public class MatroskaExtractorNonParameterizedTest { + private static final long LARGE_INPUT_LENGTH_BYTES = 64L * 1024L * 1024L; ++ private static final int SEGMENT_CONTENT_POSITION = 52; ++ private static final int ROOT_CUES_ID_POSITION = 93; ++ private static final int ROOT_CUES_SEEK_POSITION = 100; ++ private static final int NESTED_SEEK_HEAD_POSITION = 100_000; ++ private static final int CUES_POSITION = 107_445; + - @Test - public void seek_afterSeekMapSent_seekMapRemainsValid() throws Exception { - String fileName = "media/mkv/sample.mkv"; -@@ -67,4 +72,79 @@ public class MatroskaExtractorNonParameterizedTest { - assertThat(trackAwareSeekMap.getSeekPoints(timeStampUs, videoTrackId).first) - .isEqualTo(expectedTrackSpecificSeekPoint); - } ++ @Test ++ public void seek_afterSeekMapSent_seekMapRemainsValid() throws Exception { ++ String fileName = "media/mkv/sample.mkv"; +@@ -109,0 +123,216 @@ public class MatroskaExtractorNonParameterizedTest { + + @Test + public void tracksAfterClusters_buildsSeekableMap() throws Exception { @@ -435,4 +417,144 @@ index 5df042682b..2c913b32ce 100644 + assertThat(output.seekMap.isSeekable()).isTrue(); + assertThat(output.seekMap.getSeekPoints(targetTimeUs).first.position).isGreaterThan(0); + } - } ++ ++ @Test ++ public void deferredCues_chainedSeekHead_resolvesCuesOnlyAfterNonZeroSeek() throws Exception { ++ byte[] fileBytes = createChainedSeekHeadSample(/* nestedSeekHeadPointsToCues= */ true); ++ MatroskaExtractor extractor = createDeferredExtractor(); ++ FakeExtractorOutput output = createDeduplicatingOutput(); ++ extractor.init(output); ++ FakeExtractorInput delegateInput = ++ new FakeExtractorInput.Builder().setData(fileBytes).build(); ++ ForwardingExtractorInput input = largeInput(delegateInput); ++ PositionHolder positionHolder = new PositionHolder(); ++ extractor.seek(/* position= */ 0, /* timeUs= */ 0); ++ ++ while (output.seekMap == null) { ++ assertThat(extractor.read(input, positionHolder)).isNotEqualTo(RESULT_SEEK); ++ } ++ ++ SeekMap provisionalSeekMap = output.seekMap; ++ long targetTimeUs = provisionalSeekMap.getDurationUs() / 2; ++ SeekPoint provisionalSeekPoint = provisionalSeekMap.getSeekPoints(targetTimeUs).first; ++ assertThat(provisionalSeekPoint.position).isEqualTo(NESTED_SEEK_HEAD_POSITION); ++ ++ extractor.seek(provisionalSeekPoint.position, targetTimeUs); ++ delegateInput.setPosition((int) provisionalSeekPoint.position); ++ List requestedPositions = new ArrayList<>(); ++ while (output.seekMap == provisionalSeekMap) { ++ int readResult = extractor.read(input, positionHolder); ++ if (readResult == RESULT_SEEK) { ++ requestedPositions.add(positionHolder.position); ++ delegateInput.setPosition((int) positionHolder.position); ++ } ++ } ++ ++ assertThat(requestedPositions.get(0)).isEqualTo(CUES_POSITION); ++ assertThat(output.seekMap).isInstanceOf(TrackAwareSeekMap.class); ++ assertThat(output.seekMap.isSeekable()).isTrue(); ++ assertThat(output.seekMap.getSeekPoints(targetTimeUs).first.position).isGreaterThan(0); ++ } ++ ++ @Test ++ public void deferredCues_cyclicSeekHead_fallsBackToUnseekableWithoutLooping() throws Exception { ++ byte[] fileBytes = createChainedSeekHeadSample(/* nestedSeekHeadPointsToCues= */ false); ++ MatroskaExtractor extractor = createDeferredExtractor(); ++ FakeExtractorOutput output = createDeduplicatingOutput(); ++ extractor.init(output); ++ FakeExtractorInput delegateInput = ++ new FakeExtractorInput.Builder().setData(fileBytes).build(); ++ ForwardingExtractorInput input = largeInput(delegateInput); ++ PositionHolder positionHolder = new PositionHolder(); ++ extractor.seek(/* position= */ 0, /* timeUs= */ 0); ++ ++ while (output.seekMap == null) { ++ assertThat(extractor.read(input, positionHolder)).isNotEqualTo(RESULT_SEEK); ++ } ++ ++ SeekMap provisionalSeekMap = output.seekMap; ++ long targetTimeUs = provisionalSeekMap.getDurationUs() / 2; ++ SeekPoint provisionalSeekPoint = provisionalSeekMap.getSeekPoints(targetTimeUs).first; ++ extractor.seek(provisionalSeekPoint.position, targetTimeUs); ++ delegateInput.setPosition((int) provisionalSeekPoint.position); ++ ++ int seekCount = 0; ++ while (output.seekMap == provisionalSeekMap && seekCount < 10) { ++ if (extractor.read(input, positionHolder) == RESULT_SEEK) { ++ seekCount++; ++ delegateInput.setPosition((int) positionHolder.position); ++ } ++ } ++ ++ assertThat(seekCount).isEqualTo(1); ++ assertThat(positionHolder.position).isEqualTo(0); ++ assertThat(output.seekMap.isSeekable()).isFalse(); ++ } ++ ++ private static MatroskaExtractor createDeferredExtractor() { ++ return new MatroskaExtractor( ++ SubtitleParser.Factory.UNSUPPORTED, MatroskaExtractor.FLAG_DEFER_SEEK_FOR_CUES); ++ } ++ ++ private static FakeExtractorOutput createDeduplicatingOutput() { ++ return new FakeExtractorOutput( ++ (id, type) -> new FakeTrackOutput(type, /* deduplicateConsecutiveFormats= */ true)); ++ } ++ ++ private static ForwardingExtractorInput largeInput(FakeExtractorInput delegateInput) { ++ return new ForwardingExtractorInput(delegateInput) { ++ @Override ++ public long getLength() { ++ return LARGE_INPUT_LENGTH_BYTES; ++ } ++ }; ++ } ++ ++ private static byte[] createChainedSeekHeadSample(boolean nestedSeekHeadPointsToCues) ++ throws Exception { ++ byte[] fileBytes = ++ Arrays.copyOf( ++ TestUtil.getByteArray( ++ ApplicationProvider.getApplicationContext(), "media/mkv/sample.mkv"), ++ CUES_POSITION + 64); ++ byte[] nestedElementId = ++ nestedSeekHeadPointsToCues ++ ? new byte[] {0x1c, 0x53, (byte) 0xbb, 0x6b} ++ : new byte[] {0x11, 0x4d, (byte) 0x9b, 0x74}; ++ int nestedTargetPosition = ++ nestedSeekHeadPointsToCues ? CUES_POSITION : NESTED_SEEK_HEAD_POSITION; ++ ++ System.arraycopy( ++ new byte[] {0x11, 0x4d, (byte) 0x9b, 0x74}, ++ 0, ++ fileBytes, ++ ROOT_CUES_ID_POSITION, ++ 4); ++ writeUnsignedInt24( ++ fileBytes, ++ ROOT_CUES_SEEK_POSITION, ++ NESTED_SEEK_HEAD_POSITION - SEGMENT_CONTENT_POSITION); ++ ++ byte[] nestedSeekHead = ++ new byte[] { ++ 0x11, 0x4d, (byte) 0x9b, 0x74, (byte) 0x8f, ++ 0x4d, (byte) 0xbb, (byte) 0x8d, ++ 0x53, (byte) 0xab, (byte) 0x84, ++ nestedElementId[0], nestedElementId[1], nestedElementId[2], nestedElementId[3], ++ 0x53, (byte) 0xac, (byte) 0x83, ++ 0, 0, 0 ++ }; ++ writeUnsignedInt24( ++ nestedSeekHead, ++ nestedSeekHead.length - 3, ++ nestedTargetPosition - SEGMENT_CONTENT_POSITION); ++ System.arraycopy( ++ nestedSeekHead, 0, fileBytes, NESTED_SEEK_HEAD_POSITION, nestedSeekHead.length); ++ return fileBytes; ++ } ++ ++ private static void writeUnsignedInt24(byte[] data, int offset, int value) { ++ data[offset] = (byte) (value >> 16); ++ data[offset + 1] = (byte) (value >> 8); ++ data[offset + 2] = (byte) value; ++ } diff --git a/third_party/patches/media3-exo-bounded-cache-writer.patch b/third_party/patches/media3-exo-bounded-cache-writer.patch new file mode 100644 index 0000000000..75cacfdd28 --- /dev/null +++ b/third_party/patches/media3-exo-bounded-cache-writer.patch @@ -0,0 +1,76 @@ +diff --git a/libraries/datasource/src/main/java/androidx/media3/datasource/cache/CacheWriter.java b/libraries/datasource/src/main/java/androidx/media3/datasource/cache/CacheWriter.java +index 61a4aa3d99..2b31e216b4 100644 +--- a/libraries/datasource/src/main/java/androidx/media3/datasource/cache/CacheWriter.java ++++ b/libraries/datasource/src/main/java/androidx/media3/datasource/cache/CacheWriter.java +@@ -181 +181 @@ public final class CacheWriter { +- int totalBytesRead = 0; ++ long totalBytesRead = 0; +@@ -184 +184,3 @@ public final class CacheWriter { +- onRequestEndPosition(position + resolvedLength); ++ onRequestEndPosition( ++ position ++ + (length == C.LENGTH_UNSET ? resolvedLength : Math.min(resolvedLength, length))); +@@ -187 +189,2 @@ public final class CacheWriter { +- while (bytesRead != C.RESULT_END_OF_INPUT) { ++ while (bytesRead != C.RESULT_END_OF_INPUT ++ && (length == C.LENGTH_UNSET || totalBytesRead < length)) { +@@ -189 +192,5 @@ public final class CacheWriter { +- bytesRead = dataSource.read(temporaryBuffer, /* offset= */ 0, temporaryBuffer.length); ++ int bytesToRead = ++ length == C.LENGTH_UNSET ++ ? temporaryBuffer.length ++ : (int) Math.min((long) temporaryBuffer.length, length - totalBytesRead); ++ bytesRead = dataSource.read(temporaryBuffer, /* offset= */ 0, bytesToRead); +diff --git a/libraries/datasource/src/test/java/androidx/media3/datasource/cache/CacheWriterTest.java b/libraries/datasource/src/test/java/androidx/media3/datasource/cache/CacheWriterTest.java +index 2becd3c7bb..5408a9f4d7 100644 +--- a/libraries/datasource/src/test/java/androidx/media3/datasource/cache/CacheWriterTest.java ++++ b/libraries/datasource/src/test/java/androidx/media3/datasource/cache/CacheWriterTest.java +@@ -104,0 +105,47 @@ public final class CacheWriterTest { ++ @Test ++ public void cache_dataSourceIgnoresBoundedLength_stopsAtRequestedLength() throws Exception { ++ FakeDataSet fakeDataSet = new FakeDataSet().setRandomData("test_data", 100); ++ FakeDataSource delegate = new FakeDataSource(fakeDataSet); ++ DataSource dataSource = ++ new DataSource() { ++ @Override ++ public void addTransferListener(TransferListener transferListener) { ++ delegate.addTransferListener(transferListener); ++ } ++ ++ @Override ++ public long open(DataSpec dataSpec) throws IOException { ++ return delegate.open(dataSpec.buildUpon().setLength(C.LENGTH_UNSET).build()); ++ } ++ ++ @Override ++ public int read(byte[] buffer, int offset, int length) throws IOException { ++ return delegate.read(buffer, offset, length); ++ } ++ ++ @Override ++ public Uri getUri() { ++ return delegate.getUri(); ++ } ++ ++ @Override ++ public void close() throws IOException { ++ delegate.close(); ++ } ++ }; ++ DataSpec dataSpec = new DataSpec(Uri.parse("test_data"), /* position= */ 10, /* length= */ 20); ++ CachingCounters counters = new CachingCounters(); ++ ++ CacheWriter cacheWriter = ++ new CacheWriter( ++ new CacheDataSource(cache, dataSource), ++ dataSpec, ++ /* temporaryBuffer= */ new byte[7], ++ counters); ++ cacheWriter.cache(); ++ ++ counters.assertValues(0, 20, 20); ++ assertThat(cache.getCachedBytes("test_data", /* position= */ 0, /* length= */ 100)) ++ .isEqualTo(20); ++ } ++ + diff --git a/third_party/patches/media3-exo-cue-data-contract.patch b/third_party/patches/media3-exo-cue-data-contract.patch new file mode 100644 index 0000000000..074da26bf4 --- /dev/null +++ b/third_party/patches/media3-exo-cue-data-contract.patch @@ -0,0 +1,594 @@ +diff --git a/libraries/common/src/main/java/androidx/media3/common/text/Cue.java b/libraries/common/src/main/java/androidx/media3/common/text/Cue.java +index 475eeefe38..74e808c45f 100644 +--- a/libraries/common/src/main/java/androidx/media3/common/text/Cue.java ++++ b/libraries/common/src/main/java/androidx/media3/common/text/Cue.java +@@ -164,6 +164,23 @@ public final class Cue { + /** Vertical left-to-right (e.g. for Mongolian). */ + public static final int VERTICAL_TYPE_LR = 2; + ++ /** The collision avoidance behavior for this cue. */ ++ @Documented ++ @Retention(RetentionPolicy.SOURCE) ++ @Target({FIELD, METHOD, PARAMETER, LOCAL_VARIABLE, TYPE_USE}) ++ @IntDef({COLLISION_AVOIDANCE_NONE, COLLISION_AVOIDANCE_UP, COLLISION_AVOIDANCE_DOWN}) ++ @UnstableApi ++ public @interface CollisionAvoidance {} ++ ++ /** Do not move this cue to avoid collisions. */ ++ @UnstableApi public static final int COLLISION_AVOIDANCE_NONE = 0; ++ ++ /** Move this cue upward by the minimum distance needed to avoid collisions. */ ++ @UnstableApi public static final int COLLISION_AVOIDANCE_UP = 1; ++ ++ /** Move this cue downward by the minimum distance needed to avoid collisions. */ ++ @UnstableApi public static final int COLLISION_AVOIDANCE_DOWN = 2; ++ + /** + * The cue text, or null if this is an image cue. Note the {@link CharSequence} may be decorated + * with styling spans. +@@ -280,6 +297,15 @@ public final class Cue { + */ + public final float bitmapHeight; + ++ /** ++ * The height of the text region as a fraction of the viewport size, or {@link #DIMEN_UNSET} if ++ * unavailable. ++ * ++ *

This describes authored layout metadata. Renderers may still size the cue box to its text ++ * content. ++ */ ++ @UnstableApi public final float textRegionHeight; ++ + /** Specifies whether or not the {@link #windowColor} property is set. */ + public final boolean windowColorSet; + +@@ -313,6 +339,9 @@ public final class Cue { + /** The Z index for cue, the larger index will render above the smaller index. May be negative. */ + @UnstableApi public final int zIndex; + ++ /** The collision avoidance behavior for this cue. */ ++ @UnstableApi public final @CollisionAvoidance int collisionAvoidance; ++ + private Cue( + @Nullable CharSequence text, + @Nullable Alignment textAlignment, +@@ -327,11 +356,13 @@ public final class Cue { + float textSize, + float size, + float bitmapHeight, ++ float textRegionHeight, + boolean windowColorSet, + int windowColor, + @VerticalType int verticalType, + float shearDegrees, +- int zIndex) { ++ int zIndex, ++ @CollisionAvoidance int collisionAvoidance) { + // Exactly one of text or bitmap should be set. + if (text == null) { + checkNotNull(bitmap); +@@ -355,6 +386,7 @@ public final class Cue { + this.positionAnchor = positionAnchor; + this.size = size; + this.bitmapHeight = bitmapHeight; ++ this.textRegionHeight = textRegionHeight; + this.windowColorSet = windowColorSet; + this.windowColor = windowColor; + this.textSizeType = textSizeType; +@@ -362,6 +394,7 @@ public final class Cue { + this.verticalType = verticalType; + this.shearDegrees = shearDegrees; + this.zIndex = zIndex; ++ this.collisionAvoidance = collisionAvoidance; + } + + /** Returns a new {@link Cue.Builder} initialized with the same values as this Cue. */ +@@ -392,13 +425,15 @@ public final class Cue { + && positionAnchor == that.positionAnchor + && size == that.size + && bitmapHeight == that.bitmapHeight ++ && textRegionHeight == that.textRegionHeight + && windowColorSet == that.windowColorSet + && windowColor == that.windowColor + && textSizeType == that.textSizeType + && textSize == that.textSize + && verticalType == that.verticalType + && shearDegrees == that.shearDegrees +- && zIndex == that.zIndex; ++ && zIndex == that.zIndex ++ && collisionAvoidance == that.collisionAvoidance; + } + + @Override +@@ -415,13 +450,15 @@ public final class Cue { + positionAnchor, + size, + bitmapHeight, ++ textRegionHeight, + windowColorSet, + windowColor, + textSizeType, + textSize, + verticalType, + shearDegrees, +- zIndex); ++ zIndex, ++ collisionAvoidance); + } + + /** A builder for {@link Cue} objects. */ +@@ -440,11 +477,13 @@ public final class Cue { + private float textSize; + private float size; + private float bitmapHeight; ++ private float textRegionHeight; + private boolean windowColorSet; + @ColorInt private int windowColor; + private @VerticalType int verticalType; + private float shearDegrees; + private int zIndex; ++ private @CollisionAvoidance int collisionAvoidance; + + public Builder() { + text = null; +@@ -460,9 +499,11 @@ public final class Cue { + textSize = DIMEN_UNSET; + size = DIMEN_UNSET; + bitmapHeight = DIMEN_UNSET; ++ textRegionHeight = DIMEN_UNSET; + windowColorSet = false; + windowColor = Color.BLACK; + verticalType = TYPE_UNSET; ++ collisionAvoidance = COLLISION_AVOIDANCE_NONE; + } + + private Builder(Cue cue) { +@@ -479,11 +520,13 @@ public final class Cue { + textSize = cue.textSize; + size = cue.size; + bitmapHeight = cue.bitmapHeight; ++ textRegionHeight = cue.textRegionHeight; + windowColorSet = cue.windowColorSet; + windowColor = cue.windowColor; + verticalType = cue.verticalType; + shearDegrees = cue.shearDegrees; + zIndex = cue.zIndex; ++ collisionAvoidance = cue.collisionAvoidance; + } + + /** +@@ -752,6 +795,27 @@ public final class Cue { + return bitmapHeight; + } + ++ /** ++ * Sets the height of the text region as a fraction of the viewport size. ++ * ++ * @see Cue#textRegionHeight ++ */ ++ @CanIgnoreReturnValue ++ public Builder setTextRegionHeight(float textRegionHeight) { ++ this.textRegionHeight = textRegionHeight; ++ return this; ++ } ++ ++ /** ++ * Gets the height of the text region as a fraction of the viewport size. ++ * ++ * @see Cue#textRegionHeight ++ */ ++ @Pure ++ public float getTextRegionHeight() { ++ return textRegionHeight; ++ } ++ + /** + * Sets the fill color of the window. + * +@@ -835,6 +899,19 @@ public final class Cue { + return zIndex; + } + ++ /** Sets the collision avoidance behavior for this Cue. */ ++ @CanIgnoreReturnValue ++ public Builder setCollisionAvoidance(@CollisionAvoidance int collisionAvoidance) { ++ this.collisionAvoidance = collisionAvoidance; ++ return this; ++ } ++ ++ /** Gets the collision avoidance behavior for this Cue. */ ++ @Pure ++ public @CollisionAvoidance int getCollisionAvoidance() { ++ return collisionAvoidance; ++ } ++ + /** Build the cue. */ + public Cue build() { + return new Cue( +@@ -851,11 +928,13 @@ public final class Cue { + textSize, + size, + bitmapHeight, ++ textRegionHeight, + windowColorSet, + windowColor, + verticalType, + shearDegrees, +- zIndex); ++ zIndex, ++ collisionAvoidance); + } + } + +@@ -879,6 +958,8 @@ public final class Cue { + private static final String FIELD_VERTICAL_TYPE = Util.intToStringMaxRadix(15); + private static final String FIELD_SHEAR_DEGREES = Util.intToStringMaxRadix(16); + private static final String FIELD_Z_INDEX = Util.intToStringMaxRadix(19); ++ private static final String FIELD_COLLISION_AVOIDANCE = Util.intToStringMaxRadix(20); ++ private static final String FIELD_TEXT_REGION_HEIGHT = Util.intToStringMaxRadix(21); + + /** + * Returns a {@link Bundle} that can be serialized to bytes. +@@ -950,11 +1031,13 @@ public final class Cue { + bundle.putFloat(FIELD_TEXT_SIZE, textSize); + bundle.putFloat(FIELD_SIZE, size); + bundle.putFloat(FIELD_BITMAP_HEIGHT, bitmapHeight); ++ bundle.putFloat(FIELD_TEXT_REGION_HEIGHT, textRegionHeight); + bundle.putBoolean(FIELD_WINDOW_COLOR_SET, windowColorSet); + bundle.putInt(FIELD_WINDOW_COLOR, windowColor); + bundle.putInt(FIELD_VERTICAL_TYPE, verticalType); + bundle.putFloat(FIELD_SHEAR_DEGREES, shearDegrees); + bundle.putInt(FIELD_Z_INDEX, zIndex); ++ bundle.putInt(FIELD_COLLISION_AVOIDANCE, collisionAvoidance); + return bundle; + } + +@@ -1015,6 +1098,9 @@ public final class Cue { + if (bundle.containsKey(FIELD_BITMAP_HEIGHT)) { + builder.setBitmapHeight(bundle.getFloat(FIELD_BITMAP_HEIGHT)); + } ++ if (bundle.containsKey(FIELD_TEXT_REGION_HEIGHT)) { ++ builder.setTextRegionHeight(bundle.getFloat(FIELD_TEXT_REGION_HEIGHT)); ++ } + if (bundle.containsKey(FIELD_WINDOW_COLOR)) { + builder.setWindowColor(bundle.getInt(FIELD_WINDOW_COLOR)); + } +@@ -1030,6 +1116,9 @@ public final class Cue { + if (bundle.containsKey(FIELD_Z_INDEX)) { + builder.setZIndex(bundle.getInt(FIELD_Z_INDEX)); + } ++ if (bundle.containsKey(FIELD_COLLISION_AVOIDANCE)) { ++ builder.setCollisionAvoidance(bundle.getInt(FIELD_COLLISION_AVOIDANCE)); ++ } + return builder.build(); + } + } +diff --git a/libraries/common/src/main/java/androidx/media3/common/text/CustomSpanBundler.java b/libraries/common/src/main/java/androidx/media3/common/text/CustomSpanBundler.java +index 31292eeb14..cc6d1c5524 100644 +--- a/libraries/common/src/main/java/androidx/media3/common/text/CustomSpanBundler.java ++++ b/libraries/common/src/main/java/androidx/media3/common/text/CustomSpanBundler.java +@@ -46,7 +46,14 @@ import java.util.ArrayList; + @Documented + @Retention(RetentionPolicy.SOURCE) + @Target({TYPE_USE}) +- @IntDef({UNKNOWN, RUBY, TEXT_EMPHASIS, HORIZONTAL_TEXT_IN_VERTICAL_CONTEXT, VOICE}) ++ @IntDef({ ++ UNKNOWN, ++ RUBY, ++ TEXT_EMPHASIS, ++ HORIZONTAL_TEXT_IN_VERTICAL_CONTEXT, ++ VOICE, ++ LETTER_SPACING ++ }) + private @interface CustomSpanType {} + + private static final int UNKNOWN = -1; +@@ -59,6 +66,8 @@ import java.util.ArrayList; + + private static final int VOICE = 4; + ++ private static final int LETTER_SPACING = 5; ++ + private static final String FIELD_START_INDEX = Util.intToStringMaxRadix(0); + private static final String FIELD_END_INDEX = Util.intToStringMaxRadix(1); + private static final String FIELD_FLAGS = Util.intToStringMaxRadix(2); +@@ -89,6 +98,12 @@ import java.util.ArrayList; + spanToBundle(text, span, /* spanType= */ VOICE, /* params= */ span.toBundle()); + bundledCustomSpans.add(bundle); + } ++ for (LetterSpacingSpan span : text.getSpans(0, text.length(), LetterSpacingSpan.class)) { ++ Bundle bundle = ++ spanToBundle( ++ text, span, /* spanType= */ LETTER_SPACING, /* params= */ span.toBundle()); ++ bundledCustomSpans.add(bundle); ++ } + return bundledCustomSpans; + } + +@@ -111,6 +126,9 @@ import java.util.ArrayList; + case VOICE: + text.setSpan(VoiceSpan.fromBundle(checkNotNull(span)), start, end, flags); + break; ++ case LETTER_SPACING: ++ text.setSpan(LetterSpacingSpan.fromBundle(checkNotNull(span)), start, end, flags); ++ break; + default: + break; + } +diff --git a/libraries/common/src/main/java/androidx/media3/common/text/LetterSpacingSpan.java b/libraries/common/src/main/java/androidx/media3/common/text/LetterSpacingSpan.java +new file mode 100644 +index 0000000000..e988244520 +--- /dev/null ++++ b/libraries/common/src/main/java/androidx/media3/common/text/LetterSpacingSpan.java +@@ -0,0 +1,86 @@ ++/* ++ * Copyright 2026 The Android Open Source Project ++ * ++ * Licensed under the Apache License, Version 2.0 (the "License"); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an "AS IS" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package androidx.media3.common.text; ++ ++import android.os.Bundle; ++import android.text.TextPaint; ++import android.text.style.MetricAffectingSpan; ++import androidx.media3.common.util.UnstableApi; ++import androidx.media3.common.util.Util; ++ ++/** A span that adds space between characters in pixels or em. */ ++@UnstableApi ++public final class LetterSpacingSpan extends MetricAffectingSpan { ++ ++ private static final String FIELD_LETTER_SPACING_PIXELS = Util.intToStringMaxRadix(0); ++ private static final String FIELD_LETTER_SPACING_EM = Util.intToStringMaxRadix(1); ++ ++ /** The extra spacing between characters in pixels, or {@link Float#NaN} if specified in em. */ ++ public final float letterSpacingPixels; ++ ++ private final float letterSpacingEm; ++ ++ public LetterSpacingSpan(float letterSpacingPixels) { ++ this(letterSpacingPixels, Float.NaN); ++ } ++ ++ private LetterSpacingSpan(float letterSpacingPixels, float letterSpacingEm) { ++ this.letterSpacingPixels = letterSpacingPixels; ++ this.letterSpacingEm = letterSpacingEm; ++ } ++ ++ /** Creates a span with extra spacing measured in em. */ ++ public static LetterSpacingSpan createFromEm(float letterSpacingEm) { ++ return new LetterSpacingSpan(Float.NaN, letterSpacingEm); ++ } ++ ++ @Override ++ public void updateDrawState(TextPaint textPaint) { ++ apply(textPaint); ++ } ++ ++ @Override ++ public void updateMeasureState(TextPaint textPaint) { ++ apply(textPaint); ++ } ++ ++ public Bundle toBundle() { ++ Bundle bundle = new Bundle(); ++ if (Float.isNaN(letterSpacingEm)) { ++ bundle.putFloat(FIELD_LETTER_SPACING_PIXELS, letterSpacingPixels); ++ } else { ++ bundle.putFloat(FIELD_LETTER_SPACING_EM, letterSpacingEm); ++ } ++ return bundle; ++ } ++ ++ public static LetterSpacingSpan fromBundle(Bundle bundle) { ++ return bundle.containsKey(FIELD_LETTER_SPACING_EM) ++ ? createFromEm(bundle.getFloat(FIELD_LETTER_SPACING_EM)) ++ : new LetterSpacingSpan(bundle.getFloat(FIELD_LETTER_SPACING_PIXELS)); ++ } ++ ++ private void apply(TextPaint textPaint) { ++ if (!Float.isNaN(letterSpacingEm)) { ++ textPaint.setLetterSpacing(letterSpacingEm); ++ return; ++ } ++ float textSize = textPaint.getTextSize(); ++ if (textSize > 0) { ++ textPaint.setLetterSpacing(letterSpacingPixels / textSize); ++ } ++ } ++} +diff --git a/libraries/common/src/test/java/androidx/media3/common/text/CueTest.java b/libraries/common/src/test/java/androidx/media3/common/text/CueTest.java +index 0850ebf10c..627be8380b 100644 +--- a/libraries/common/src/test/java/androidx/media3/common/text/CueTest.java ++++ b/libraries/common/src/test/java/androidx/media3/common/text/CueTest.java +@@ -21,6 +21,7 @@ import static org.junit.Assert.assertThrows; + + import android.graphics.Bitmap; + import android.graphics.Color; ++import android.os.Bundle; + import android.text.Layout; + import android.text.SpannedString; + import androidx.test.ext.junit.runners.AndroidJUnit4; +@@ -47,6 +48,8 @@ public class CueTest { + .setWindowColor(Color.CYAN) + .setVerticalType(Cue.VERTICAL_TYPE_RL) + .setShearDegrees(-15f) ++ .setTextRegionHeight(0.6f) ++ .setCollisionAvoidance(Cue.COLLISION_AVOIDANCE_DOWN) + .build(); + + Cue modifiedCue = cue.buildUpon().build(); +@@ -65,6 +68,8 @@ public class CueTest { + assertThat(cue.windowColorSet).isTrue(); + assertThat(cue.verticalType).isEqualTo(Cue.VERTICAL_TYPE_RL); + assertThat(cue.shearDegrees).isEqualTo(-15f); ++ assertThat(cue.textRegionHeight).isEqualTo(0.6f); ++ assertThat(cue.collisionAvoidance).isEqualTo(Cue.COLLISION_AVOIDANCE_DOWN); + + assertThat(modifiedCue.text).isSameInstanceAs(cue.text); + assertThat(modifiedCue.textAlignment).isEqualTo(cue.textAlignment); +@@ -80,6 +85,36 @@ public class CueTest { + assertThat(modifiedCue.windowColorSet).isEqualTo(cue.windowColorSet); + assertThat(modifiedCue.verticalType).isEqualTo(cue.verticalType); + assertThat(modifiedCue.shearDegrees).isEqualTo(cue.shearDegrees); ++ assertThat(modifiedCue.textRegionHeight).isEqualTo(cue.textRegionHeight); ++ assertThat(modifiedCue.collisionAvoidance).isEqualTo(cue.collisionAvoidance); ++ } ++ ++ @Test ++ public void newFieldsDefaultAndOldBundleRemainCompatible() { ++ Cue cue = new Cue.Builder().setText("text").build(); ++ ++ assertThat(cue.textRegionHeight).isEqualTo(Cue.DIMEN_UNSET); ++ assertThat(cue.collisionAvoidance).isEqualTo(Cue.COLLISION_AVOIDANCE_NONE); ++ ++ Bundle oldBundle = new Bundle(); ++ oldBundle.putCharSequence("0", "text"); ++ Cue cueFromOldBundle = Cue.fromBundle(oldBundle); ++ assertThat(cueFromOldBundle.textRegionHeight).isEqualTo(Cue.DIMEN_UNSET); ++ assertThat(cueFromOldBundle.collisionAvoidance).isEqualTo(Cue.COLLISION_AVOIDANCE_NONE); ++ } ++ ++ @Test ++ public void newFieldsRoundTripThroughAllBundleTypes() { ++ Cue cue = ++ new Cue.Builder() ++ .setText("text") ++ .setTextRegionHeight(0.25f) ++ .setCollisionAvoidance(Cue.COLLISION_AVOIDANCE_UP) ++ .build(); ++ ++ assertThat(Cue.fromBundle(cue.toBinderBasedBundle())).isEqualTo(cue); ++ assertThat(Cue.fromBundle(cue.toSerializableBundle())).isEqualTo(cue); ++ assertThat(Cue.fromBundle(cue.toBundle())).isEqualTo(cue); + } + + @Test +diff --git a/libraries/common/src/test/java/androidx/media3/common/text/CustomCueBundlerTest.java b/libraries/common/src/test/java/androidx/media3/common/text/CustomCueBundlerTest.java +index 5f7a1bd08a..f20ebe2e4b 100644 +--- a/libraries/common/src/test/java/androidx/media3/common/text/CustomCueBundlerTest.java ++++ b/libraries/common/src/test/java/androidx/media3/common/text/CustomCueBundlerTest.java +@@ -52,12 +52,18 @@ public class CustomCueBundlerTest { + TextAnnotation.POSITION_AFTER); + private static final HorizontalTextInVerticalContextSpan + HORIZONTAL_TEXT_IN_VERTICAL_CONTEXT_SPAN = new HorizontalTextInVerticalContextSpan(); ++ private static final LetterSpacingSpan LETTER_SPACING_PIXELS_SPAN = new LetterSpacingSpan(2f); ++ private static final LetterSpacingSpan LETTER_SPACING_EM_SPAN = ++ LetterSpacingSpan.createFromEm(0.1f); + private static final ImmutableMap> ALL_SPANS_TO_START_END_INDEX = +- ImmutableMap.of( +- RUBY_SPAN, new Pair<>(1, 2), +- TEXT_EMPHASIS_SPAN, new Pair<>(2, 3), +- HORIZONTAL_TEXT_IN_VERTICAL_CONTEXT_SPAN, new Pair<>(5, 7), +- VOICE_SPAN, new Pair<>(8, 10)); ++ ImmutableMap.>builder() ++ .put(RUBY_SPAN, new Pair<>(1, 2)) ++ .put(TEXT_EMPHASIS_SPAN, new Pair<>(2, 3)) ++ .put(HORIZONTAL_TEXT_IN_VERTICAL_CONTEXT_SPAN, new Pair<>(5, 7)) ++ .put(VOICE_SPAN, new Pair<>(8, 10)) ++ .put(LETTER_SPACING_PIXELS_SPAN, new Pair<>(9, 10)) ++ .put(LETTER_SPACING_EM_SPAN, new Pair<>(10, 11)) ++ .build(); + + @Test + public void serializingSpannableWithAllCustomSpans() { +@@ -99,6 +105,10 @@ public class CustomCueBundlerTest { + ALL_SPANS_TO_START_END_INDEX.get(VOICE_SPAN).first, + ALL_SPANS_TO_START_END_INDEX.get(VOICE_SPAN).second) + .withName(VOICE_SPAN.name); ++ LetterSpacingSpan[] spans = result.getSpans(0, result.length(), LetterSpacingSpan.class); ++ assertThat(spans).hasLength(2); ++ assertThat(spans[0].toBundle()).isNotNull(); ++ assertThat(spans[1].toBundle()).isNotNull(); + } + + @Test +diff --git a/libraries/common/src/test/java/androidx/media3/common/text/LetterSpacingSpanTest.java b/libraries/common/src/test/java/androidx/media3/common/text/LetterSpacingSpanTest.java +new file mode 100644 +index 0000000000..ee636886e6 +--- /dev/null ++++ b/libraries/common/src/test/java/androidx/media3/common/text/LetterSpacingSpanTest.java +@@ -0,0 +1,73 @@ ++/* ++ * Copyright 2026 The Android Open Source Project ++ * ++ * Licensed under the Apache License, Version 2.0 (the "License"); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an "AS IS" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package androidx.media3.common.text; ++ ++import static com.google.common.truth.Truth.assertThat; ++ ++import android.text.TextPaint; ++import androidx.test.ext.junit.runners.AndroidJUnit4; ++import org.junit.Test; ++import org.junit.runner.RunWith; ++ ++/** Tests for {@link LetterSpacingSpan}. */ ++@RunWith(AndroidJUnit4.class) ++public class LetterSpacingSpanTest { ++ ++ @Test ++ public void pixelSpacingUsesCurrentTextSize() { ++ TextPaint textPaint = new TextPaint(); ++ textPaint.setTextSize(10f); ++ ++ new LetterSpacingSpan(2f).updateMeasureState(textPaint); ++ ++ assertThat(textPaint.getLetterSpacing()).isWithin(0.0001f).of(0.2f); ++ } ++ ++ @Test ++ public void negativePixelSpacingIsPreserved() { ++ TextPaint textPaint = new TextPaint(); ++ textPaint.setTextSize(10f); ++ ++ new LetterSpacingSpan(-2f).updateDrawState(textPaint); ++ ++ assertThat(textPaint.getLetterSpacing()).isWithin(0.0001f).of(-0.2f); ++ } ++ ++ @Test ++ public void emSpacingIsAppliedDirectly() { ++ TextPaint textPaint = new TextPaint(); ++ textPaint.setTextSize(10f); ++ ++ LetterSpacingSpan.createFromEm(0.15f).updateMeasureState(textPaint); ++ ++ assertThat(textPaint.getLetterSpacing()).isWithin(0.0001f).of(0.15f); ++ } ++ ++ @Test ++ public void bundleRoundTripPreservesPixelAndEmSpacing() { ++ TextPaint pixelPaint = new TextPaint(); ++ pixelPaint.setTextSize(8f); ++ TextPaint emPaint = new TextPaint(); ++ ++ LetterSpacingSpan.fromBundle(new LetterSpacingSpan(2f).toBundle()) ++ .updateMeasureState(pixelPaint); ++ LetterSpacingSpan.fromBundle(LetterSpacingSpan.createFromEm(0.25f).toBundle()) ++ .updateMeasureState(emPaint); ++ ++ assertThat(pixelPaint.getLetterSpacing()).isWithin(0.0001f).of(0.25f); ++ assertThat(emPaint.getLetterSpacing()).isWithin(0.0001f).of(0.25f); ++ } ++} diff --git a/third_party/patches/media3-exo-dts-14bit-frame-size.patch b/third_party/patches/media3-exo-dts-14bit-frame-size.patch new file mode 100644 index 0000000000..a18ad2d8db --- /dev/null +++ b/third_party/patches/media3-exo-dts-14bit-frame-size.patch @@ -0,0 +1,46 @@ +diff --git a/libraries/extractor/src/main/java/androidx/media3/extractor/DtsUtil.java b/libraries/extractor/src/main/java/androidx/media3/extractor/DtsUtil.java +index e47deaeaab..81ce1b52d2 100644 +--- a/libraries/extractor/src/main/java/androidx/media3/extractor/DtsUtil.java ++++ b/libraries/extractor/src/main/java/androidx/media3/extractor/DtsUtil.java +@@ -466,2 +466,6 @@ public final class DtsUtil { +- // If the frame is stored in 14-bit mode, adjust the frame size to reflect the actual byte size. +- return uses14BitPerWord ? fsize * 16 / 14 : fsize; ++ if (!uses14BitPerWord) { ++ return fsize; ++ } ++ // A 14-bit stream stores each 14-bit word in a 16-bit container. Convert the unpacked byte ++ // size to a whole number of 14-bit words before converting those words to physical bytes. ++ return (fsize * C.BITS_PER_BYTE / 14) * 2; +diff --git a/libraries/extractor/src/test/java/androidx/media3/extractor/DtsUtilTest.java b/libraries/extractor/src/test/java/androidx/media3/extractor/DtsUtilTest.java +index 5bf7cc1006..c57dbb5fa9 100644 +--- a/libraries/extractor/src/test/java/androidx/media3/extractor/DtsUtilTest.java ++++ b/libraries/extractor/src/test/java/androidx/media3/extractor/DtsUtilTest.java +@@ -41,0 +42,28 @@ public final class DtsUtilTest { ++ ++ @Test ++ public void getDtsFrameSize_with14BitBigEndianFrameSize3585_returns4096Bytes() { ++ byte[] data = new byte[10]; ++ data[0] = 0x1F; ++ data[7] = (byte) 0xE0; ++ ++ assertThat(DtsUtil.getDtsFrameSize(data)).isEqualTo(4096); ++ } ++ ++ @Test ++ public void getDtsFrameSize_with14BitLittleEndianFrameSize3585_returns4096Bytes() { ++ byte[] data = new byte[10]; ++ data[0] = (byte) 0xFF; ++ data[6] = (byte) 0xE0; ++ ++ assertThat(DtsUtil.getDtsFrameSize(data)).isEqualTo(4096); ++ } ++ ++ @Test ++ public void getDtsFrameSize_with16BitBigEndianFrame_returnsEncodedSize() { ++ byte[] data = new byte[8]; ++ data[0] = 0x7F; ++ data[6] = 0x06; ++ data[7] = 0x30; ++ ++ assertThat(DtsUtil.getDtsFrameSize(data)).isEqualTo(100); ++ } diff --git a/third_party/patches/media3-exo-eac3-joc-pixel-guard.patch b/third_party/patches/media3-exo-eac3-joc-pixel-guard.patch new file mode 100644 index 0000000000..d12d9616c1 --- /dev/null +++ b/third_party/patches/media3-exo-eac3-joc-pixel-guard.patch @@ -0,0 +1,72 @@ +diff --git a/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/mediacodec/MediaCodecUtil.java b/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/mediacodec/MediaCodecUtil.java +--- a/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/mediacodec/MediaCodecUtil.java ++++ b/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/mediacodec/MediaCodecUtil.java +@@ -49,6 +49,7 @@ + import java.util.Collections; + import java.util.HashMap; + import java.util.List; ++import java.util.Objects; + import org.checkerframework.checker.nullness.qual.EnsuresNonNull; + import org.checkerframework.checker.nullness.qual.RequiresNonNull; + +@@ -384,5 +385,9 @@ public static List getAlternativeCodecMimeTypes(Format format) { + if (MimeTypes.AUDIO_E_AC3_JOC.equals(format.sampleMimeType)) { + // E-AC3 decoders can decode JOC streams, but in 2-D rather than 3-D. +- return Collections.singletonList(MimeTypes.AUDIO_E_AC3); ++ // Some devices (e.g. Pixel) integrate an EAC3 decoder that does not support EAC3-JOC ++ // stream decoding. ++ return supportsEac3JocFallbackDecoding() ++ ? Collections.singletonList(MimeTypes.AUDIO_E_AC3) ++ : Collections.emptyList(); + } + if (MimeTypes.AUDIO_MEDIA3_DTS_HD_MA_CORELESS.equals(format.sampleMimeType)) { +@@ -434,6 +439,17 @@ public static List getAlternativeCodecMimeTypes(Format format) { + return Collections.emptyList(); + } + ++ /** ++ * Returns whether the device supports decoding E-AC3 JOC streams using a standard E-AC3 decoder ++ * (in 2-D rather than 3-D). ++ * ++ *

Some devices (e.g. Pixel) have an E-AC3 decoder that cannot handle E-AC3 JOC streams at all, ++ * even in degraded 2-D. See Issue 3257. ++ */ ++ private static boolean supportsEac3JocFallbackDecoding() { ++ return !Objects.equals(Build.MANUFACTURER, "Google"); ++ } ++ + // Internal methods. + + /** +diff --git a/libraries/exoplayer/src/test/java/androidx/media3/exoplayer/mediacodec/MediaCodecUtilTest.java b/libraries/exoplayer/src/test/java/androidx/media3/exoplayer/mediacodec/MediaCodecUtilTest.java +--- a/libraries/exoplayer/src/test/java/androidx/media3/exoplayer/mediacodec/MediaCodecUtilTest.java ++++ b/libraries/exoplayer/src/test/java/androidx/media3/exoplayer/mediacodec/MediaCodecUtilTest.java +@@ -29,5 +29,6 @@ + import org.junit.Test; + import org.junit.runner.RunWith; ++import org.robolectric.shadows.ShadowBuild; + + /** Unit tests for {@link MediaCodecUtil}. */ + @RunWith(AndroidJUnit4.class) +@@ -261,6 +262,21 @@ public void getAlternativeCodecMimeType_withNonFallbackCompatibleFormat_returnsE + .isEqualTo(Collections.singletonList(MimeTypes.VIDEO_AV1)); + } + ++ @Test ++ public void getAlternativeCodecMimeTypes_withEac3JocFormatOnNonGoogleDevice_returnsEac3() { ++ ShadowBuild.setManufacturer("Samsung"); ++ Format format = new Format.Builder().setSampleMimeType(MimeTypes.AUDIO_E_AC3_JOC).build(); ++ assertThat(MediaCodecUtil.getAlternativeCodecMimeTypes(format)) ++ .containsExactly(MimeTypes.AUDIO_E_AC3); ++ } ++ ++ @Test ++ public void getAlternativeCodecMimeTypes_withEac3JocFormatOnGoogleDevice_returnsEmpty() { ++ ShadowBuild.setManufacturer("Google"); ++ Format format = new Format.Builder().setSampleMimeType(MimeTypes.AUDIO_E_AC3_JOC).build(); ++ assertThat(MediaCodecUtil.getAlternativeCodecMimeTypes(format)).isEmpty(); ++ } ++ + private static void assertHevcBaseLayerCodecProfileAndLevelForFormat( + Format format, int profile, int level) { + MediaCodecProfileAndLevel codecProfileAndLevel = diff --git a/third_party/patches/media3-exo-hdr-parser-safety.patch b/third_party/patches/media3-exo-hdr-parser-safety.patch new file mode 100644 index 0000000000..355905874a --- /dev/null +++ b/third_party/patches/media3-exo-hdr-parser-safety.patch @@ -0,0 +1,158 @@ +diff --git a/libraries/container/src/main/java/androidx/media3/container/DolbyVisionConfig.java b/libraries/container/src/main/java/androidx/media3/container/DolbyVisionConfig.java +index 7af4f691d8..f2f5e281ef 100644 +--- a/libraries/container/src/main/java/androidx/media3/container/DolbyVisionConfig.java ++++ b/libraries/container/src/main/java/androidx/media3/container/DolbyVisionConfig.java +@@ -36 +36,8 @@ public final class DolbyVisionConfig { +- data.skipBytes(2); // dv_version_major, dv_version_minor ++ if (data.bytesLeft() < 4) { ++ return null; ++ } ++ int majorVersion = data.readUnsignedByte(); ++ data.skipBytes(1); // dv_version_minor ++ if (majorVersion != 1) { ++ return null; ++ } +diff --git a/libraries/extractor/src/main/java/androidx/media3/extractor/mkv/MatroskaExtractor.java b/libraries/extractor/src/main/java/androidx/media3/extractor/mkv/MatroskaExtractor.java +index 5af42a7caa..a57a4415e0 100644 +--- a/libraries/extractor/src/main/java/androidx/media3/extractor/mkv/MatroskaExtractor.java ++++ b/libraries/extractor/src/main/java/androidx/media3/extractor/mkv/MatroskaExtractor.java +@@ -2604,0 +2605,2 @@ public class MatroskaExtractor implements Extractor { ++ // CTA-861.3 stores minimum mastering luminance in units of 0.0001 cd/m2. ++ private static final int MIN_MASTERING_LUMINANCE_SCALE = 10_000; +@@ -3120 +3122,2 @@ public class MatroskaExtractor implements Extractor { +- hdrStaticInfo.putShort((short) (minMasteringLuminance + 0.5f)); ++ hdrStaticInfo.putShort( ++ (short) ((minMasteringLuminance * MIN_MASTERING_LUMINANCE_SCALE) + 0.5f)); +diff --git a/libraries/extractor/src/main/java/androidx/media3/extractor/mp4/BoxParser.java b/libraries/extractor/src/main/java/androidx/media3/extractor/mp4/BoxParser.java +index bd6740ea8c..e2db447e4b 100644 +--- a/libraries/extractor/src/main/java/androidx/media3/extractor/mp4/BoxParser.java ++++ b/libraries/extractor/src/main/java/androidx/media3/extractor/mp4/BoxParser.java +@@ -1706 +1706,7 @@ public final class BoxParser { +- dolbyVisionConfig = DolbyVisionConfig.parse(parent); ++ byte[] dolbyVisionConfigBytes = ++ parseDolbyVisionConfigBytes( ++ parent, ++ childStartPosition, ++ childAtomSize, ++ /* sampleEntryEndPosition= */ (long) position + size); ++ dolbyVisionConfig = DolbyVisionConfig.parse(new ParsableByteArray(dolbyVisionConfigBytes)); +@@ -1930,0 +1937,17 @@ public final class BoxParser { ++ /* package */ static byte[] parseDolbyVisionConfigBytes( ++ ParsableByteArray parent, ++ int childStartPosition, ++ int childAtomSize, ++ long sampleEntryEndPosition) ++ throws ParserException { ++ long configurationStartPosition = (long) childStartPosition + Mp4Box.HEADER_SIZE; ++ long configurationEndPosition = (long) childStartPosition + childAtomSize; ++ ExtractorUtil.checkContainerInput( ++ childAtomSize >= Mp4Box.HEADER_SIZE + 4 ++ && configurationEndPosition <= sampleEntryEndPosition ++ && configurationEndPosition <= parent.limit(), ++ "Invalid Dolby Vision configuration"); ++ return Arrays.copyOfRange( ++ parent.getData(), (int) configurationStartPosition, (int) configurationEndPosition); ++ } ++ +diff --git a/libraries/extractor/src/test/java/androidx/media3/extractor/mkv/MatroskaExtractorNonParameterizedTest.java b/libraries/extractor/src/test/java/androidx/media3/extractor/mkv/MatroskaExtractorNonParameterizedTest.java +index 2c913b32ce..b3b3d5c3b3 100644 +--- a/libraries/extractor/src/test/java/androidx/media3/extractor/mkv/MatroskaExtractorNonParameterizedTest.java ++++ b/libraries/extractor/src/test/java/androidx/media3/extractor/mkv/MatroskaExtractorNonParameterizedTest.java +@@ -18,0 +19 @@ import static androidx.media3.extractor.Extractor.RESULT_SEEK; ++import static com.google.common.base.Preconditions.checkNotNull; +@@ -32,0 +34,2 @@ import androidx.test.ext.junit.runners.AndroidJUnit4; ++import java.nio.ByteBuffer; ++import java.nio.ByteOrder; +@@ -39,0 +43,37 @@ public class MatroskaExtractorNonParameterizedTest { ++ @Test ++ public void initializeFormat_hdrStaticInfo_encodesMinimumLuminanceInCta861Units() ++ throws Exception { ++ assertMinimumMasteringLuminanceEncoded(/* minimumLuminance= */ 0.0001f, /* expected= */ 1); ++ assertMinimumMasteringLuminanceEncoded(/* minimumLuminance= */ 0.005f, /* expected= */ 50); ++ } ++ ++ private static void assertMinimumMasteringLuminanceEncoded( ++ float minimumLuminance, int expected) throws Exception { ++ MatroskaExtractor.Track track = new MatroskaExtractor.Track(); ++ track.codecId = "V_VP9"; ++ track.width = 426; ++ track.height = 240; ++ track.primaryRChromaticityX = 0.708f; ++ track.primaryRChromaticityY = 0.292f; ++ track.primaryGChromaticityX = 0.170f; ++ track.primaryGChromaticityY = 0.797f; ++ track.primaryBChromaticityX = 0.131f; ++ track.primaryBChromaticityY = 0.046f; ++ track.whitePointChromaticityX = 0.3127f; ++ track.whitePointChromaticityY = 0.3290f; ++ track.maxMasteringLuminance = 1000f; ++ track.minMasteringLuminance = minimumLuminance; ++ track.maxContentLuminance = 1100; ++ track.maxFrameAverageLuminance = 180; ++ ++ track.initializeFormat(/* trackId= */ 1); ++ ++ byte[] hdrStaticInfo = checkNotNull(checkNotNull(track.format.colorInfo).hdrStaticInfo); ++ ByteBuffer hdrStaticInfoBuffer = ++ ByteBuffer.wrap(hdrStaticInfo).order(ByteOrder.LITTLE_ENDIAN); ++ assertThat(Short.toUnsignedInt(hdrStaticInfoBuffer.getShort(17))).isEqualTo(1000); ++ assertThat(Short.toUnsignedInt(hdrStaticInfoBuffer.getShort(19))).isEqualTo(expected); ++ assertThat(Short.toUnsignedInt(hdrStaticInfoBuffer.getShort(21))).isEqualTo(1100); ++ assertThat(Short.toUnsignedInt(hdrStaticInfoBuffer.getShort(23))).isEqualTo(180); ++ } ++ +diff --git a/libraries/extractor/src/test/java/androidx/media3/extractor/mp4/BoxParserTest.java b/libraries/extractor/src/test/java/androidx/media3/extractor/mp4/BoxParserTest.java +index bb968cf088..c9cf7f9084 100644 +--- a/libraries/extractor/src/test/java/androidx/media3/extractor/mp4/BoxParserTest.java ++++ b/libraries/extractor/src/test/java/androidx/media3/extractor/mp4/BoxParserTest.java +@@ -19,0 +20 @@ import static java.nio.charset.StandardCharsets.UTF_8; ++import static org.junit.Assert.assertThrows; +@@ -44,0 +46,2 @@ public final class BoxParserTest { ++ private static final byte[] DOLBY_VISION_CONFIGURATION_BOX = ++ Util.getBytesFromHexString("0000000D647663430100100D10"); +@@ -259,0 +263,45 @@ public final class BoxParserTest { ++ @Test ++ public void parseDolbyVisionConfigBytes_withValidBox_returnsPayload() throws ParserException { ++ ParsableByteArray parent = new ParsableByteArray(DOLBY_VISION_CONFIGURATION_BOX); ++ ++ byte[] configuration = ++ BoxParser.parseDolbyVisionConfigBytes( ++ parent, ++ /* childStartPosition= */ 0, ++ /* childAtomSize= */ DOLBY_VISION_CONFIGURATION_BOX.length, ++ /* sampleEntryEndPosition= */ DOLBY_VISION_CONFIGURATION_BOX.length); ++ ++ assertThat(configuration).isEqualTo(Util.getBytesFromHexString("0100100D10")); ++ } ++ ++ @Test ++ public void parseDolbyVisionConfigBytes_withBoxCrossingSampleEntry_throws() { ++ ParsableByteArray parent = new ParsableByteArray(DOLBY_VISION_CONFIGURATION_BOX); ++ ++ assertThrows( ++ ParserException.class, ++ () -> ++ BoxParser.parseDolbyVisionConfigBytes( ++ parent, ++ /* childStartPosition= */ 0, ++ /* childAtomSize= */ DOLBY_VISION_CONFIGURATION_BOX.length, ++ /* sampleEntryEndPosition= */ DOLBY_VISION_CONFIGURATION_BOX.length - 1)); ++ } ++ ++ @Test ++ public void parseDolbyVisionConfigBytes_withTruncatedBox_throws() { ++ ParsableByteArray parent = ++ new ParsableByteArray( ++ DOLBY_VISION_CONFIGURATION_BOX, ++ /* limit= */ DOLBY_VISION_CONFIGURATION_BOX.length - 1); ++ ++ assertThrows( ++ ParserException.class, ++ () -> ++ BoxParser.parseDolbyVisionConfigBytes( ++ parent, ++ /* childStartPosition= */ 0, ++ /* childAtomSize= */ DOLBY_VISION_CONFIGURATION_BOX.length, ++ /* sampleEntryEndPosition= */ DOLBY_VISION_CONFIGURATION_BOX.length)); ++ } ++ diff --git a/third_party/patches/media3-exo-iso-multi-extent.patch b/third_party/patches/media3-exo-iso-multi-extent.patch new file mode 100644 index 0000000000..05fd0d8bda --- /dev/null +++ b/third_party/patches/media3-exo-iso-multi-extent.patch @@ -0,0 +1,1475 @@ +diff --git a/libraries/datasource/src/main/java/androidx/media3/datasource/IsoDataSource.java b/libraries/datasource/src/main/java/androidx/media3/datasource/IsoDataSource.java +index 922c58d359..962b971f0d 100644 +--- a/libraries/datasource/src/main/java/androidx/media3/datasource/IsoDataSource.java ++++ b/libraries/datasource/src/main/java/androidx/media3/datasource/IsoDataSource.java +@@ -20,6 +20,10 @@ import androidx.annotation.Nullable; + import androidx.media3.common.C; + import androidx.media3.common.PlaybackException; + import java.io.IOException; ++import java.util.Arrays; ++import java.util.Collections; ++import java.util.List; ++import java.util.Map; + + public final class IsoDataSource extends BaseDataSource { + +@@ -30,27 +34,66 @@ public final class IsoDataSource extends BaseDataSource { + private static final int SACD_SECTOR_SIZE = 2048; + private static final int SACD_HEADER_SIZE = 4; + private static final int SACD_PAYLOAD_SIZE = SACD_SECTOR_SIZE - SACD_HEADER_SIZE; ++ private static final long ZERO_FILLED_EXTENT_OFFSET = -1; + + private final byte[] m2tsBuf = new byte[M2TS_PACKET_SIZE]; + private final byte[] sacdBuf = new byte[SACD_SECTOR_SIZE]; + private final DataSource upstream; +- private final long clipByteOffset; ++ private final long[] extentByteOffsets; ++ private final long[] extentByteLengths; ++ private final long clipLogicalByteOffset; + private final long clipByteLength; + private final boolean stripM2tsHeaders; + private final boolean stripSacdHeaders; + +- @Nullable +- private Uri uri; ++ @Nullable private Uri uri; + private long bytesRemaining; + private int m2tsBufPos; + private int m2tsBufLimit; + private int sacdBufPos; + private int sacdBufLimit; ++ private boolean upstreamOpened; ++ private boolean opened; ++ @Nullable private DataSpec openedDataSpec; ++ private long rawReadPosition; ++ private long rawReadEnd; ++ private long currentExtentBytesRemaining; ++ private boolean currentExtentIsZeroFilled; + +- public IsoDataSource(DataSource upstream, long clipByteOffset, long clipByteLength, boolean stripM2tsHeaders, boolean stripSacdHeaders) { ++ public IsoDataSource( ++ DataSource upstream, ++ long[] extentByteOffsets, ++ long[] extentByteLengths, ++ long clipLogicalByteOffset, ++ long clipByteLength, ++ boolean stripM2tsHeaders, ++ boolean stripSacdHeaders) { + super(false); ++ if (extentByteOffsets.length == 0 || extentByteOffsets.length != extentByteLengths.length) { ++ throw new IllegalArgumentException("Invalid ISO extents"); ++ } + this.upstream = upstream; +- this.clipByteOffset = clipByteOffset; ++ this.extentByteOffsets = Arrays.copyOf(extentByteOffsets, extentByteOffsets.length); ++ this.extentByteLengths = Arrays.copyOf(extentByteLengths, extentByteLengths.length); ++ long totalExtentLength = 0; ++ try { ++ for (int i = 0; i < extentByteOffsets.length; i++) { ++ if ((extentByteOffsets[i] < 0 && extentByteOffsets[i] != ZERO_FILLED_EXTENT_OFFSET) ++ || extentByteLengths[i] < 0) { ++ throw new IllegalArgumentException("Invalid ISO extent"); ++ } ++ totalExtentLength = Math.addExact(totalExtentLength, extentByteLengths[i]); ++ } ++ } catch (ArithmeticException e) { ++ throw new IllegalArgumentException("ISO extent length overflow", e); ++ } ++ if (clipLogicalByteOffset < 0 ++ || clipByteLength < 0 ++ || clipLogicalByteOffset > totalExtentLength ++ || clipByteLength > totalExtentLength - clipLogicalByteOffset) { ++ throw new IllegalArgumentException("ISO clip is outside its extents"); ++ } ++ this.clipLogicalByteOffset = clipLogicalByteOffset; + this.clipByteLength = clipByteLength; + this.stripM2tsHeaders = stripM2tsHeaders; + this.stripSacdHeaders = stripSacdHeaders; +@@ -71,47 +114,65 @@ public final class IsoDataSource extends BaseDataSource { + if (clipPosition > clipVirtualLength) { + throw new DataSourceException(PlaybackException.ERROR_CODE_IO_READ_POSITION_OUT_OF_RANGE); + } +- long isoOffset; +- long upstreamLength; ++ long rawClipPosition; ++ long rawLength; + long packetOffset = 0; + if (stripM2tsHeaders) { + long packetIndex = clipPosition / TS_PACKET_SIZE; + packetOffset = clipPosition % TS_PACKET_SIZE; +- isoOffset = clipByteOffset + packetIndex * M2TS_PACKET_SIZE; ++ rawClipPosition = packetIndex * M2TS_PACKET_SIZE; + long virtualRemaining = clipVirtualLength - clipPosition; +- bytesRemaining = dataSpec.length == C.LENGTH_UNSET ? virtualRemaining : Math.min(dataSpec.length, virtualRemaining); ++ bytesRemaining = ++ dataSpec.length == C.LENGTH_UNSET ++ ? virtualRemaining ++ : Math.min(dataSpec.length, virtualRemaining); + long packetsNeeded = (bytesRemaining + packetOffset + TS_PACKET_SIZE - 1) / TS_PACKET_SIZE; +- upstreamLength = packetsNeeded * M2TS_PACKET_SIZE; ++ rawLength = packetsNeeded * M2TS_PACKET_SIZE; + } else if (stripSacdHeaders) { + long sectorIndex = clipPosition / SACD_PAYLOAD_SIZE; + packetOffset = clipPosition % SACD_PAYLOAD_SIZE; +- isoOffset = clipByteOffset + sectorIndex * SACD_SECTOR_SIZE; ++ rawClipPosition = sectorIndex * SACD_SECTOR_SIZE; + long virtualRemaining = clipVirtualLength - clipPosition; +- bytesRemaining = dataSpec.length == C.LENGTH_UNSET ? virtualRemaining : Math.min(dataSpec.length, virtualRemaining); +- long sectorsNeeded = (bytesRemaining + packetOffset + SACD_PAYLOAD_SIZE - 1) / SACD_PAYLOAD_SIZE; +- upstreamLength = sectorsNeeded * SACD_SECTOR_SIZE; ++ bytesRemaining = ++ dataSpec.length == C.LENGTH_UNSET ++ ? virtualRemaining ++ : Math.min(dataSpec.length, virtualRemaining); ++ long sectorsNeeded = ++ (bytesRemaining + packetOffset + SACD_PAYLOAD_SIZE - 1) / SACD_PAYLOAD_SIZE; ++ rawLength = sectorsNeeded * SACD_SECTOR_SIZE; + } else { +- isoOffset = clipByteOffset + clipPosition; ++ rawClipPosition = clipPosition; + long rawRemaining = clipVirtualLength - clipPosition; +- bytesRemaining = dataSpec.length == C.LENGTH_UNSET ? rawRemaining : Math.min(dataSpec.length, rawRemaining); +- upstreamLength = bytesRemaining; ++ bytesRemaining = ++ dataSpec.length == C.LENGTH_UNSET ++ ? rawRemaining ++ : Math.min(dataSpec.length, rawRemaining); ++ rawLength = bytesRemaining; + } + m2tsBufPos = 0; + m2tsBufLimit = 0; + sacdBufPos = 0; + sacdBufLimit = 0; +- DataSpec upstreamSpec = new DataSpec.Builder().setUri(dataSpec.uri).setPosition(isoOffset).setLength(upstreamLength).setKey(dataSpec.key).build(); ++ openedDataSpec = dataSpec; ++ rawReadPosition = clipLogicalByteOffset + rawClipPosition; ++ long rawAvailable = clipLogicalByteOffset + clipByteLength - rawReadPosition; ++ rawReadEnd = rawReadPosition + Math.min(rawLength, rawAvailable); ++ currentExtentBytesRemaining = 0; ++ currentExtentIsZeroFilled = false; + transferInitializing(dataSpec); +- upstream.open(upstreamSpec); ++ if (rawReadPosition < rawReadEnd) { ++ openExtentForCurrentPosition(); ++ } ++ opened = true; + transferStarted(dataSpec); + if (stripM2tsHeaders && packetOffset > 0) { +- int got = readFully(m2tsBuf, 0, M2TS_PACKET_SIZE); ++ int got = readFully(m2tsBuf, M2TS_PACKET_SIZE); + if (got == M2TS_PACKET_SIZE) { + m2tsBufPos = M2TS_HEADER_SIZE + (int) packetOffset; + m2tsBufLimit = M2TS_PACKET_SIZE; + } + } else if (stripSacdHeaders && packetOffset > 0) { +- int got = readFully(sacdBuf, 0, SACD_SECTOR_SIZE); ++ int got = readFully(sacdBuf, SACD_SECTOR_SIZE); + if (got == SACD_SECTOR_SIZE) { + sacdBufPos = SACD_HEADER_SIZE + (int) packetOffset; + sacdBufLimit = SACD_SECTOR_SIZE; +@@ -133,10 +194,11 @@ public final class IsoDataSource extends BaseDataSource { + if (stripM2tsHeaders) { + while (totalRead < toRead) { + if (m2tsBufPos >= m2tsBufLimit) { +- int got = readFully(m2tsBuf, 0, M2TS_PACKET_SIZE); ++ int got = readFully(m2tsBuf, M2TS_PACKET_SIZE); + if (got < M2TS_PACKET_SIZE) { + if (bytesRemaining > TS_PACKET_SIZE) { +- throw new IOException("Unexpected end of M2TS stream: " + bytesRemaining + " bytes remaining"); ++ throw new IOException( ++ "Unexpected end of M2TS stream: " + bytesRemaining + " bytes remaining"); + } + break; + } +@@ -152,7 +214,7 @@ public final class IsoDataSource extends BaseDataSource { + } else if (stripSacdHeaders) { + while (totalRead < toRead) { + if (sacdBufPos >= sacdBufLimit) { +- int got = readFully(sacdBuf, 0, SACD_SECTOR_SIZE); ++ int got = readFully(sacdBuf, SACD_SECTOR_SIZE); + if (got < SACD_SECTOR_SIZE) { + break; + } +@@ -166,7 +228,7 @@ public final class IsoDataSource extends BaseDataSource { + totalRead += copy; + } + } else { +- totalRead = upstream.read(buffer, offset, toRead); ++ totalRead = readRaw(buffer, offset, toRead); + if (totalRead == C.RESULT_END_OF_INPUT) { + totalRead = 0; + } +@@ -181,23 +243,41 @@ public final class IsoDataSource extends BaseDataSource { + @Nullable + @Override + public Uri getUri() { ++ if (upstreamOpened) { ++ @Nullable Uri upstreamUri = upstream.getUri(); ++ if (upstreamUri != null) { ++ return upstreamUri; ++ } ++ } + return uri; + } + ++ @Override ++ public Map> getResponseHeaders() { ++ return upstreamOpened ? upstream.getResponseHeaders() : Collections.emptyMap(); ++ } ++ + @Override + public void close() throws IOException { + uri = null; ++ openedDataSpec = null; + try { +- upstream.close(); ++ if (upstreamOpened) { ++ upstreamOpened = false; ++ upstream.close(); ++ } + } finally { +- transferEnded(); ++ if (opened) { ++ opened = false; ++ transferEnded(); ++ } + } + } + +- private int readFully(byte[] buf, int offset, int length) throws IOException { ++ private int readFully(byte[] buf, int length) throws IOException { + int total = 0; + while (total < length) { +- int read = upstream.read(buf, offset + total, length - total); ++ int read = readRaw(buf, total, length - total); + if (read == C.RESULT_END_OF_INPUT) { + break; + } +@@ -206,29 +286,138 @@ public final class IsoDataSource extends BaseDataSource { + return total; + } + ++ private int readRaw(byte[] buffer, int offset, int length) throws IOException { ++ int totalRead = 0; ++ while (totalRead < length && rawReadPosition < rawReadEnd) { ++ if (currentExtentBytesRemaining == 0) { ++ openExtentForCurrentPosition(); ++ } ++ int toRead = ++ (int) ++ Math.min( ++ Math.min((long) length - totalRead, currentExtentBytesRemaining), ++ rawReadEnd - rawReadPosition); ++ int read; ++ if (currentExtentIsZeroFilled) { ++ Arrays.fill(buffer, offset + totalRead, offset + totalRead + toRead, (byte) 0); ++ read = toRead; ++ } else { ++ read = upstream.read(buffer, offset + totalRead, toRead); ++ } ++ if (read == C.RESULT_END_OF_INPUT) { ++ break; ++ } ++ if (read == 0) { ++ throw new IOException("ISO upstream made no read progress"); ++ } ++ totalRead += read; ++ rawReadPosition += read; ++ currentExtentBytesRemaining -= read; ++ } ++ return totalRead == 0 ? C.RESULT_END_OF_INPUT : totalRead; ++ } ++ ++ private void openExtentForCurrentPosition() throws IOException { ++ if (upstreamOpened) { ++ upstream.close(); ++ upstreamOpened = false; ++ } ++ currentExtentIsZeroFilled = false; ++ long extentLogicalStart = 0; ++ for (int i = 0; i < extentByteOffsets.length; i++) { ++ long extentLength = extentByteLengths[i]; ++ long extentLogicalEnd = extentLogicalStart + extentLength; ++ if (rawReadPosition >= extentLogicalStart && rawReadPosition < extentLogicalEnd) { ++ long offsetInExtent = rawReadPosition - extentLogicalStart; ++ currentExtentBytesRemaining = ++ Math.min(extentLength - offsetInExtent, rawReadEnd - rawReadPosition); ++ if (extentByteOffsets[i] == ZERO_FILLED_EXTENT_OFFSET) { ++ currentExtentIsZeroFilled = true; ++ return; ++ } ++ DataSpec dataSpec = openedDataSpec; ++ if (dataSpec == null) { ++ throw new IOException("ISO data source is not open"); ++ } ++ DataSpec upstreamSpec = ++ dataSpec ++ .buildUpon() ++ .setPosition(extentByteOffsets[i] + offsetInExtent) ++ .setLength(currentExtentBytesRemaining) ++ .build(); ++ upstreamOpened = true; ++ upstream.open(upstreamSpec); ++ return; ++ } ++ extentLogicalStart = extentLogicalEnd; ++ } ++ throw new DataSourceException(PlaybackException.ERROR_CODE_IO_READ_POSITION_OUT_OF_RANGE); ++ } ++ + public static final class Factory implements DataSource.Factory { + + private final DataSource.Factory upstreamFactory; +- private final long byteOffset; +- private final long byteLength; ++ private final long[] extentByteOffsets; ++ private final long[] extentByteLengths; ++ private final long clipLogicalByteOffset; ++ private final long clipByteLength; + private final boolean stripM2tsHeaders; + private final boolean stripSacdHeaders; + +- public Factory(DataSource.Factory upstreamFactory, long byteOffset, long byteLength, boolean stripM2tsHeaders) { ++ public Factory( ++ DataSource.Factory upstreamFactory, ++ long byteOffset, ++ long byteLength, ++ boolean stripM2tsHeaders) { + this(upstreamFactory, byteOffset, byteLength, stripM2tsHeaders, false); + } + +- public Factory(DataSource.Factory upstreamFactory, long byteOffset, long byteLength, boolean stripM2tsHeaders, boolean stripSacdHeaders) { ++ public Factory( ++ DataSource.Factory upstreamFactory, ++ long byteOffset, ++ long byteLength, ++ boolean stripM2tsHeaders, ++ boolean stripSacdHeaders) { ++ this( ++ upstreamFactory, ++ new long[] {byteOffset}, ++ new long[] {byteLength}, ++ /* clipLogicalByteOffset= */ 0, ++ byteLength, ++ stripM2tsHeaders, ++ stripSacdHeaders); ++ } ++ ++ public Factory( ++ DataSource.Factory upstreamFactory, ++ long[] extentByteOffsets, ++ long[] extentByteLengths, ++ long clipLogicalByteOffset, ++ long clipByteLength, ++ boolean stripM2tsHeaders, ++ boolean stripSacdHeaders) { ++ if (extentByteOffsets.length == 0 || extentByteOffsets.length != extentByteLengths.length) { ++ throw new IllegalArgumentException("Invalid ISO extents"); ++ } + this.upstreamFactory = upstreamFactory; +- this.byteOffset = byteOffset; +- this.byteLength = byteLength; ++ this.extentByteOffsets = Arrays.copyOf(extentByteOffsets, extentByteOffsets.length); ++ this.extentByteLengths = Arrays.copyOf(extentByteLengths, extentByteLengths.length); ++ this.clipLogicalByteOffset = clipLogicalByteOffset; ++ this.clipByteLength = clipByteLength; + this.stripM2tsHeaders = stripM2tsHeaders; + this.stripSacdHeaders = stripSacdHeaders; + } + + @Override + public DataSource createDataSource() { +- return new IsoDataSource(upstreamFactory.createDataSource(), byteOffset, byteLength, stripM2tsHeaders, stripSacdHeaders); ++ return new IsoDataSource( ++ upstreamFactory.createDataSource(), ++ extentByteOffsets, ++ extentByteLengths, ++ clipLogicalByteOffset, ++ clipByteLength, ++ stripM2tsHeaders, ++ stripSacdHeaders); + } + } + } +diff --git a/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/source/iso/BdmvSourceHelper.java b/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/source/iso/BdmvSourceHelper.java +index 19cebc3541..b6832ff7e7 100644 +--- a/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/source/iso/BdmvSourceHelper.java ++++ b/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/source/iso/BdmvSourceHelper.java +@@ -99,9 +99,16 @@ final class BdmvSourceHelper { + } + startM2ts = (startM2ts / BdmvConstants.M2TS_PACKET_SIZE) * BdmvConstants.M2TS_PACKET_SIZE; + endM2ts = Math.min(m2tsEntry.length, Util.ceilDivide(endM2ts, BdmvConstants.M2TS_PACKET_SIZE) * BdmvConstants.M2TS_PACKET_SIZE); +- long clipByteOffset = m2tsEntry.byteOffset + startM2ts; + long clipByteLength = endM2ts - startM2ts; +- IsoDataSource.Factory clipFactory = new IsoDataSource.Factory(dataSourceFactory, clipByteOffset, clipByteLength, true); ++ IsoDataSource.Factory clipFactory = ++ new IsoDataSource.Factory( ++ dataSourceFactory, ++ m2tsEntry.extentOffsets, ++ m2tsEntry.extentLengths, ++ startM2ts, ++ clipByteLength, ++ /* stripM2tsHeaders= */ true, ++ /* stripSacdHeaders= */ false); + final long capturedStartM2ts = startM2ts; + final long capturedInTimeTicks = item.inTimeTicks; + final long capturedDurationUs = durationUs; +@@ -335,12 +342,24 @@ final class BdmvSourceHelper { + int maxRead = (int) Math.min(entry.length, MAX_ENTRY_READ_BYTES); + byte[] data = new byte[maxRead]; + int pos = 0; +- while (pos < maxRead) { +- int read = isoReader.read(entry.byteOffset + pos, data, pos, maxRead - pos); +- if (read <= 0) { +- break; ++ for (int i = 0; i < entry.extentOffsets.length && pos < maxRead; i++) { ++ int extentLength = (int) Math.min(entry.extentLengths[i], maxRead - pos); ++ if (entry.extentOffsets[i] == IsoFileEntry.UNRECORDED_EXTENT_OFFSET) { ++ Arrays.fill(data, pos, pos + extentLength, (byte) 0); ++ pos += extentLength; ++ continue; ++ } ++ int extentRead = 0; ++ while (extentRead < extentLength) { ++ int read = ++ isoReader.read( ++ entry.extentOffsets[i] + extentRead, data, pos, extentLength - extentRead); ++ if (read <= 0) { ++ return pos < data.length ? Arrays.copyOf(data, pos) : data; ++ } ++ pos += read; ++ extentRead += read; + } +- pos += read; + } + return pos < data.length ? Arrays.copyOf(data, pos) : data; + } +@@ -371,20 +390,34 @@ final class BdmvSourceHelper { + long minOffset = Long.MAX_VALUE; + long maxEnd = 0; + for (IsoFileEntry e : entries) { +- if (e.byteOffset < minOffset) { +- minOffset = e.byteOffset; +- } +- long end = e.byteOffset + e.length; +- if (end > maxEnd) { +- maxEnd = end; ++ for (int i = 0; i < e.extentOffsets.length; i++) { ++ if (e.extentOffsets[i] == IsoFileEntry.UNRECORDED_EXTENT_OFFSET) { ++ continue; ++ } ++ minOffset = Math.min(minOffset, e.extentOffsets[i]); ++ long end = e.extentOffsets[i] + e.extentLengths[i]; ++ if (end >= e.extentOffsets[i]) { ++ maxEnd = Math.max(maxEnd, end); ++ } + } + } ++ if (minOffset == Long.MAX_VALUE) { ++ return; ++ } + long span = maxEnd - minOffset; + if (span > 0 && span <= BATCH_PREFETCH_MAX_SPAN) { + isoReader.prefetchRange(minOffset, maxEnd); + } else { + for (IsoFileEntry e : entries) { +- isoReader.prefetchRange(e.byteOffset, e.byteOffset + e.length); ++ for (int i = 0; i < e.extentOffsets.length; i++) { ++ if (e.extentOffsets[i] == IsoFileEntry.UNRECORDED_EXTENT_OFFSET) { ++ continue; ++ } ++ long end = e.extentOffsets[i] + e.extentLengths[i]; ++ if (end >= e.extentOffsets[i]) { ++ isoReader.prefetchRange(e.extentOffsets[i], end); ++ } ++ } + } + } + } +diff --git a/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/source/iso/DvdSourceHelper.java b/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/source/iso/DvdSourceHelper.java +index 2671617912..f3201bd83b 100644 +--- a/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/source/iso/DvdSourceHelper.java ++++ b/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/source/iso/DvdSourceHelper.java +@@ -66,7 +66,15 @@ final class DvdSourceHelper { + continue; + } + final IndexSeekMap seekMap = (cellIndex < cellSeekMaps.size()) ? cellSeekMaps.get(cellIndex) : null; +- IsoDataSource.Factory clipFactory = new IsoDataSource.Factory(dataSourceFactory, cell.byteOffset, cell.length, false); ++ IsoDataSource.Factory clipFactory = ++ new IsoDataSource.Factory( ++ dataSourceFactory, ++ cell.extentOffsets, ++ cell.extentLengths, ++ /* clipLogicalByteOffset= */ 0, ++ cell.length, ++ /* stripM2tsHeaders= */ false, ++ /* stripSacdHeaders= */ false); + final DvdPrivateStreamReader psr = privateStreamReader; + ProgressiveMediaSource.Factory psFactory = new ProgressiveMediaSource.Factory(clipFactory, () -> new Extractor[]{new PsExtractor(new TimestampAdjuster(0), psr, seekMap)}); + MediaItem cellItem = new MediaItem.Builder().setUri(isoUri).setCustomCacheKey("cell_" + cell.byteOffset).build(); +diff --git a/libraries/extractor/src/main/java/androidx/media3/extractor/iso/IsoFileEntry.java b/libraries/extractor/src/main/java/androidx/media3/extractor/iso/IsoFileEntry.java +index 100b9ad46b..33b06a41cd 100644 +--- a/libraries/extractor/src/main/java/androidx/media3/extractor/iso/IsoFileEntry.java ++++ b/libraries/extractor/src/main/java/androidx/media3/extractor/iso/IsoFileEntry.java +@@ -15,8 +15,13 @@ + */ + package androidx.media3.extractor.iso; + ++import java.util.Arrays; ++ + public final class IsoFileEntry { + ++ /** Extent offset indicating that the logical extent contains zero-filled unrecorded data. */ ++ public static final long UNRECORDED_EXTENT_OFFSET = -1; ++ + // File name within the UDF directory. + public final String name; + +@@ -26,9 +31,43 @@ public final class IsoFileEntry { + // Length of the file's data in bytes. + public final long length; + ++ // Physical byte offsets of the file's allocation extents within the ISO image, or ++ // {@link #UNRECORDED_EXTENT_OFFSET} for zero-filled unrecorded extents. ++ public final long[] extentOffsets; ++ ++ // Logical byte lengths corresponding to {@link #extentOffsets}. ++ public final long[] extentLengths; ++ + public IsoFileEntry(String name, long byteOffset, long length) { ++ this(name, new long[] {byteOffset}, new long[] {length}, length); ++ } ++ ++ public IsoFileEntry(String name, long[] extentOffsets, long[] extentLengths, long length) { ++ if (extentOffsets.length == 0 || extentOffsets.length != extentLengths.length) { ++ throw new IllegalArgumentException("Invalid ISO file extents"); ++ } ++ if (length < 0) { ++ throw new IllegalArgumentException("Invalid ISO file length"); ++ } ++ long totalExtentLength = 0; ++ try { ++ for (int i = 0; i < extentOffsets.length; i++) { ++ if ((extentOffsets[i] < 0 && extentOffsets[i] != UNRECORDED_EXTENT_OFFSET) ++ || extentLengths[i] < 0) { ++ throw new IllegalArgumentException("Invalid ISO file extent"); ++ } ++ totalExtentLength = Math.addExact(totalExtentLength, extentLengths[i]); ++ } ++ } catch (ArithmeticException e) { ++ throw new IllegalArgumentException("ISO file extent length overflow", e); ++ } ++ if (length > totalExtentLength) { ++ throw new IllegalArgumentException("ISO file length exceeds its extents"); ++ } + this.name = name; +- this.byteOffset = byteOffset; ++ this.byteOffset = extentOffsets[0]; + this.length = length; ++ this.extentOffsets = Arrays.copyOf(extentOffsets, extentOffsets.length); ++ this.extentLengths = Arrays.copyOf(extentLengths, extentLengths.length); + } + } +diff --git a/libraries/extractor/src/main/java/androidx/media3/extractor/iso/dvd/DvdCell.java b/libraries/extractor/src/main/java/androidx/media3/extractor/iso/dvd/DvdCell.java +index 5edb848604..2a3b87cfec 100644 +--- a/libraries/extractor/src/main/java/androidx/media3/extractor/iso/dvd/DvdCell.java ++++ b/libraries/extractor/src/main/java/androidx/media3/extractor/iso/dvd/DvdCell.java +@@ -15,6 +15,8 @@ + */ + package androidx.media3.extractor.iso.dvd; + ++import java.util.Arrays; ++ + public final class DvdCell { + + /** +@@ -27,6 +29,12 @@ public final class DvdCell { + */ + public final long length; + ++ /** Physical byte offsets containing this cell's data, in playback order. */ ++ public final long[] extentOffsets; ++ ++ /** Byte lengths corresponding to {@link #extentOffsets}. */ ++ public final long[] extentLengths; ++ + /** + * Duration of this cell in microseconds. + */ +@@ -45,8 +53,23 @@ public final class DvdCell { + public final long lastSector; + + public DvdCell(long byteOffset, long length, long durationUs, long firstSector, long lastSector) { +- this.byteOffset = byteOffset; ++ this(new long[] {byteOffset}, new long[] {length}, length, durationUs, firstSector, lastSector); ++ } ++ ++ public DvdCell( ++ long[] extentOffsets, ++ long[] extentLengths, ++ long length, ++ long durationUs, ++ long firstSector, ++ long lastSector) { ++ if (extentOffsets.length == 0 || extentOffsets.length != extentLengths.length) { ++ throw new IllegalArgumentException("Invalid DVD cell extents"); ++ } ++ this.byteOffset = extentOffsets[0]; + this.length = length; ++ this.extentOffsets = Arrays.copyOf(extentOffsets, extentOffsets.length); ++ this.extentLengths = Arrays.copyOf(extentLengths, extentLengths.length); + this.durationUs = durationUs; + this.firstSector = firstSector; + this.lastSector = lastSector; +diff --git a/libraries/extractor/src/main/java/androidx/media3/extractor/iso/dvd/DvdIfoParser.java b/libraries/extractor/src/main/java/androidx/media3/extractor/iso/dvd/DvdIfoParser.java +index 626ef26a6d..f0bc5ff46c 100644 +--- a/libraries/extractor/src/main/java/androidx/media3/extractor/iso/dvd/DvdIfoParser.java ++++ b/libraries/extractor/src/main/java/androidx/media3/extractor/iso/dvd/DvdIfoParser.java +@@ -102,20 +102,29 @@ public final class DvdIfoParser { + this.udf = udf; + } + +- private static long vobSectorToByteOffset(long[][] vobParts, long sector) { ++ static long[][] vobSectorRangeToExtents(long[][] vobParts, long firstSector, long lastSector) { ++ List extents = new ArrayList<>(); ++ long sector = firstSector; + for (long[] part : vobParts) { + long partStart = part[0]; + long partByteOffset = part[1]; + long partSectors = part[2]; +- if (sector >= partStart && sector < partStart + partSectors) { +- return partByteOffset + (sector - partStart) * SECTOR_SIZE; ++ long partEnd = partStart + partSectors; ++ if (sector >= partStart && sector < partEnd) { ++ long extentEndSector = Math.min(lastSector + 1, partEnd); ++ extents.add(new long[] { ++ partByteOffset == IsoFileEntry.UNRECORDED_EXTENT_OFFSET ++ ? IsoFileEntry.UNRECORDED_EXTENT_OFFSET ++ : partByteOffset + (sector - partStart) * SECTOR_SIZE, ++ (extentEndSector - sector) * SECTOR_SIZE ++ }); ++ sector = extentEndSector; ++ if (sector > lastSector) { ++ break; ++ } + } + } +- if (vobParts.length > 0) { +- long[] last = vobParts[vobParts.length - 1]; +- return last[1] + (sector - last[0]) * SECTOR_SIZE; +- } +- return sector * SECTOR_SIZE; ++ return sector > lastSector ? extents.toArray(new long[0][]) : new long[0][]; + } + + private static int parseVtsNum(String ifoName) { +@@ -294,9 +303,18 @@ public final class DvdIfoParser { + long durationUs = decodeDvdTime(pgcData, cpOffset + CELL_DURATION_OFFSET); + long firstSector = pgcBB.getInt(cpOffset + CELL_FIRST_SECTOR_OFFSET) & 0xFFFFFFFFL; + long lastSector = pgcBB.getInt(cpOffset + CELL_LAST_SECTOR_OFFSET) & 0xFFFFFFFFL; +- long byteOffset = vobSectorToByteOffset(vobParts, firstSector); + long length = (lastSector - firstSector + 1) * SECTOR_SIZE; +- cells.add(new DvdCell(byteOffset, length, durationUs, firstSector, lastSector)); ++ long[][] cellExtents = vobSectorRangeToExtents(vobParts, firstSector, lastSector); ++ if (cellExtents.length == 0) { ++ continue; ++ } ++ long[] extentOffsets = new long[cellExtents.length]; ++ long[] extentLengths = new long[cellExtents.length]; ++ for (int i = 0; i < cellExtents.length; i++) { ++ extentOffsets[i] = cellExtents[i][0]; ++ extentLengths[i] = cellExtents[i][1]; ++ } ++ cells.add(new DvdCell(extentOffsets, extentLengths, length, durationUs, firstSector, lastSector)); + } + String[] audioLanguages = new String[MAX_AUDIO_STREAMS]; + int[] audioFormats = new int[MAX_AUDIO_STREAMS]; +@@ -388,8 +406,14 @@ public final class DvdIfoParser { + break; + } + long partSectors = entry.length / SECTOR_SIZE; +- parts.add(new long[]{cumSectors, entry.byteOffset, partSectors}); +- cumSectors += partSectors; ++ for (int i = 0; i < entry.extentOffsets.length; i++) { ++ long extentSectors = entry.extentLengths[i] / SECTOR_SIZE; ++ if (extentSectors == 0) { ++ continue; ++ } ++ parts.add(new long[]{cumSectors, entry.extentOffsets[i], extentSectors}); ++ cumSectors += extentSectors; ++ } + } catch (IOException e) { + break; + } +@@ -452,7 +476,11 @@ public final class DvdIfoParser { + IsoFileEntry entry = udf.findFile(ifoPath); + if (entry != null) { + ifoCache.put(ifoPath, entry); +- offsets.add(entry.byteOffset); ++ for (long extentOffset : entry.extentOffsets) { ++ if (extentOffset != IsoFileEntry.UNRECORDED_EXTENT_OFFSET) { ++ offsets.add(extentOffset); ++ } ++ } + } + } + if (offsets.isEmpty()) { +@@ -489,19 +517,39 @@ public final class DvdIfoParser { + } + ifoCache.put(ifoPath, entry); + } +- return readAbsolute(entry.byteOffset + sectorOffset * SECTOR_SIZE, numSectors * SECTOR_SIZE); ++ return readLogical(entry, sectorOffset * SECTOR_SIZE, numSectors * SECTOR_SIZE); + } + +- private byte[] readAbsolute(long byteOffset, int length) throws IOException { ++ private byte[] readLogical(IsoFileEntry entry, long logicalOffset, int length) throws IOException { ++ if (logicalOffset < 0 || length < 0 || logicalOffset > entry.length - length) { ++ throw new IOException("DVD: IFO read out of range: " + entry.name); ++ } + byte[] data = new byte[length]; + int pos = 0; +- while (pos < length) { +- int n = reader.read(byteOffset + pos, data, pos, length - pos); +- if (n == -1) { +- break; ++ long extentLogicalStart = 0; ++ for (int i = 0; i < entry.extentOffsets.length && pos < length; i++) { ++ long extentLength = entry.extentLengths[i]; ++ long extentLogicalEnd = extentLogicalStart + extentLength; ++ if (logicalOffset < extentLogicalEnd) { ++ long offsetInExtent = Math.max(0, logicalOffset - extentLogicalStart); ++ int extentReadLength = (int) Math.min(extentLength - offsetInExtent, length - pos); ++ if (entry.extentOffsets[i] == IsoFileEntry.UNRECORDED_EXTENT_OFFSET) { ++ Arrays.fill(data, pos, pos + extentReadLength, (byte) 0); ++ pos += extentReadLength; ++ } else { ++ int extentRead = 0; ++ while (extentRead < extentReadLength) { ++ int n = reader.read(entry.extentOffsets[i] + offsetInExtent + extentRead, data, pos, extentReadLength - extentRead); ++ if (n <= 0) throw new IOException("DVD: short IFO read: " + entry.name); ++ extentRead += n; ++ pos += n; ++ } ++ } ++ logicalOffset += extentReadLength; + } +- pos += n; ++ extentLogicalStart = extentLogicalEnd; + } ++ if (pos != length) throw new IOException("DVD: short IFO read: " + entry.name); + return data; + } + } +diff --git a/libraries/extractor/src/main/java/androidx/media3/extractor/iso/udf/UdfFileSystem.java b/libraries/extractor/src/main/java/androidx/media3/extractor/iso/udf/UdfFileSystem.java +index 0cacd9c459..1ac200bf83 100644 +--- a/libraries/extractor/src/main/java/androidx/media3/extractor/iso/udf/UdfFileSystem.java ++++ b/libraries/extractor/src/main/java/androidx/media3/extractor/iso/udf/UdfFileSystem.java +@@ -27,9 +27,11 @@ import java.nio.charset.StandardCharsets; + import java.util.ArrayList; + import java.util.Arrays; + import java.util.HashMap; ++import java.util.HashSet; + import java.util.List; + import java.util.Locale; + import java.util.Map; ++import java.util.Set; + + public final class UdfFileSystem { + +@@ -50,7 +52,6 @@ public final class UdfFileSystem { + + private static final int LVD_NUM_PARTITION_MAPS_OFFSET = 268; + private static final int LVD_PARTITION_MAPS_START = 440; +- private static final int PM_TYPE2_MIN_SIZE = 40; + private static final int PM_TYPE2_ID_OFFSET = 5; + private static final int PM_TYPE2_ID_LENGTH = 8; + private static final int PM_META_FILOC_OFFSET = 40; +@@ -68,6 +69,7 @@ public final class UdfFileSystem { + + private static final int TAG_FSD = 256; + private static final int TAG_FID = 257; ++ private static final int TAG_AED = 258; + private static final int TAG_FE = 261; + private static final int TAG_EFE = 266; + private static final int TAG_AVDP = 2; +@@ -75,6 +77,7 @@ public final class UdfFileSystem { + private static final int TAG_LVD = 6; + private static final int TAG_TD = 8; + ++ private static final int AD_SHORT = 0; + private static final int AD_LONG = 1; + private static final int AD_EXTENDED = 2; + private static final int AD_EMBEDDED = 3; +@@ -82,10 +85,10 @@ public final class UdfFileSystem { + private static final int AD_SHORT_SIZE = 8; + private static final int AD_LONG_SIZE = 16; + private static final int AD_EXTENDED_SIZE = 20; +- +- private static final int ENTRY_OFFSET = 0; +- private static final int ENTRY_SIZE = 1; +- private static final int ENTRY_IS_DIR = 2; ++ private static final int AED_AD_LENGTH_OFFSET = 20; ++ private static final int AED_AD_START_OFFSET = 24; ++ private static final int MAX_ALLOCATION_DESCRIPTOR_BYTES = 1024 * 1024; ++ private static final int MAX_ALLOCATION_DESCRIPTOR_CONTINUATIONS = 64; + + private static final int FID_MIN_SIZE = 38; + private static final int FID_FILE_CHARS_OFFSET = 18; +@@ -125,15 +128,15 @@ public final class UdfFileSystem { + return null; + } + } +- Map entries = readDirectoryEntries(dirLbn); ++ Map entries = readDirectoryEntries(dirLbn); + String nameLower = fileName.toLowerCase(Locale.US); +- for (Map.Entry e : entries.entrySet()) { ++ for (Map.Entry e : entries.entrySet()) { + if (e.getKey().toLowerCase(Locale.US).equals(nameLower)) { +- long[] v = e.getValue(); +- if (v[ENTRY_IS_DIR] != 0) { ++ DirectoryEntry entry = e.getValue(); ++ if (entry.isDirectory || entry.extentOffsets.length == 0) { + return null; + } +- return v[ENTRY_OFFSET] >= 0 ? new IsoFileEntry(e.getKey(), v[ENTRY_OFFSET], v[ENTRY_SIZE]) : null; ++ return new IsoFileEntry(e.getKey(), entry.extentOffsets, entry.extentLengths, entry.length); + } + } + return null; +@@ -160,7 +163,10 @@ public final class UdfFileSystem { + long mvdsLengthBytes = (long) VDS_DEFAULT_SECTORS * SECTOR_SIZE; + long rvdsLocation = -1; + long rvdsLengthBytes = 0; +- long[] avdpCandidates = totalSectors > AVDP_SECTOR_MAIN ? new long[]{AVDP_SECTOR_MAIN, AVDP_SECTOR_RESERVE, totalSectors - AVDP_SECTOR_MAIN} : new long[]{AVDP_SECTOR_MAIN, AVDP_SECTOR_RESERVE}; ++ long[] avdpCandidates = ++ totalSectors > AVDP_SECTOR_MAIN ++ ? new long[] {AVDP_SECTOR_MAIN, AVDP_SECTOR_RESERVE, totalSectors - AVDP_SECTOR_MAIN} ++ : new long[] {AVDP_SECTOR_MAIN, AVDP_SECTOR_RESERVE}; + for (long avdpSector : avdpCandidates) { + if (!tryReadSector(avdpSector)) { + continue; +@@ -176,12 +182,12 @@ public final class UdfFileSystem { + if (mvdsLocation < 0) { + mvdsLocation = VDS_DEFAULT_SECTORS; + } +- long[] vdsResult = scanVds(mvdsLocation, mvdsLengthBytes); +- if (vdsResult[0] == 0 && rvdsLocation > 0) { ++ VdsResult vdsResult = scanVds(mvdsLocation, mvdsLengthBytes); ++ if (vdsResult.partitionStart == 0 && rvdsLocation > 0) { + vdsResult = scanVds(rvdsLocation, rvdsLengthBytes); + } +- long partitionStart = vdsResult[0]; +- long metaFileLoc = vdsResult[1]; ++ long partitionStart = vdsResult.partitionStart; ++ long metaFileLoc = vdsResult.metadataFileLocation; + if (partitionStart == 0) { + throw new IOException("UDF: PartitionDescriptor not found in VDS at sector " + mvdsLocation); + } +@@ -204,7 +210,7 @@ public final class UdfFileSystem { + rootIcbLbn = sectorBB.getInt(FSD_ROOT_ICB_OFFSET) & 0xFFFFFFFFL; + } + +- private long[] scanVds(long location, long lengthBytes) { ++ private VdsResult scanVds(long location, long lengthBytes) { + long sectors = Math.max(1, Util.ceilDivide(lengthBytes, SECTOR_SIZE)); + reader.prefetchRange(location * SECTOR_SIZE, (location + sectors) * SECTOR_SIZE); + long partitionStart = 0; +@@ -225,7 +231,7 @@ public final class UdfFileSystem { + break; + } + } +- return new long[]{partitionStart, metaFileLoc}; ++ return new VdsResult(partitionStart, metaFileLoc); + } + + private long scanForTag(long start, int count) { +@@ -254,8 +260,14 @@ public final class UdfFileSystem { + if (pmLen == 0) { + break; + } +- if (pmType == 2 && pos + PM_TYPE2_MIN_SIZE < SECTOR_SIZE) { +- String id8 = new String(sectorBuf, pos + PM_TYPE2_ID_OFFSET, PM_TYPE2_ID_LENGTH, StandardCharsets.ISO_8859_1); ++ int requiredMapLength = PM_META_FILOC_OFFSET + 4; ++ if (pmType == 2 && pmLen >= requiredMapLength && pos <= SECTOR_SIZE - pmLen) { ++ String id8 = ++ new String( ++ sectorBuf, ++ pos + PM_TYPE2_ID_OFFSET, ++ PM_TYPE2_ID_LENGTH, ++ StandardCharsets.ISO_8859_1); + if (id8.equals("*UDF Met")) { + return sectorBB.getInt(pos + PM_META_FILOC_OFFSET) & 0xFFFFFFFFL; + } +@@ -272,19 +284,19 @@ public final class UdfFileSystem { + if (part.isEmpty()) { + continue; + } +- Map entries = readDirectoryEntries(dirLbn); ++ Map entries = readDirectoryEntries(dirLbn); + String nameLower = part.toLowerCase(Locale.US); +- long[] found = null; +- for (Map.Entry e : entries.entrySet()) { ++ @Nullable DirectoryEntry found = null; ++ for (Map.Entry e : entries.entrySet()) { + if (e.getKey().toLowerCase(Locale.US).equals(nameLower)) { + found = e.getValue(); + break; + } + } +- if (found == null || found[ENTRY_IS_DIR] == 0) { ++ if (found == null || !found.isDirectory) { + return -1; + } +- dirLbn = found[ENTRY_OFFSET]; ++ dirLbn = found.logicalBlockNumber; + } + return dirLbn; + } +@@ -293,55 +305,90 @@ public final class UdfFileSystem { + return new ArrayList<>(readDirectoryEntries(dirLbn).keySet()); + } + +- private Map readDirectoryEntries(long dirLbn) throws IOException { ++ private Map readDirectoryEntries(long dirLbn) throws IOException { + readSector(fsdPhysicalSector + dirLbn); + int tagId = readTag(); + if (tagId != TAG_FE && tagId != TAG_EFE) { + throw new IOException("UDF: expected FE/EFE at lbn=" + dirLbn + ", got tag=" + tagId); + } +- long[] layout = readFileEntryLayout(tagId); +- int adOffset = (int) layout[0]; +- int adLength = (int) layout[1]; +- int adType = (int) layout[2]; +- long infoLength = layout[3]; ++ FileEntryLayout layout = readFileEntryLayout(tagId); + byte[] feSector = sectorBuf.clone(); +- Map result = new HashMap<>(); +- if (adType == AD_EMBEDDED) { +- parseDirectoryData(feSector, adOffset, adLength, result); ++ Map result = new HashMap<>(); ++ if (layout.allocationDescriptorType == AD_EMBEDDED) { ++ parseDirectoryData( ++ feSector, layout.allocationDescriptorOffset, layout.allocationDescriptorLength, result); + } else { +- byte[] dirData = readAllocDesc(feSector, adOffset, adLength, adType, (int) infoLength); ++ if (layout.informationLength > Integer.MAX_VALUE) { ++ throw new IOException("UDF: directory is too large"); ++ } ++ byte[] dirData = ++ readAllocDesc( ++ feSector, ++ layout.allocationDescriptorOffset, ++ layout.allocationDescriptorLength, ++ layout.allocationDescriptorType, ++ (int) layout.informationLength); + parseDirectoryData(dirData, 0, dirData.length, result); + } + return result; + } + +- private byte[] readAllocDesc(byte[] feSector, int adOffset, int adLength, int adType, int totalLength) throws IOException { ++ private byte[] readAllocDesc( ++ byte[] feSector, int adOffset, int adLength, int adType, int totalLength) throws IOException { + byte[] data = new byte[totalLength]; + int dataPos = 0; +- int pos = adOffset; +- int end = adOffset + adLength; +- ByteBuffer feBB = ByteBuffer.wrap(feSector).order(ByteOrder.LITTLE_ENDIAN); +- while (pos < end && dataPos < totalLength) { +- long[] ad = readExtentAd(feBB, pos, adType, false); +- long lbn = ad[0]; +- long base = ad[1]; +- int extentLength = (int) ad[2]; +- pos = (int) ad[3]; +- if (extentLength == 0) { ++ List allocationDescriptors = ++ readExtentAds(feSector, adOffset, adLength, adType, /* resolvePartRef= */ false); ++ for (AllocationDescriptor descriptor : allocationDescriptors) { ++ if (dataPos >= totalLength) { ++ break; ++ } ++ if (descriptor.allocationLength == 0) { ++ continue; ++ } ++ if (descriptor.extentType == 1 || descriptor.extentType == 2) { ++ int zeroLength = (int) Math.min(descriptor.informationLength, totalLength - dataPos); ++ Arrays.fill(data, dataPos, dataPos + zeroLength, (byte) 0); ++ dataPos += zeroLength; + continue; + } +- int numSectors = Util.ceilDivide(extentLength, SECTOR_SIZE); +- for (int s = 0; s < numSectors && dataPos < totalLength; s++) { +- readSector(base + lbn + s); +- int toCopy = Math.min(SECTOR_SIZE, totalLength - dataPos); ++ if (descriptor.extentType != 0) { ++ throw new IOException("UDF: unsupported directory extent type " + descriptor.extentType); ++ } ++ if (descriptor.recordedLength != descriptor.informationLength ++ || descriptor.recordedLength > descriptor.allocationLength) { ++ throw new IOException("UDF: unsupported directory extent lengths"); ++ } ++ if (descriptor.informationLength == 0) { ++ continue; ++ } ++ if (descriptor.informationLength > Integer.MAX_VALUE) { ++ throw new IOException("UDF: directory extent is too large"); ++ } ++ int extentInformationLength = (int) descriptor.informationLength; ++ int numSectors = Util.ceilDivide(extentInformationLength, SECTOR_SIZE); ++ int extentBytesRead = 0; ++ for (int s = 0; ++ s < numSectors && dataPos < totalLength && extentBytesRead < extentInformationLength; ++ s++) { ++ readSector(descriptor.partitionStart + descriptor.logicalBlockNumber + s); ++ int toCopy = ++ Math.min( ++ Math.min(SECTOR_SIZE, extentInformationLength - extentBytesRead), ++ totalLength - dataPos); + System.arraycopy(sectorBuf, 0, data, dataPos, toCopy); + dataPos += toCopy; ++ extentBytesRead += toCopy; + } + } + return data; + } + +- private void parseDirectoryData(byte[] data, int offset, int length, Map out) { ++ private void parseDirectoryData( ++ byte[] data, int offset, int length, Map out) throws IOException { ++ if (offset < 0 || length < 0 || offset > data.length - length) { ++ throw new IOException("UDF: invalid directory data range"); ++ } + ByteBuffer bb = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN); + int pos = offset; + int end = offset + length; +@@ -354,17 +401,22 @@ public final class UdfFileSystem { + int fiLength = data[pos + FID_FI_LENGTH_OFFSET] & 0xFF; + long icbLbn = bb.getInt(pos + FID_ICB_LBN_OFFSET) & 0xFFFFFFFFL; + int implUseLength = bb.getShort(pos + FID_IMPL_USE_LEN_OFFSET) & 0xFFFF; ++ if (implUseLength > end - pos - FID_MIN_SIZE) { ++ throw new IOException("UDF: truncated file identifier implementation data"); ++ } + int nameOffset = pos + FID_MIN_SIZE + implUseLength; ++ if (fiLength > end - nameOffset) { ++ throw new IOException("UDF: truncated file identifier name"); ++ } + boolean isDir = (fileChars & 0x02) != 0; + boolean isParent = (fileChars & 0x08) != 0; + if (!isParent && fiLength > 0) { + String name = decodeOsta(data, nameOffset, fiLength); + if (isDir) { +- out.put(name, new long[]{icbLbn, 0, 1}); ++ out.put(name, DirectoryEntry.forDirectory(icbLbn)); + } else { + try { +- long[] fileInfo = resolveFileEntry(icbLbn); +- out.put(name, new long[]{fileInfo[ENTRY_OFFSET], fileInfo[ENTRY_SIZE], 0}); ++ out.put(name, resolveFileEntry(icbLbn)); + } catch (IOException ignored) { + } + } +@@ -375,65 +427,207 @@ public final class UdfFileSystem { + } + } + +- private long[] resolveFileEntry(long icbLbn) throws IOException { ++ private DirectoryEntry resolveFileEntry(long icbLbn) throws IOException { + readSector(fsdPhysicalSector + icbLbn); + int tagId = readTag(); + if (tagId != TAG_FE && tagId != TAG_EFE) { + throw new IOException("UDF: expected FE/EFE at icbLbn=" + icbLbn + ", got tag=" + tagId); + } +- long[] layout = readFileEntryLayout(tagId); +- int adOffset = (int) layout[0]; +- int adLength = (int) layout[1]; +- int adType = (int) layout[2]; +- long infoLength = layout[3]; +- if (adType == AD_EMBEDDED || adLength == 0) { +- return new long[]{-1, infoLength}; ++ FileEntryLayout layout = readFileEntryLayout(tagId); ++ if (layout.allocationDescriptorType == AD_EMBEDDED || layout.allocationDescriptorLength == 0) { ++ return DirectoryEntry.forUnresolvedFile(layout.informationLength); + } + byte[] feSector = sectorBuf.clone(); +- ByteBuffer feBB = ByteBuffer.wrap(feSector).order(ByteOrder.LITTLE_ENDIAN); +- int pos = adOffset; +- int end = adOffset + adLength; +- long firstByteOffset = -1; +- long nextExpectedSector = -1; +- while (pos < end) { +- long[] ad = readExtentAd(feBB, pos, adType, true); +- long lbn = ad[0]; +- long base = ad[1]; +- int extentLength = (int) ad[2]; +- pos = (int) ad[3]; +- if (extentLength == 0) { ++ List extentOffsets = new ArrayList<>(); ++ List extentLengths = new ArrayList<>(); ++ long remainingLength = layout.informationLength; ++ List allocationDescriptors = ++ readExtentAds( ++ feSector, ++ layout.allocationDescriptorOffset, ++ layout.allocationDescriptorLength, ++ layout.allocationDescriptorType, ++ /* resolvePartRef= */ true); ++ for (AllocationDescriptor descriptor : allocationDescriptors) { ++ if (remainingLength <= 0) { ++ break; ++ } ++ if (descriptor.allocationLength == 0) { + continue; + } +- long physicalSector = base + lbn; +- if (firstByteOffset < 0) { +- firstByteOffset = physicalSector * SECTOR_SIZE; +- } else if (physicalSector != nextExpectedSector) { ++ if (descriptor.extentType == 1 || descriptor.extentType == 2) { ++ long logicalExtentLength = Math.min(descriptor.informationLength, remainingLength); ++ if (logicalExtentLength > 0) { ++ extentOffsets.add(IsoFileEntry.UNRECORDED_EXTENT_OFFSET); ++ extentLengths.add(logicalExtentLength); ++ remainingLength -= logicalExtentLength; ++ } ++ continue; ++ } ++ if (descriptor.extentType != 0 ++ || descriptor.recordedLength != descriptor.informationLength ++ || descriptor.recordedLength > descriptor.allocationLength) { ++ return DirectoryEntry.forUnresolvedFile(layout.informationLength); ++ } ++ if (descriptor.informationLength == 0) { ++ continue; ++ } ++ long physicalSector; ++ long physicalByteOffset; ++ try { ++ physicalSector = Math.addExact(descriptor.partitionStart, descriptor.logicalBlockNumber); ++ physicalByteOffset = Math.multiplyExact(physicalSector, (long) SECTOR_SIZE); ++ } catch (ArithmeticException e) { ++ return DirectoryEntry.forUnresolvedFile(layout.informationLength); ++ } ++ long logicalExtentLength = Math.min(descriptor.informationLength, remainingLength); ++ extentOffsets.add(physicalByteOffset); ++ extentLengths.add(logicalExtentLength); ++ remainingLength -= logicalExtentLength; ++ } ++ if (extentOffsets.isEmpty() || remainingLength > 0) { ++ return DirectoryEntry.forUnresolvedFile(layout.informationLength); ++ } ++ long[] offsetArray = new long[extentOffsets.size()]; ++ long[] lengthArray = new long[extentLengths.size()]; ++ for (int i = 0; i < extentOffsets.size(); i++) { ++ offsetArray[i] = extentOffsets.get(i); ++ lengthArray[i] = extentLengths.get(i); ++ } ++ return DirectoryEntry.forFile(layout.informationLength, offsetArray, lengthArray); ++ } ++ ++ List readExtentAds( ++ byte[] initialData, int initialOffset, int initialLength, int adType, boolean resolvePartRef) ++ throws IOException { ++ if (initialOffset < 0 ++ || initialLength < 0 ++ || initialOffset > initialData.length - initialLength) { ++ throw new IOException("UDF: invalid allocation descriptor range"); ++ } ++ List allocationDescriptors = new ArrayList<>(); ++ Set continuationOffsets = new HashSet<>(); ++ byte[] descriptorData = initialData; ++ int position = initialOffset; ++ int end = initialOffset + initialLength; ++ int descriptorSize = getAllocationDescriptorSize(adType); ++ int continuationCount = 0; ++ while (true) { ++ ByteBuffer descriptorBuffer = ByteBuffer.wrap(descriptorData).order(ByteOrder.LITTLE_ENDIAN); ++ boolean hasContinuation = false; ++ while (position < end) { ++ if (position + descriptorSize > end) { ++ throw new IOException("UDF: truncated allocation descriptor"); ++ } ++ AllocationDescriptor allocationDescriptor = ++ readExtentAd(descriptorBuffer, position, adType, resolvePartRef); ++ position = allocationDescriptor.nextPosition; ++ if (allocationDescriptor.allocationLength == 0) { ++ return allocationDescriptors; ++ } ++ if (allocationDescriptor.extentType != 3) { ++ allocationDescriptors.add(allocationDescriptor); ++ continue; ++ } ++ if (++continuationCount > MAX_ALLOCATION_DESCRIPTOR_CONTINUATIONS) { ++ throw new IOException("UDF: too many allocation descriptor continuations"); ++ } ++ long continuationOffset; ++ try { ++ continuationOffset = ++ Math.multiplyExact( ++ Math.addExact( ++ allocationDescriptor.partitionStart, allocationDescriptor.logicalBlockNumber), ++ SECTOR_SIZE); ++ } catch (ArithmeticException e) { ++ throw new IOException("UDF: allocation descriptor continuation overflow", e); ++ } ++ if (!continuationOffsets.add(continuationOffset)) { ++ throw new IOException("UDF: cyclic allocation descriptor continuation"); ++ } ++ if (allocationDescriptor.allocationLength < AED_AD_START_OFFSET ++ || allocationDescriptor.allocationLength > MAX_ALLOCATION_DESCRIPTOR_BYTES) { ++ throw new IOException( ++ "UDF: invalid allocation descriptor continuation length: " ++ + allocationDescriptor.allocationLength); ++ } ++ descriptorData = readBytes(continuationOffset, allocationDescriptor.allocationLength); ++ descriptorBuffer = ByteBuffer.wrap(descriptorData).order(ByteOrder.LITTLE_ENDIAN); ++ if ((descriptorBuffer.getShort(0) & 0xFFFF) != TAG_AED) { ++ throw new IOException("UDF: expected allocation extent descriptor"); ++ } ++ int continuationAdLength = descriptorBuffer.getInt(AED_AD_LENGTH_OFFSET); ++ if (continuationAdLength < 0 ++ || continuationAdLength > descriptorData.length - AED_AD_START_OFFSET) { ++ throw new IOException("UDF: invalid continued allocation descriptor length"); ++ } ++ position = AED_AD_START_OFFSET; ++ end = AED_AD_START_OFFSET + continuationAdLength; ++ hasContinuation = true; + break; + } +- nextExpectedSector = physicalSector + Util.ceilDivide(extentLength, SECTOR_SIZE); ++ if (!hasContinuation) { ++ return allocationDescriptors; ++ } + } +- return new long[]{firstByteOffset < 0 ? -1 : firstByteOffset, infoLength}; + } + +- private long[] readFileEntryLayout(int tagId) { ++ private static int getAllocationDescriptorSize(int adType) throws IOException { ++ switch (adType) { ++ case AD_LONG: ++ return AD_LONG_SIZE; ++ case AD_EXTENDED: ++ return AD_EXTENDED_SIZE; ++ case AD_SHORT: ++ return AD_SHORT_SIZE; ++ default: ++ throw new IOException("UDF: unsupported allocation descriptor type " + adType); ++ } ++ } ++ ++ private byte[] readBytes(long byteOffset, int length) throws IOException { ++ byte[] data = new byte[length]; ++ int totalRead = 0; ++ while (totalRead < length) { ++ int bytesRead = reader.read(byteOffset + totalRead, data, totalRead, length - totalRead); ++ if (bytesRead <= 0) { ++ throw new IOException("UDF: short allocation descriptor continuation read"); ++ } ++ totalRead += bytesRead; ++ } ++ return data; ++ } ++ ++ private FileEntryLayout readFileEntryLayout(int tagId) throws IOException { + long infoLength = sectorBB.getLong(FE_INFO_LENGTH_OFFSET); + int icbTagFlags = sectorBB.getShort(FE_ICB_TAG_FLAGS_OFFSET) & 0xFFFF; + int adType = icbTagFlags & 0x7; +- int eaLength, adLength, adOffset; ++ int eaLength, adLength, adStart; + if (tagId == TAG_FE) { + eaLength = sectorBB.getInt(FE_EA_LENGTH_OFFSET); + adLength = sectorBB.getInt(FE_AD_LENGTH_OFFSET); +- adOffset = FE_AD_START_OFFSET + eaLength; ++ adStart = FE_AD_START_OFFSET; + } else { + eaLength = sectorBB.getInt(EFE_EA_LENGTH_OFFSET); + adLength = sectorBB.getInt(EFE_AD_LENGTH_OFFSET); +- adOffset = EFE_AD_START_OFFSET + eaLength; ++ adStart = EFE_AD_START_OFFSET; ++ } ++ if (infoLength < 0 ++ || eaLength < 0 ++ || adLength < 0 ++ || eaLength > SECTOR_SIZE - adStart ++ || adLength > SECTOR_SIZE - adStart - eaLength) { ++ throw new IOException("UDF: invalid file entry layout"); + } +- return new long[]{adOffset, adLength, adType, infoLength}; ++ return new FileEntryLayout(adStart + eaLength, adLength, adType, infoLength); + } + +- private long[] readExtentAd(ByteBuffer bb, int pos, int adType, boolean resolvePartRef) { +- int extentLength = bb.getInt(pos) & 0x3FFFFFFF; ++ AllocationDescriptor readExtentAd(ByteBuffer bb, int pos, int adType, boolean resolvePartRef) { ++ int rawExtentLength = bb.getInt(pos); ++ int extentType = rawExtentLength >>> 30; ++ int allocationLength = rawExtentLength & 0x3FFFFFFF; ++ long recordedLength = allocationLength; ++ long informationLength = allocationLength; + long lbn; + long base = fsdPhysicalSector; + int nextPos; +@@ -447,6 +641,8 @@ public final class UdfFileSystem { + nextPos = pos + AD_LONG_SIZE; + break; + case AD_EXTENDED: ++ recordedLength = bb.getInt(pos + 4) & 0x3FFFFFFFL; ++ informationLength = bb.getInt(pos + 8) & 0xFFFFFFFFL; + lbn = bb.getInt(pos + 12) & 0xFFFFFFFFL; + if (resolvePartRef) { + int partRef = bb.getShort(pos + 16) & 0xFFFF; +@@ -454,7 +650,7 @@ public final class UdfFileSystem { + } + nextPos = pos + AD_EXTENDED_SIZE; + break; +- default: ++ case AD_SHORT: + lbn = bb.getInt(pos + 4) & 0xFFFFFFFFL; + if (metadataPartitionSectors > 0 && lbn < metadataPartitionSectors) { + base = fsdPhysicalSector; +@@ -463,8 +659,109 @@ public final class UdfFileSystem { + } + nextPos = pos + AD_SHORT_SIZE; + break; ++ default: ++ throw new IllegalArgumentException("Unsupported allocation descriptor type " + adType); ++ } ++ return new AllocationDescriptor( ++ lbn, base, informationLength, nextPos, extentType, recordedLength, allocationLength); ++ } ++ ++ static final class AllocationDescriptor { ++ ++ final long logicalBlockNumber; ++ final long partitionStart; ++ final long informationLength; ++ final int nextPosition; ++ final int extentType; ++ final long recordedLength; ++ final int allocationLength; ++ ++ private AllocationDescriptor( ++ long logicalBlockNumber, ++ long partitionStart, ++ long informationLength, ++ int nextPosition, ++ int extentType, ++ long recordedLength, ++ int allocationLength) { ++ this.logicalBlockNumber = logicalBlockNumber; ++ this.partitionStart = partitionStart; ++ this.informationLength = informationLength; ++ this.nextPosition = nextPosition; ++ this.extentType = extentType; ++ this.recordedLength = recordedLength; ++ this.allocationLength = allocationLength; ++ } ++ } ++ ++ private static final class FileEntryLayout { ++ ++ final int allocationDescriptorOffset; ++ final int allocationDescriptorLength; ++ final int allocationDescriptorType; ++ final long informationLength; ++ ++ FileEntryLayout( ++ int allocationDescriptorOffset, ++ int allocationDescriptorLength, ++ int allocationDescriptorType, ++ long informationLength) { ++ this.allocationDescriptorOffset = allocationDescriptorOffset; ++ this.allocationDescriptorLength = allocationDescriptorLength; ++ this.allocationDescriptorType = allocationDescriptorType; ++ this.informationLength = informationLength; ++ } ++ } ++ ++ private static final class VdsResult { ++ ++ final long partitionStart; ++ final long metadataFileLocation; ++ ++ VdsResult(long partitionStart, long metadataFileLocation) { ++ this.partitionStart = partitionStart; ++ this.metadataFileLocation = metadataFileLocation; ++ } ++ } ++ ++ private static final class DirectoryEntry { ++ ++ final long logicalBlockNumber; ++ final long length; ++ final boolean isDirectory; ++ final long[] extentOffsets; ++ final long[] extentLengths; ++ ++ static DirectoryEntry forDirectory(long logicalBlockNumber) { ++ return new DirectoryEntry( ++ logicalBlockNumber, /* length= */ 0, /* isDirectory= */ true, new long[0], new long[0]); ++ } ++ ++ static DirectoryEntry forUnresolvedFile(long length) { ++ return forFile(length, new long[0], new long[0]); ++ } ++ ++ static DirectoryEntry forFile(long length, long[] extentOffsets, long[] extentLengths) { ++ return new DirectoryEntry( ++ /* logicalBlockNumber= */ 0, ++ length, ++ /* isDirectory= */ false, ++ extentOffsets, ++ extentLengths); ++ } ++ ++ private DirectoryEntry( ++ long logicalBlockNumber, ++ long length, ++ boolean isDirectory, ++ long[] extentOffsets, ++ long[] extentLengths) { ++ this.logicalBlockNumber = logicalBlockNumber; ++ this.length = length; ++ this.isDirectory = isDirectory; ++ this.extentOffsets = extentOffsets; ++ this.extentLengths = extentLengths; + } +- return new long[]{lbn, base, extentLength, nextPos}; + } + + private String decodeOsta(byte[] data, int offset, int length) { +@@ -483,13 +780,24 @@ public final class UdfFileSystem { + } + + private void readSector(long sectorNumber) throws IOException { +- long byteOffset = sectorNumber * SECTOR_SIZE; ++ if (sectorNumber < 0) { ++ throw new IOException("UDF: invalid negative sector"); ++ } ++ long byteOffset; ++ try { ++ byteOffset = Math.multiplyExact(sectorNumber, (long) SECTOR_SIZE); ++ } catch (ArithmeticException e) { ++ throw new IOException("UDF: sector offset overflow", e); ++ } + int total = 0; + while (total < SECTOR_SIZE) { + int n = reader.read(byteOffset + total, sectorBuf, total, SECTOR_SIZE - total); + if (n == -1) { + break; + } ++ if (n == 0) { ++ throw new IOException("UDF: reader made no progress"); ++ } + total += n; + } + if (total < SECTOR_SIZE) { +@@ -506,4 +814,4 @@ public final class UdfFileSystem { + return false; + } + } +-} +\ No newline at end of file ++} + diff --git a/third_party/patches/media3-exo-iso-reader-safety.patch b/third_party/patches/media3-exo-iso-reader-safety.patch new file mode 100644 index 0000000000..b1175c49bf --- /dev/null +++ b/third_party/patches/media3-exo-iso-reader-safety.patch @@ -0,0 +1,206 @@ +diff --git a/libraries/datasource/src/main/java/androidx/media3/datasource/IsoDataReader.java b/libraries/datasource/src/main/java/androidx/media3/datasource/IsoDataReader.java +index 1eb011cb97..d667e18d52 100644 +--- a/libraries/datasource/src/main/java/androidx/media3/datasource/IsoDataReader.java ++++ b/libraries/datasource/src/main/java/androidx/media3/datasource/IsoDataReader.java +@@ -50,6 +50,9 @@ public final class IsoDataReader implements CacheDataReader, Closeable { + + @Override + public int read(long byteOffset, byte[] buf, int offset, int length) throws IOException { ++ if (length == 0) { ++ return 0; ++ } + long firstSector = byteOffset / SECTOR_SIZE; + long lastSector = (byteOffset + length - 1) / SECTOR_SIZE; + int filled = 0; +@@ -80,8 +83,15 @@ public final class IsoDataReader implements CacheDataReader, Closeable { + + @Override + public void prefetchRange(long startByteOffset, long endByteOffset) { ++ if (startByteOffset < 0 || endByteOffset <= startByteOffset) { ++ return; ++ } + long firstSector = startByteOffset / SECTOR_SIZE; + long lastSector = (endByteOffset - 1) / SECTOR_SIZE; ++ long sectorCount = lastSector - firstSector + 1; ++ if (sectorCount > CACHE_SECTORS) { ++ return; ++ } + synchronized (sectorCache) { + boolean allCached = true; + for (long s = firstSector; s <= lastSector; s++) { +@@ -94,7 +104,7 @@ public final class IsoDataReader implements CacheDataReader, Closeable { + return; + } + } +- int length = (int) ((lastSector - firstSector + 1) * SECTOR_SIZE); ++ int length = (int) (sectorCount * SECTOR_SIZE); + byte[] batch = new byte[length]; + try { + int total = directRead(firstSector * SECTOR_SIZE, batch, 0, length); +@@ -149,9 +159,9 @@ public final class IsoDataReader implements CacheDataReader, Closeable { + private int directRead(long byteOffset, byte[] buf, int offset, int length) throws IOException { + DataSource dataSource = dataSourceFactory.createDataSource(); + DataSpec spec = new DataSpec.Builder().setUri(uri).setPosition(byteOffset).setLength(length).build(); +- dataSource.open(spec); +- int total = 0; + try { ++ dataSource.open(spec); ++ int total = 0; + while (total < length) { + int n = dataSource.read(buf, offset + total, length - total); + if (n == C.RESULT_END_OF_INPUT) { +@@ -159,10 +169,10 @@ public final class IsoDataReader implements CacheDataReader, Closeable { + } + total += n; + } ++ return total == 0 ? C.RESULT_END_OF_INPUT : total; + } finally { + dataSource.close(); + } +- return total == 0 ? -1 : total; + } + + @Override +diff --git a/libraries/datasource/src/test/java/androidx/media3/datasource/IsoDataReaderTest.java b/libraries/datasource/src/test/java/androidx/media3/datasource/IsoDataReaderTest.java +new file mode 100644 +index 0000000000..a2b8a11fe1 +--- /dev/null ++++ b/libraries/datasource/src/test/java/androidx/media3/datasource/IsoDataReaderTest.java +@@ -0,0 +1,137 @@ ++/* ++ * Copyright (C) 2026 The Android Open Source Project ++ * ++ * Licensed under the Apache License, Version 2.0 (the "License"); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an "AS IS" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package androidx.media3.datasource; ++ ++import static com.google.common.truth.Truth.assertThat; ++import static org.junit.Assert.assertThrows; ++ ++import android.net.Uri; ++import androidx.media3.common.C; ++import androidx.test.ext.junit.runners.AndroidJUnit4; ++import java.io.IOException; ++import java.util.Arrays; ++import java.util.concurrent.atomic.AtomicInteger; ++import org.junit.Test; ++import org.junit.runner.RunWith; ++ ++/** Unit tests for {@link IsoDataReader}. */ ++@RunWith(AndroidJUnit4.class) ++public final class IsoDataReaderTest { ++ ++ private static final int SECTOR_SIZE = 2048; ++ private static final Uri URI = Uri.parse("test://iso"); ++ ++ @Test ++ public void read_zeroLength_returnsZeroWithoutCreatingDataSource() throws Exception { ++ AtomicInteger createCount = new AtomicInteger(); ++ IsoDataReader reader = ++ new IsoDataReader( ++ () -> { ++ createCount.incrementAndGet(); ++ return new ByteArrayDataSource(new byte[SECTOR_SIZE]); ++ }, ++ URI); ++ ++ assertThat(reader.read(0, new byte[0], 0, 0)).isEqualTo(0); ++ assertThat(createCount.get()).isEqualTo(0); ++ } ++ ++ @Test ++ public void prefetchRange_invalidOrTooLarge_doesNotCreateDataSource() { ++ AtomicInteger createCount = new AtomicInteger(); ++ IsoDataReader reader = ++ new IsoDataReader( ++ () -> { ++ createCount.incrementAndGet(); ++ return new ByteArrayDataSource(new byte[SECTOR_SIZE]); ++ }, ++ URI); ++ ++ reader.prefetchRange(-1, SECTOR_SIZE); ++ reader.prefetchRange(SECTOR_SIZE, SECTOR_SIZE); ++ reader.prefetchRange(SECTOR_SIZE * 2L, SECTOR_SIZE); ++ reader.prefetchRange(0, (8192L + 1) * SECTOR_SIZE); ++ ++ assertThat(createCount.get()).isEqualTo(0); ++ } ++ ++ @Test ++ public void read_normalRangeAcrossSectorBoundary_returnsExpectedBytes() throws Exception { ++ byte[] input = new byte[SECTOR_SIZE * 2]; ++ for (int i = 0; i < input.length; i++) { ++ input[i] = (byte) i; ++ } ++ IsoDataReader reader = new IsoDataReader(() -> new ByteArrayDataSource(input), URI); ++ byte[] output = new byte[16]; ++ ++ assertThat(reader.read(SECTOR_SIZE - 8, output, 0, output.length)).isEqualTo(output.length); ++ assertThat(output) ++ .isEqualTo(Arrays.copyOfRange(input, SECTOR_SIZE - 8, SECTOR_SIZE + 8)); ++ } ++ ++ @Test ++ public void read_openThrows_closesDataSource() { ++ TrackingDataSource dataSource = new TrackingDataSource(/* failOnOpen= */ true); ++ IsoDataReader reader = new IsoDataReader(() -> dataSource, URI); ++ ++ assertThrows(IOException.class, () -> reader.read(0, new byte[1], 0, 1)); ++ assertThat(dataSource.closed).isTrue(); ++ } ++ ++ @Test ++ public void read_endOfInput_closesDataSource() { ++ TrackingDataSource dataSource = new TrackingDataSource(/* failOnOpen= */ false); ++ IsoDataReader reader = new IsoDataReader(() -> dataSource, URI); ++ ++ assertThrows(IOException.class, () -> reader.read(0, new byte[1], 0, 1)); ++ assertThat(dataSource.closed).isTrue(); ++ } ++ ++ private static final class TrackingDataSource implements DataSource { ++ private final boolean failOnOpen; ++ private boolean closed; ++ ++ private TrackingDataSource(boolean failOnOpen) { ++ this.failOnOpen = failOnOpen; ++ } ++ ++ @Override ++ public void addTransferListener(TransferListener transferListener) {} ++ ++ @Override ++ public long open(DataSpec dataSpec) throws IOException { ++ if (failOnOpen) { ++ throw new IOException("open failed"); ++ } ++ return C.LENGTH_UNSET; ++ } ++ ++ @Override ++ public int read(byte[] buffer, int offset, int length) { ++ return C.RESULT_END_OF_INPUT; ++ } ++ ++ @Override ++ public Uri getUri() { ++ return URI; ++ } ++ ++ @Override ++ public void close() { ++ closed = true; ++ } ++ } ++} diff --git a/third_party/patches/media3-exo-subtitle-byte-safety.patch b/third_party/patches/media3-exo-subtitle-byte-safety.patch new file mode 100644 index 0000000000..23491c78cf --- /dev/null +++ b/third_party/patches/media3-exo-subtitle-byte-safety.patch @@ -0,0 +1,504 @@ +diff --git a/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/source/DefaultMediaSourceFactory.java b/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/source/DefaultMediaSourceFactory.java +index d89917d626..eb45499859 100644 +--- a/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/source/DefaultMediaSourceFactory.java ++++ b/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/source/DefaultMediaSourceFactory.java +@@ -627,7 +627,9 @@ public final class DefaultMediaSourceFactory implements MediaSourceFactory { + new Extractor[] { + subtitleParserFactory.supportsFormat(format) + ? new SubtitleExtractor( +- subtitleParserFactory.create(format), /* format= */ null) ++ subtitleParserFactory.create(format), ++ /* format= */ null, ++ format.sampleMimeType) + : new UnknownSubtitlesExtractor(format) + }; + ProgressiveMediaSource.Factory progressiveMediaSourceFactory = +diff --git a/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/text/DelegatingSubtitleDecoder.java b/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/text/DelegatingSubtitleDecoder.java +index b3590bd13f..d808629e28 100644 +--- a/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/text/DelegatingSubtitleDecoder.java ++++ b/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/text/DelegatingSubtitleDecoder.java +@@ -15,11 +15,13 @@ + */ + package androidx.media3.exoplayer.text; + ++import androidx.annotation.Nullable; + import androidx.media3.extractor.text.SimpleSubtitleDecoder; + import androidx.media3.extractor.text.Subtitle; + import androidx.media3.extractor.text.SubtitleParser; + import com.google.common.base.Charsets; + import java.nio.charset.Charset; ++import java.util.regex.Pattern; + import org.mozilla.universalchardet.UniversalDetector; + + /** +@@ -48,19 +50,28 @@ import org.mozilla.universalchardet.UniversalDetector; + // deprecated and later deleted. + /* package */ final class DelegatingSubtitleDecoder extends SimpleSubtitleDecoder { + ++ private static final Pattern XML_ENCODING_ATTRIBUTE = ++ Pattern.compile("(?i)^\uFEFF?(\\s*<\\?xml\\b[^>]*\\bencoding\\s*=\\s*)([\"'])[^\"']*([\"'])"); ++ + private final SubtitleParser subtitleParser; +- private final UniversalDetector detector; +- private final boolean binaryFormat; ++ @Nullable private final UniversalDetector detector; ++ private final boolean inputIsTtml; + + public DelegatingSubtitleDecoder(String name, SubtitleParser subtitleParser) { +- this(name, subtitleParser, false); ++ this(name, subtitleParser, /* detectCharset= */ false, /* inputIsTtml= */ false); ++ } ++ ++ public DelegatingSubtitleDecoder( ++ String name, SubtitleParser subtitleParser, boolean detectCharset) { ++ this(name, subtitleParser, detectCharset, /* inputIsTtml= */ false); + } + +- public DelegatingSubtitleDecoder(String name, SubtitleParser subtitleParser, boolean binaryFormat) { ++ public DelegatingSubtitleDecoder( ++ String name, SubtitleParser subtitleParser, boolean detectCharset, boolean inputIsTtml) { + super(name); +- this.binaryFormat = binaryFormat; + this.subtitleParser = subtitleParser; +- this.detector = new UniversalDetector(null); ++ detector = detectCharset ? new UniversalDetector(null) : null; ++ this.inputIsTtml = inputIsTtml; + } + + @Override +@@ -68,24 +79,44 @@ import org.mozilla.universalchardet.UniversalDetector; + if (reset) { + subtitleParser.reset(); + } +- if (binaryFormat || data.length != length) { ++ if (detector == null) { + return subtitleParser.parseToLegacySubtitle(data, /* offset= */ 0, length); +- } else { +- data = convertToUtf8(data); +- return subtitleParser.parseToLegacySubtitle(data, /* offset= */ 0, data.length); + } ++ byte[] convertedData = maybeConvertToUtf8(data, length); ++ int convertedLength = convertedData == data ? length : convertedData.length; ++ return subtitleParser.parseToLegacySubtitle(convertedData, /* offset= */ 0, convertedLength); + } + +- private byte[] convertToUtf8(byte[] data) { ++ private byte[] maybeConvertToUtf8(byte[] data, int length) { ++ UniversalDetector detector = this.detector; ++ if (detector == null) { ++ return data; ++ } + detector.reset(); +- detector.handleData(data, 0, data.length); ++ detector.handleData(data, 0, length); + detector.dataEnd(); +- if (detector.getDetectedCharset() == null) { ++ @Nullable String detectedCharsetName = detector.getDetectedCharset(); ++ if (detectedCharsetName == null ++ || detectedCharsetName.regionMatches(/* ignoreCase= */ true, 0, "UTF", 0, 3)) { + return data; + } +- if (!detector.getDetectedCharset().startsWith("UTF")) { +- data = new String(data, Charset.forName(detector.getDetectedCharset())).getBytes(Charsets.UTF_8); ++ @Nullable Charset detectedCharset = forNameOrNull(detectedCharsetName); ++ if (detectedCharset == null) { ++ return data; ++ } ++ String utf8Text = new String(data, /* offset= */ 0, length, detectedCharset); ++ if (inputIsTtml) { ++ utf8Text = XML_ENCODING_ATTRIBUTE.matcher(utf8Text).replaceFirst("$1$2UTF-8$3"); ++ } ++ return utf8Text.getBytes(Charsets.UTF_8); ++ } ++ ++ @Nullable ++ private static Charset forNameOrNull(String charsetName) { ++ try { ++ return Charset.forName(charsetName); ++ } catch (IllegalArgumentException e) { ++ return null; + } +- return data; + } + } +diff --git a/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/text/SubtitleDecoderFactory.java b/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/text/SubtitleDecoderFactory.java +index a7b03ad627..f4f02a6ca4 100644 +--- a/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/text/SubtitleDecoderFactory.java ++++ b/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/text/SubtitleDecoderFactory.java +@@ -91,12 +91,21 @@ public interface SubtitleDecoderFactory { + } + if (delegate.supportsFormat(format)) { + SubtitleParser subtitleParser = delegate.create(format); +- boolean binaryFormat = MimeTypes.APPLICATION_DVBSUBS.equals(mimeType) || MimeTypes.APPLICATION_PGS.equals(mimeType) || MimeTypes.APPLICATION_VOBSUB.equals(mimeType); + return new DelegatingSubtitleDecoder( +- subtitleParser.getClass().getSimpleName() + "Decoder", subtitleParser, binaryFormat); ++ subtitleParser.getClass().getSimpleName() + "Decoder", ++ subtitleParser, ++ shouldDetectCharset(mimeType), ++ Objects.equals(mimeType, MimeTypes.APPLICATION_TTML)); + } + throw new IllegalArgumentException( + "Attempted to create decoder for unsupported MIME type: " + mimeType); + } ++ ++ private boolean shouldDetectCharset(@Nullable String mimeType) { ++ return Objects.equals(mimeType, MimeTypes.TEXT_SSA) ++ || Objects.equals(mimeType, MimeTypes.TEXT_VTT) ++ || Objects.equals(mimeType, MimeTypes.APPLICATION_SUBRIP) ++ || Objects.equals(mimeType, MimeTypes.APPLICATION_TTML); ++ } + }; + } +diff --git a/libraries/exoplayer/src/test/java/androidx/media3/exoplayer/text/DelegatingSubtitleDecoderCharsetTest.java b/libraries/exoplayer/src/test/java/androidx/media3/exoplayer/text/DelegatingSubtitleDecoderCharsetTest.java +new file mode 100644 +index 0000000000..f43c2e1b21 +--- /dev/null ++++ b/libraries/exoplayer/src/test/java/androidx/media3/exoplayer/text/DelegatingSubtitleDecoderCharsetTest.java +@@ -0,0 +1,107 @@ ++/* ++ * Copyright 2026 The Android Open Source Project ++ * ++ * Licensed under the Apache License, Version 2.0 (the "License"); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * https://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an "AS IS" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package androidx.media3.exoplayer.text; ++ ++import static com.google.common.truth.Truth.assertThat; ++ ++import androidx.media3.common.Format; ++import androidx.media3.common.util.Consumer; ++import androidx.media3.extractor.text.CuesWithTiming; ++import androidx.media3.extractor.text.SubtitleParser; ++import androidx.test.ext.junit.runners.AndroidJUnit4; ++import java.nio.charset.Charset; ++import java.nio.charset.StandardCharsets; ++import java.util.Arrays; ++import java.util.concurrent.atomic.AtomicReference; ++import org.junit.Test; ++import org.junit.runner.RunWith; ++ ++/** Tests charset conversion boundaries in {@link DelegatingSubtitleDecoder}. */ ++@RunWith(AndroidJUnit4.class) ++public final class DelegatingSubtitleDecoderCharsetTest { ++ ++ @Test ++ public void decode_nonUtfTextWithUnusedBufferTail_convertsOnlyValidBytes() { ++ String subtitleText = ++ "1\n00:00:00,000 --> 00:00:01,000\n" ++ + "这是用于检测字幕字符集的中文文本,这是用于检测字幕字符集的中文文本。\n"; ++ byte[] validBytes = subtitleText.getBytes(Charset.forName("GB18030")); ++ byte[] decoderBuffer = Arrays.copyOf(validBytes, validBytes.length + 64); ++ Arrays.fill(decoderBuffer, validBytes.length, decoderBuffer.length, (byte) 0x7F); ++ CapturingSubtitleParser parser = new CapturingSubtitleParser(); ++ DelegatingSubtitleDecoder decoder = ++ new DelegatingSubtitleDecoder("CharsetDecoder", parser, /* detectCharset= */ true); ++ ++ decoder.decode(decoderBuffer, validBytes.length, /* reset= */ false); ++ ++ assertThat(new String(parser.data.get(), StandardCharsets.UTF_8)).isEqualTo(subtitleText); ++ } ++ ++ @Test ++ public void decode_nonUtfTtml_updatesXmlEncodingDeclaration() { ++ String ttml = ++ "" ++ + "

" ++ + "这是用于检测字幕字符集的中文文本,这是用于检测字幕字符集的中文文本。" ++ + "

"; ++ byte[] bytes = ttml.getBytes(Charset.forName("GB18030")); ++ CapturingSubtitleParser parser = new CapturingSubtitleParser(); ++ DelegatingSubtitleDecoder decoder = ++ new DelegatingSubtitleDecoder( ++ "TtmlCharsetDecoder", ++ parser, ++ /* detectCharset= */ true, ++ /* inputIsTtml= */ true); ++ ++ decoder.decode(bytes, bytes.length, /* reset= */ false); ++ ++ String converted = new String(parser.data.get(), StandardCharsets.UTF_8); ++ assertThat(converted).contains("encoding='UTF-8'"); ++ assertThat(converted).contains("这是用于检测字幕字符集的中文文本"); ++ } ++ ++ @Test ++ public void decode_detectionDisabled_preservesBinaryBytesAndValidLength() { ++ byte[] validBytes = new byte[] {0, 3, (byte) 0xFF, 1, 2}; ++ byte[] decoderBuffer = Arrays.copyOf(validBytes, validBytes.length + 8); ++ CapturingSubtitleParser parser = new CapturingSubtitleParser(); ++ DelegatingSubtitleDecoder decoder = ++ new DelegatingSubtitleDecoder("BinaryDecoder", parser, /* detectCharset= */ false); ++ ++ decoder.decode(decoderBuffer, validBytes.length, /* reset= */ false); ++ ++ assertThat(parser.data.get()).isEqualTo(validBytes); ++ } ++ ++ private static final class CapturingSubtitleParser implements SubtitleParser { ++ private final AtomicReference data = new AtomicReference<>(); ++ ++ @Override ++ public void parse( ++ byte[] data, ++ int offset, ++ int length, ++ OutputOptions outputOptions, ++ Consumer output) { ++ this.data.set(Arrays.copyOfRange(data, offset, offset + length)); ++ } ++ ++ @Override ++ public @Format.CueReplacementBehavior int getCueReplacementBehavior() { ++ return Format.CUE_REPLACEMENT_BEHAVIOR_MERGE; ++ } ++ } ++} +diff --git a/libraries/extractor/src/main/java/androidx/media3/extractor/text/SubtitleExtractor.java b/libraries/extractor/src/main/java/androidx/media3/extractor/text/SubtitleExtractor.java +index 92b09d4f14..7d3b4b5e57 100644 +--- a/libraries/extractor/src/main/java/androidx/media3/extractor/text/SubtitleExtractor.java ++++ b/libraries/extractor/src/main/java/androidx/media3/extractor/text/SubtitleExtractor.java +@@ -47,6 +47,7 @@ import java.util.Arrays; + import java.util.Collections; + import java.util.List; + import java.util.concurrent.atomic.AtomicLong; ++import java.util.regex.Pattern; + import org.checkerframework.checker.nullness.qual.MonotonicNonNull; + import org.mozilla.universalchardet.UniversalDetector; + +@@ -89,13 +90,16 @@ public class SubtitleExtractor implements Extractor { + private static final int STATE_RELEASED = 5; + + private static final int DEFAULT_BUFFER_SIZE = 1024; ++ private static final Pattern XML_ENCODING_ATTRIBUTE = ++ Pattern.compile("(?i)^\uFEFF?(\\s*<\\?xml\\b[^>]*\\bencoding\\s*=\\s*)([\"'])[^\"']*([\"'])"); + + private final SubtitleParser subtitleParser; + private final CueEncoder cueEncoder; + @Nullable private final Format format; + private final List samples; + private final ParsableByteArray scratchSampleArray; +- private final UniversalDetector detector; ++ @Nullable private final UniversalDetector detector; ++ private final boolean inputIsTtml; + + private byte[] subtitleData; + private @MonotonicNonNull TrackOutput trackOutput; +@@ -116,13 +120,35 @@ public class SubtitleExtractor implements Extractor { + * ExtractorOutput#endTracks()} will be called outside this extractor. + */ + public SubtitleExtractor(SubtitleParser subtitleParser, @Nullable Format format) { ++ this( ++ subtitleParser, ++ format, ++ format != null ? format.sampleMimeType : /* inputSampleMimeType= */ null); ++ } ++ ++ /** ++ * Creates an instance. ++ * ++ * @param subtitleParser The parser used for parsing the subtitle data. The extractor will reset ++ * the parser in {@link SubtitleExtractor#release()}. ++ * @param format {@link Format} that describes subtitle data. Can be null if {@link ++ * TrackOutput#format}, {@link ExtractorOutput#seekMap} and {@link ++ * ExtractorOutput#endTracks()} will be called outside this extractor. ++ * @param inputSampleMimeType The MIME type of the input subtitle bytes. This can be set when ++ * {@code format} is null and is used only to decide whether charset detection is safe. ++ */ ++ public SubtitleExtractor( ++ SubtitleParser subtitleParser, ++ @Nullable Format format, ++ @Nullable String inputSampleMimeType) { + this.subtitleParser = subtitleParser; + cueEncoder = new CueEncoder(); + subtitleData = Util.EMPTY_BYTE_ARRAY; + scratchSampleArray = new ParsableByteArray(); + // TODO: b/376693592 - Simplify this by taking the post-transformation Format as a parameter + // instead. +- detector = new UniversalDetector(null); ++ detector = shouldDetectCharset(inputSampleMimeType) ? new UniversalDetector(null) : null; ++ inputIsTtml = MimeTypes.APPLICATION_TTML.equals(inputSampleMimeType); + this.format = + format != null + ? format +@@ -181,7 +207,7 @@ public class SubtitleExtractor implements Extractor { + if (state == STATE_EXTRACTING) { + boolean inputFinished = readFromInput(input); + if (inputFinished) { +- convertToUtf8(); ++ maybeConvertToUtf8(); + parseAndWriteToOutput(); + state = STATE_FINISHED; + } +@@ -324,22 +350,47 @@ public class SubtitleExtractor implements Extractor { + /* cryptoData= */ null); + } + +- private void convertToUtf8() { +- if (subtitleData.length != bytesRead) { ++ private void maybeConvertToUtf8() { ++ @Nullable UniversalDetector detector = this.detector; ++ if (detector == null) { + return; + } + detector.reset(); + detector.handleData(subtitleData, 0, bytesRead); + detector.dataEnd(); +- if (detector.getDetectedCharset() == null) { ++ @Nullable String detectedCharsetName = detector.getDetectedCharset(); ++ if (detectedCharsetName == null ++ || detectedCharsetName.regionMatches(/* ignoreCase= */ true, 0, "UTF", 0, 3)) { ++ return; ++ } ++ @Nullable Charset detectedCharset = forNameOrNull(detectedCharsetName); ++ if (detectedCharset == null) { + return; + } +- if (!detector.getDetectedCharset().startsWith("UTF")) { +- subtitleData = new String(subtitleData, Charset.forName(detector.getDetectedCharset())).getBytes(Charsets.UTF_8); ++ String utf8Text = new String(subtitleData, /* offset= */ 0, bytesRead, detectedCharset); ++ if (inputIsTtml) { ++ utf8Text = XML_ENCODING_ATTRIBUTE.matcher(utf8Text).replaceFirst("$1$2UTF-8$3"); + } ++ subtitleData = utf8Text.getBytes(Charsets.UTF_8); + bytesRead = subtitleData.length; + } + ++ private static boolean shouldDetectCharset(@Nullable String mimeType) { ++ return MimeTypes.TEXT_SSA.equals(mimeType) ++ || MimeTypes.TEXT_VTT.equals(mimeType) ++ || MimeTypes.APPLICATION_SUBRIP.equals(mimeType) ++ || MimeTypes.APPLICATION_TTML.equals(mimeType); ++ } ++ ++ @Nullable ++ private static Charset forNameOrNull(String charsetName) { ++ try { ++ return Charset.forName(charsetName); ++ } catch (IllegalArgumentException e) { ++ return null; ++ } ++ } ++ + private static class Sample implements Comparable { + private final long timeUs; + private final byte[] data; +diff --git a/libraries/extractor/src/test/java/androidx/media3/extractor/text/SubtitleExtractorTest.java b/libraries/extractor/src/test/java/androidx/media3/extractor/text/SubtitleExtractorTest.java +index e1539db4b7..6d44769b22 100644 +--- a/libraries/extractor/src/test/java/androidx/media3/extractor/text/SubtitleExtractorTest.java ++++ b/libraries/extractor/src/test/java/androidx/media3/extractor/text/SubtitleExtractorTest.java +@@ -30,7 +30,11 @@ import androidx.media3.test.utils.FakeExtractorOutput; + import androidx.media3.test.utils.FakeTrackOutput; + import androidx.test.ext.junit.runners.AndroidJUnit4; + import com.google.common.primitives.Ints; ++import java.nio.charset.Charset; ++import java.nio.charset.StandardCharsets; ++import java.util.Arrays; + import java.util.concurrent.atomic.AtomicInteger; ++import java.util.concurrent.atomic.AtomicReference; + import org.junit.Before; + import org.junit.Test; + import org.junit.runner.RunWith; +@@ -239,6 +243,70 @@ public class SubtitleExtractorTest { + assertThat(lengthFromParse.get()).isEqualTo(inputData.length); + } + ++ @Test ++ public void extractor_unknownLengthNonUtfInput_convertsOnlyBytesRead() throws Exception { ++ String subtitleText = ++ "WEBVTT\n\n00:00.000 --> 00:01.000\n" ++ + "这是用于检测字幕字符集的中文文本,这是用于检测字幕字符集的中文文本。\n"; ++ byte[] inputData = subtitleText.getBytes(Charset.forName("GB18030")); ++ FakeExtractorInput input = ++ new FakeExtractorInput.Builder() ++ .setData(inputData) ++ .setSimulatePartialReads(true) ++ .setSimulateUnknownLength(true) ++ .build(); ++ AtomicReference dataFromParse = new AtomicReference<>(); ++ SubtitleExtractor extractor = ++ new SubtitleExtractor( ++ capturingParser(dataFromParse), ++ new Format.Builder().setSampleMimeType(MimeTypes.TEXT_VTT).build()); ++ extractor.init(new FakeExtractorOutput()); ++ ++ while (extractor.read(input, null) != Extractor.RESULT_END_OF_INPUT) {} ++ ++ assertThat(new String(dataFromParse.get(), StandardCharsets.UTF_8)).isEqualTo(subtitleText); ++ } ++ ++ @Test ++ public void extractor_nonUtfTtml_updatesXmlEncodingDeclaration() throws Exception { ++ String ttml = ++ "" ++ + "

" ++ + "这是用于检测字幕字符集的中文文本,这是用于检测字幕字符集的中文文本。" ++ + "

"; ++ byte[] inputData = ttml.getBytes(Charset.forName("GB18030")); ++ FakeExtractorInput input = ++ new FakeExtractorInput.Builder().setData(inputData).setSimulatePartialReads(true).build(); ++ AtomicReference dataFromParse = new AtomicReference<>(); ++ SubtitleExtractor extractor = ++ new SubtitleExtractor( ++ capturingParser(dataFromParse), ++ new Format.Builder().setSampleMimeType(MimeTypes.APPLICATION_TTML).build()); ++ extractor.init(new FakeExtractorOutput()); ++ ++ while (extractor.read(input, null) != Extractor.RESULT_END_OF_INPUT) {} ++ ++ String converted = new String(dataFromParse.get(), StandardCharsets.UTF_8); ++ assertThat(converted).contains("encoding='UTF-8'"); ++ assertThat(converted).contains("这是用于检测字幕字符集的中文文本"); ++ } ++ ++ @Test ++ public void extractor_binaryMimeType_preservesInputBytes() throws Exception { ++ byte[] inputData = new byte[] {0, 3, (byte) 0xFF, 1, 2}; ++ AtomicReference dataFromParse = new AtomicReference<>(); ++ SubtitleExtractor extractor = ++ new SubtitleExtractor( ++ capturingParser(dataFromParse), ++ new Format.Builder().setSampleMimeType(MimeTypes.APPLICATION_TX3G).build()); ++ extractor.init(new FakeExtractorOutput()); ++ FakeExtractorInput input = new FakeExtractorInput.Builder().setData(inputData).build(); ++ ++ while (extractor.read(input, null) != Extractor.RESULT_END_OF_INPUT) {} ++ ++ assertThat(dataFromParse.get()).isEqualTo(inputData); ++ } ++ + @Test + public void read_withoutInit_fails() { + FakeExtractorInput input = new FakeExtractorInput.Builder().setData(new byte[0]).build(); +@@ -344,4 +412,23 @@ public class SubtitleExtractorTest { + return decoder.decode( + trackOutput.getSampleTimeUs(sampleIndex), sampleData, /* offset= */ 0, sampleData.length); + } ++ ++ private static SubtitleParser capturingParser(AtomicReference dataFromParse) { ++ return new SubtitleParser() { ++ @Override ++ public void parse( ++ byte[] data, ++ int offset, ++ int length, ++ OutputOptions outputOptions, ++ Consumer output) { ++ dataFromParse.set(Arrays.copyOfRange(data, offset, offset + length)); ++ } ++ ++ @Override ++ public @Format.CueReplacementBehavior int getCueReplacementBehavior() { ++ return Format.CUE_REPLACEMENT_BEHAVIOR_MERGE; ++ } ++ }; ++ } + } diff --git a/third_party/patches/media3-precache-hls-safety.patch b/third_party/patches/media3-precache-hls-safety.patch new file mode 100644 index 0000000000..e083e1d7a5 --- /dev/null +++ b/third_party/patches/media3-precache-hls-safety.patch @@ -0,0 +1,25 @@ +diff --git a/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/source/preload/PreCacheHelper.java b/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/source/preload/PreCacheHelper.java +--- a/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/source/preload/PreCacheHelper.java ++++ b/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/source/preload/PreCacheHelper.java +@@ -469,6 +469,19 @@ public final class PreCacheHelper { + checkState(helper == this.downloadHelper); + isPreparationOngoing = false; +- DownloadRequest downloadRequest = +- helper.getDownloadRequest(/* data= */ null, startPositionMs, durationMs); ++ DownloadRequest downloadRequest; ++ try { ++ downloadRequest = ++ helper.getDownloadRequest(/* data= */ null, startPositionMs, durationMs); ++ } catch (RuntimeException e) { ++ // HLS can report prepared tracks before its initial multivariant playlist is available. ++ // DownloadHelper.getDownloadRequest() must not let that asynchronous state race crash the ++ // application. Report the request-build failure through the existing prepare-error path. ++ downloadHelper.release(); ++ notifyListeners( ++ listener -> ++ listener.onPrepareError( ++ mediaItem, new IOException("Pre-cache download request unavailable", e))); ++ return; ++ } + downloadHelper.release(); + MediaItem updatedMediaItem = downloadRequest.toMediaItem(mediaItem.buildUpon()); diff --git a/third_party/patches/mpv-audiotrack-truehd-channel-mask.patch b/third_party/patches/mpv-audiotrack-truehd-channel-mask.patch index c26dade271..59f9521266 100644 --- a/third_party/patches/mpv-audiotrack-truehd-channel-mask.patch +++ b/third_party/patches/mpv-audiotrack-truehd-channel-mask.patch @@ -1,7 +1,39 @@ diff --git a/audio/out/ao_audiotrack.c b/audio/out/ao_audiotrack.c --- a/audio/out/ao_audiotrack.c +++ b/audio/out/ao_audiotrack.c -@@ -714,6 +714,15 @@ static int init(struct ao *ao) +@@ -34,3 +34,6 @@ + static int jni_static_use_count = 0; +- ++enum { ++ ANDROID_API_LEVEL_S = 31, ++}; ++ + struct priv { +@@ -234,3 +237,14 @@ static const struct MPJniField AudioFormatBuilder_mapping[] = { + #undef OFFSET +- ++static struct JNIBuildVersion { ++ jclass clazz; ++ jint SDK_INT; ++} BuildVersion; ++#define OFFSET(member) offsetof(struct JNIBuildVersion, member) ++static const struct MPJniField BuildVersion_mapping[] = { ++ {"android/os/Build$VERSION", NULL, MP_JNI_CLASS, OFFSET(clazz), 1}, ++ {"SDK_INT", "I", MP_JNI_STATIC_FIELD_AS_INT, OFFSET(SDK_INT), 1}, ++ {0} ++}; ++#undef OFFSET ++ + static struct JNIAudioManager { +@@ -274,6 +288,7 @@ static const struct { + ENTRY(AudioAttributesBuilder), + ENTRY(AudioFormat), + ENTRY(AudioFormatBuilder), ++ ENTRY(BuildVersion), + ENTRY(AudioManager), + ENTRY(AudioTimestamp), + }; +@@ -714,6 +729,19 @@ static int init(struct ao *ao) }; static_assert(MP_ARRAY_SIZE(layout_map) == MP_ARRAY_SIZE(layouts), ""); if (p->format == AudioFormat.ENCODING_IEC61937) { @@ -13,6 +45,10 @@ diff --git a/audio/out/ao_audiotrack.c b/audio/out/ao_audiotrack.c + if (ao->format == AF_FORMAT_S_TRUEHD) { + MP_VERBOSE(ao, "Using 7.1 IEC61937 carrier mask for TrueHD\n"); + p->channel_config = AudioFormat.CHANNEL_OUT_7POINT1_SURROUND; ++ } else if (BuildVersion.SDK_INT >= ANDROID_API_LEVEL_S && ++ ao->channels.num == 8) { ++ MP_VERBOSE(ao, "Using 7.1 IEC61937 carrier mask for Android 12+ 8-channel stream\n"); ++ p->channel_config = AudioFormat.CHANNEL_OUT_7POINT1_SURROUND; + } else { + p->channel_config = AudioFormat.CHANNEL_OUT_STEREO; + } diff --git a/third_party/patches/mpv-dovi-profile7-hdr10-base-layer.patch b/third_party/patches/mpv-dovi-profile7-hdr10-base-layer.patch index 9c6482bbb7..319f452416 100644 --- a/third_party/patches/mpv-dovi-profile7-hdr10-base-layer.patch +++ b/third_party/patches/mpv-dovi-profile7-hdr10-base-layer.patch @@ -41,6 +41,16 @@ diff --git a/demux/demux_lavf.c b/demux/demux_lavf.c index ac2ca71..fd9c065 100644 --- a/demux/demux_lavf.c +++ b/demux/demux_lavf.c +@@ -1454,8 +1454,7 @@ static void detect_dovi_split_streams(demuxer_t *demuxer) + for (int n = 0; n < snapshot_count; n++) { + struct stream_info *info = priv->streams[n]; + struct sh_stream *sh = info ? info->sh : NULL; +- if (!sh || sh->type != STREAM_VIDEO || !sh->codec || +- !sh->codec->dv_el_present || sh->group) ++ if (!sh || sh->type != STREAM_VIDEO || !sh->codec || sh->group) + { + continue; + } @@ -1867,6 +1867,12 @@ static bool demux_lavf_read_packet(struct demuxer *demux, // Dispatch the EL view of this packet via the splitter. @@ -58,6 +68,18 @@ diff --git a/demux/demux_mkv.c b/demux/demux_mkv.c index e47af33..2e0b1f1 100644 --- a/demux/demux_mkv.c +++ b/demux/demux_mkv.c +@@ -1831,9 +1831,8 @@ static int demux_mkv_open_video(demuxer_t *demuxer, mkv_track_t *track, int idx) + done: + demux_add_sh_stream(demuxer, sh); + +- // Profile 7 NALU-interleaved +- if (sh_v->dv_el_present) +- track->dovi_split = mp_dovi_split_create(demuxer, sh); ++ // Profile 7 NALU-interleaved or explicit base-only HDR10 output. ++ track->dovi_split = mp_dovi_split_create(demuxer, sh); + + return 0; + } @@ -2975,6 +2975,12 @@ static void mkv_parse_and_add_packet(demuxer_t *demuxer, mkv_track_t *track, struct demux_packet *el_dp = NULL; struct sh_stream *el_sh = NULL; @@ -75,6 +97,14 @@ diff --git a/demux/dovi_split.c b/demux/dovi_split.c index 77f4644..99c3099 100644 --- a/demux/dovi_split.c +++ b/demux/dovi_split.c +@@ -15,6 +15,7 @@ + * License along with mpv. If not, see . + */ + ++#include + #include + + #include @@ -39,6 +39,7 @@ struct mp_dovi_split { struct sh_stream *el; AVBSFContext *bsf; @@ -83,17 +113,57 @@ index 77f4644..99c3099 100644 }; static void mp_dovi_split_destructor(void *p) -@@ -67,6 +68,8 @@ struct mp_dovi_split *mp_dovi_split_create(struct demuxer *demuxer, +@@ -50,10 +51,15 @@ static void mp_dovi_split_destructor(void *p) + struct mp_dovi_split *mp_dovi_split_create(struct demuxer *demuxer, + struct sh_stream *bl) + { ++ bool base_only = bl && bl->codec && bl->codec->dv_profile == 7 && ++ demuxer->opts && demuxer->opts->dovi_profile7_mode == ++ DEMUX_DOVI_PROFILE7_HDR10; + if (!bl || bl->type != STREAM_VIDEO || !bl->codec || +- !bl->codec->codec || strcmp(bl->codec->codec, "hevc") != 0) ++ !bl->codec->codec || strcmp(bl->codec->codec, "hevc") != 0 || ++ (!bl->codec->dv_el_present && !base_only)) + return NULL; + + const AVBitStreamFilter *def = av_bsf_get_by_name("dovi_split"); +@@ -61,30 +67,63 @@ struct mp_dovi_split *mp_dovi_split_create(struct demuxer *demuxer, + if (!def) { +- MP_WARN(demuxer, "Dolby Vision EL: 'dovi_split' BSF not available in " +- "libavcodec; rendering base layer only.\n"); ++ MP_WARN(demuxer, "Dolby Vision: 'dovi_split' BSF not available in " ++ "libavcodec; leaving the bitstream unchanged.\n"); + return NULL; + } + + struct mp_dovi_split *s = talloc_zero(demuxer, struct mp_dovi_split); + talloc_set_destructor(s, mp_dovi_split_destructor); s->log = demuxer->log; s->demuxer = demuxer; s->bl = bl; -+ s->base_only = demuxer->opts && demuxer->opts->dovi_profile7_mode == -+ DEMUX_DOVI_PROFILE7_HDR10; ++ s->base_only = base_only; ++ int ret = AVERROR(ENOMEM); s->staging = av_packet_alloc(); if (!s->staging) -@@ -83,13 +86,20 @@ struct mp_dovi_split *mp_dovi_split_create(struct demuxer *demuxer, - } + goto fail; + +- int ret = av_bsf_alloc(def, &s->bsf); ++ ret = av_bsf_alloc(def, &s->bsf); + if (ret < 0) + goto fail; + + AVCodecParameters *par = mp_codec_params_to_av(bl->codec); +- if (par) { +- avcodec_parameters_copy(s->bsf->par_in, par); +- avcodec_parameters_free(&par); +- } ++ if (!par) ++ goto fail; ++ ret = avcodec_parameters_copy(s->bsf->par_in, par); ++ avcodec_parameters_free(&par); ++ if (ret < 0) ++ goto fail; s->bsf->time_base_in = mp_get_codec_timebase(bl->codec); - // The enhancement pairing filter inherits Dolby Vision metadata from the @@ -103,19 +173,49 @@ index 77f4644..99c3099 100644 + // in the access unit can starve regular vendor HEVC decoders and can let + // the output representation change later in the same playback session. + const char *mode = s->base_only ? "bl" : "el_rpu"; -+ if (av_opt_set(s->bsf, "mode", mode, AV_OPT_SEARCH_CHILDREN) < 0) ++ ret = av_opt_set(s->bsf, "mode", mode, AV_OPT_SEARCH_CHILDREN); ++ if (ret < 0) goto fail; - if (av_bsf_init(s->bsf) < 0) +- if (av_bsf_init(s->bsf) < 0) ++ ret = av_bsf_init(s->bsf); ++ if (ret < 0) goto fail; + if (s->base_only) { ++ if (bl->codec->lav_codecpar) { ++ AVCodecParameters *filtered = avcodec_parameters_alloc(); ++ if (!filtered) { ++ ret = AVERROR(ENOMEM); ++ goto fail; ++ } ++ ret = avcodec_parameters_copy(filtered, s->bsf->par_out); ++ if (ret < 0) { ++ avcodec_parameters_free(&filtered); ++ goto fail; ++ } ++ MPSWAP(AVCodecParameters, *bl->codec->lav_codecpar, *filtered); ++ avcodec_parameters_free(&filtered); ++ } ++ bl->codec->dv_el_present = false; + MP_INFO(demuxer, "DV7 HDR10 fallback: stripping EL/RPU before decoder.\n"); ++ MP_VERBOSE(demuxer, "DV7 HDR10 fallback: synchronized decoder " ++ "parameters to the HDR10 base layer.\n"); + return s; + } + const AVCodecParameters *par_out = s->bsf->par_out; // Allocate the virtual EL sh_stream. +@@ -135,6 +174,9 @@ struct mp_dovi_split *mp_dovi_split_create(struct demuxer *demuxer, + return s; + + fail: ++ MP_WARN(demuxer, "Dolby Vision: failed to initialize 'dovi_split': %s; " ++ "leaving the bitstream unchanged.\n", ++ mp_strerror(AVUNERROR(ret))); + talloc_free(s); + return NULL; + } @@ -151,55 +161,101 @@ struct sh_stream *mp_dovi_split_el_stream(struct mp_dovi_split *s) return s ? s->el : NULL; } @@ -137,6 +237,8 @@ index 77f4644..99c3099 100644 if (!s || !s->bsf || !bl_dp || !bl_dp->buffer || bl_dp->len <= 0) - return NULL; + return SPLIT_PACKET_ERROR; ++ if (bl_dp->len > INT_MAX) ++ return SPLIT_PACKET_ERROR; - // av_bsf_send_packet takes ownership of the packet's buffer, so copy it, - // to not steal it from caller. @@ -153,7 +255,7 @@ index 77f4644..99c3099 100644 + && bl_dp->avpacket->size == bl_dp->len) { + ret = av_packet_ref(copy, bl_dp->avpacket); + } else { -+ ret = av_new_packet(copy, bl_dp->len); ++ ret = av_new_packet(copy, (int)bl_dp->len); + if (ret >= 0) memcpy(copy->data, bl_dp->buffer, bl_dp->len); + if (ret >= 0 && bl_dp->avpacket) + ret = av_packet_copy_props(copy, bl_dp->avpacket); diff --git a/third_party/patches/mpv-dovi-profile7-p81.patch b/third_party/patches/mpv-dovi-profile7-p81.patch new file mode 100644 index 0000000000..425d8e13cf --- /dev/null +++ b/third_party/patches/mpv-dovi-profile7-p81.patch @@ -0,0 +1,232 @@ +diff --git a/demux/demux.c b/demux/demux.c +index 492be0d..c45ef8a 100644 +--- a/demux/demux.c ++++ b/demux/demux.c +@@ -135,7 +135,8 @@ const struct m_sub_options demux_conf = { + {"no", 0}, {"filter", 1}, {"same", 2})}, + {"demuxer-dovi-profile7", OPT_CHOICE(dovi_profile7_mode, + {"preserve", DEMUX_DOVI_PROFILE7_PRESERVE}, +- {"hdr10", DEMUX_DOVI_PROFILE7_HDR10})}, ++ {"hdr10", DEMUX_DOVI_PROFILE7_HDR10}, ++ {"p81", DEMUX_DOVI_PROFILE7_P81})}, + {0} + }, + .size = sizeof(struct demux_opts), +diff --git a/demux/demux.h b/demux/demux.h +index f6a261b..c3c0c36 100644 +--- a/demux/demux.h ++++ b/demux/demux.h +@@ -95,6 +95,7 @@ struct demux_opts { + enum demux_dovi_profile7_mode { + DEMUX_DOVI_PROFILE7_PRESERVE = 0, + DEMUX_DOVI_PROFILE7_HDR10 = 1, ++ DEMUX_DOVI_PROFILE7_P81 = 2, + }; + + #define SEEK_FACTOR (1 << 1) // argument is in range [0,1] +diff --git a/demux/dovi_split.c b/demux/dovi_split.c +index 53d0c8f..bc0bfb1 100644 +--- a/demux/dovi_split.c ++++ b/demux/dovi_split.c +@@ -41,6 +41,7 @@ struct mp_dovi_split { + AVBSFContext *bsf; + AVPacket *staging; + bool base_only; ++ bool convert_p81; + }; + + static void mp_dovi_split_destructor(void *p) +@@ -53,18 +54,41 @@ static void mp_dovi_split_destructor(void *p) + struct mp_dovi_split *mp_dovi_split_create(struct demuxer *demuxer, + struct sh_stream *bl) + { ++ bool p81_requested = bl && bl->codec && bl->codec->dv_profile == 7 && ++ demuxer->opts && demuxer->opts->dovi_profile7_mode == ++ DEMUX_DOVI_PROFILE7_P81; + bool base_only = bl && bl->codec && bl->codec->dv_profile == 7 && + demuxer->opts && demuxer->opts->dovi_profile7_mode == + DEMUX_DOVI_PROFILE7_HDR10; ++ bool has_p81_config = false; ++ if (p81_requested && bl->codec->lav_codecpar) { ++ for (int i = 0; i < bl->codec->lav_codecpar->nb_coded_side_data; i++) { ++ AVPacketSideData *sd = &bl->codec->lav_codecpar->coded_side_data[i]; ++ if (sd->type != AV_PKT_DATA_DOVI_CONF || ++ sd->size < sizeof(AVDOVIDecoderConfigurationRecord)) ++ continue; ++ const AVDOVIDecoderConfigurationRecord *cfg = ++ (const void *)sd->data; ++ has_p81_config = cfg->dv_profile == 7 && ++ cfg->rpu_present_flag && cfg->bl_present_flag; ++ break; ++ } ++ if (!has_p81_config) { ++ base_only = true; ++ MP_WARN(demuxer, "DV7 P8.1 conversion requires a valid profile 7 " ++ "RPU/base-layer configuration; falling back to HDR10.\n"); ++ } ++ } ++ bool convert_p81 = p81_requested && has_p81_config; + if (!bl || bl->type != STREAM_VIDEO || !bl->codec || + !bl->codec->codec || strcmp(bl->codec->codec, "hevc") != 0 || +- (!bl->codec->dv_el_present && !base_only)) ++ (!bl->codec->dv_el_present && !base_only && !convert_p81)) + return NULL; + +- const AVBitStreamFilter *def = av_bsf_get_by_name("dovi_split"); ++ const char *filter_name = convert_p81 ? "dovi_rpu" : "dovi_split"; ++ const AVBitStreamFilter *def = av_bsf_get_by_name(filter_name); ++ if (!def && convert_p81) { ++ MP_WARN(demuxer, "Dolby Vision: 'dovi_rpu' BSF not available; " ++ "falling back to HDR10 base-layer filtering.\n"); ++ convert_p81 = false; ++ base_only = true; ++ filter_name = "dovi_split"; ++ def = av_bsf_get_by_name(filter_name); ++ } + if (!def) { +- MP_WARN(demuxer, "Dolby Vision: 'dovi_split' BSF not available in " +- "libavcodec; leaving the bitstream unchanged.\n"); ++ MP_WARN(demuxer, "Dolby Vision: '%s' BSF not available in " ++ "libavcodec; leaving the bitstream unchanged.\n", ++ filter_name); + return NULL; + } + +@@ -74,6 +98,7 @@ struct mp_dovi_split *mp_dovi_split_create(struct demuxer *demuxer, + s->demuxer = demuxer; + s->bl = bl; + s->base_only = base_only; ++ s->convert_p81 = convert_p81; + + int ret = AVERROR(ENOMEM); + s->staging = av_packet_alloc(); +@@ -93,18 +118,21 @@ struct mp_dovi_split *mp_dovi_split_create(struct demuxer *demuxer, + goto fail; + s->bsf->time_base_in = mp_get_codec_timebase(bl->codec); + +- // Feed HDR10 fallback paths a clean HEVC base layer. Leaving EL/RPU NALs +- // in the access unit can starve regular vendor HEVC decoders and can let +- // the output representation change later in the same playback session. +- const char *mode = s->base_only ? "bl" : "el_rpu"; +- ret = av_opt_set(s->bsf, "mode", mode, AV_OPT_SEARCH_CHILDREN); ++ // P8.1 conversion rewrites RPU metadata and removes EL NAL units. The ++ // existing dovi_split path remains unchanged for preserve/HDR10 modes. ++ if (convert_p81) ++ ret = av_opt_set(s->bsf, "convert", "p81", AV_OPT_SEARCH_CHILDREN); ++ else { ++ const char *mode = s->base_only ? "bl" : "el_rpu"; ++ ret = av_opt_set(s->bsf, "mode", mode, AV_OPT_SEARCH_CHILDREN); ++ } + if (ret < 0) + goto fail; + ret = av_bsf_init(s->bsf); + if (ret < 0) + goto fail; + ++ if (s->convert_p81) { ++ // hvcE describes the Profile 7 enhancement layer removed by dovi_rpu. ++ av_packet_side_data_remove(s->bsf->par_out->coded_side_data, ++ &s->bsf->par_out->nb_coded_side_data, ++ AV_PKT_DATA_HEVC_CONF); ++ MP_VERBOSE(demuxer, "DV7 P8.1 conversion: removed stale enhancement-layer configuration.\n"); ++ } ++ +- if (s->base_only) { ++ if (s->base_only || s->convert_p81) { + if (bl->codec->lav_codecpar) { + AVCodecParameters *filtered = avcodec_parameters_alloc(); + if (!filtered) { +@@ -120,9 +148,17 @@ struct mp_dovi_split *mp_dovi_split_create(struct demuxer *demuxer, + avcodec_parameters_free(&filtered); + } + bl->codec->dv_el_present = false; +- MP_INFO(demuxer, "DV7 HDR10 fallback: stripping EL/RPU before decoder.\n"); +- MP_VERBOSE(demuxer, "DV7 HDR10 fallback: synchronized decoder " +- "parameters to the HDR10 base layer.\n"); ++ if (s->convert_p81) { ++ bl->codec->dovi = true; ++ bl->codec->source_dv_profile = bl->codec->dv_profile; ++ bl->codec->source_dv_level = bl->codec->dv_level; ++ bl->codec->dv_profile = 8; ++ MP_INFO(demuxer, "DV7 P8.1 conversion: using FFmpeg dovi_rpu BSF.\n"); ++ MP_VERBOSE(demuxer, "DV7 P8.1 conversion: synchronized Profile 8.1 " ++ "decoder parameters.\n"); ++ } else { ++ MP_INFO(demuxer, "DV7 HDR10 fallback: stripping EL/RPU before decoder.\n"); ++ MP_VERBOSE(demuxer, "DV7 HDR10 fallback: synchronized decoder " ++ "parameters to the HDR10 base layer.\n"); ++ } + return s; + } + +@@ -171,9 +207,9 @@ struct mp_dovi_split *mp_dovi_split_create(struct demuxer *demuxer, + return s; + + fail: +- MP_WARN(demuxer, "Dolby Vision: failed to initialize 'dovi_split': %s; " ++ MP_WARN(demuxer, "Dolby Vision: failed to initialize '%s': %s; " + "leaving the bitstream unchanged.\n", +- mp_strerror(AVUNERROR(ret))); ++ filter_name, mp_strerror(AVUNERROR(ret))); + talloc_free(s); + return NULL; + } + +@@ -198,13 +234,20 @@ static int filter_packet(struct mp_dovi_split *s, + bool mp_dovi_split_filter_base(struct mp_dovi_split *s, + struct demux_packet **bl_dp) + { +- if (!s || !s->base_only) ++ if (!s || (!s->base_only && !s->convert_p81)) + return true; + if (!bl_dp || !*bl_dp) + return false; + + struct demux_packet *filtered = NULL; + int ret = filter_packet(s, *bl_dp, s->bl->index, &filtered); + if (ret == SPLIT_PACKET_ERROR) { +- MP_ERR(s->demuxer, "DV7 HDR10 fallback: failed to produce base-layer packet.\n"); ++ if (s->convert_p81) ++ MP_ERR(s->demuxer, "DV7 P8.1 conversion: failed to produce converted packet.\n"); ++ else ++ MP_ERR(s->demuxer, "DV7 HDR10 fallback: failed to produce base-layer packet.\n"); + return false; + } +diff --git a/demux/dovi_split.h b/demux/dovi_split.h +index 55ed81e..4a07eb6 100644 +--- a/demux/dovi_split.h ++++ b/demux/dovi_split.h +@@ -44,7 +44,8 @@ void mp_dovi_split_reset(struct mp_dovi_split *s); + // returned pointer remains valid for the lifetime of the splitter. + struct sh_stream *mp_dovi_split_el_stream(struct mp_dovi_split *s); + +-// Replace `*bl_dp` with a base-layer-only packet in HDR10 fallback mode. ++// Replace `*bl_dp` with a base-layer-only packet in HDR10 fallback mode or a ++// converted Profile 8.1 packet in explicit P8.1 mode. + // The pointer becomes NULL when an access unit contains no base-layer NAL. + // Returns false only for a filtering error; the caller owns the original + // packet in that case. +diff --git a/demux/stheader.h b/demux/stheader.h +--- a/demux/stheader.h ++++ b/demux/stheader.h +@@ -174,4 +174,6 @@ struct mp_codec_params { + bool dovi; + uint8_t dv_profile; + uint8_t dv_level; ++ uint8_t source_dv_profile; ++ uint8_t source_dv_level; + bool dv_el_present; // BL and EL interleaved in this stream (Profile 7) +diff --git a/player/command.c b/player/command.c +--- a/player/command.c ++++ b/player/command.c +@@ -2212,6 +2212,10 @@ static int get_track_entry(int item, int action, void *arg, void *ctx) + .unavailable = !p.dovi}, + {"dolby-vision-level", SUB_PROP_INT(p.dv_level), + .unavailable = !p.dovi}, ++ {"source-dolby-vision-profile", SUB_PROP_INT(p.source_dv_profile), ++ .unavailable = !p.source_dv_profile}, ++ {"source-dolby-vision-level", SUB_PROP_INT(p.source_dv_level), ++ .unavailable = !p.source_dv_profile}, + {"metadata", SUB_PROP_KEYVALUE_LIST(tag_list), + .unavailable = !tags->num_keys}, + {0} diff --git a/third_party/patches/mpv-mediacodec-output-timing-diagnostics.patch b/third_party/patches/mpv-mediacodec-output-timing-diagnostics.patch index 6da957dea8..86d0087520 100644 --- a/third_party/patches/mpv-mediacodec-output-timing-diagnostics.patch +++ b/third_party/patches/mpv-mediacodec-output-timing-diagnostics.patch @@ -50,3 +50,39 @@ index 679a7bd0..06f51b3c 100644 wakeup_core(vo); } else { in->rendering = true; +diff --git a/video/out/vo_mediacodec_embed.c b/video/out/vo_mediacodec_embed.c +--- a/video/out/vo_mediacodec_embed.c ++++ b/video/out/vo_mediacodec_embed.c +@@ -37,6 +37,8 @@ struct priv { + int64_t next_pts; + int64_t next_duration; + int64_t last_submit_start; ++ int64_t preinit_at; ++ bool first_output_logged; + int64_t timed_lead_total; + int64_t timed_lead_min; + int64_t timed_lead_max; +@@ -113,5 +115,7 @@ static int preinit(struct vo *vo) + { + struct priv *p = vo->priv; ++ p->preinit_at = mp_time_ns(); ++ p->first_output_logged = false; + if (vo->opts->android_osd_wid == 0 || + vo->opts->android_osd_wid == -1) + { +@@ -225,4 +229,15 @@ static bool schedule_image(struct vo *vo, struct mp_image *image, int64_t pts, + int64_t release_elapsed = MPMAX(mp_time_ns() - submit_start, 0); ++ if (result >= 0 && !p->first_output_logged) { ++ p->first_output_logged = true; ++ int64_t elapsed = MPMAX(mp_time_ns() - p->preinit_at, 0); ++ MP_WARN(vo, "MediaCodec first output submitted: elapsed=%lld us " ++ "media-pts=%.3f target-lead=%lld us mode=%s " ++ "release=%lld us.\n", ++ (long long)(elapsed / 1000), image->pts, ++ (long long)(lead / 1000), ++ timed ? "timed" : "immediate", ++ (long long)(release_elapsed / 1000)); ++ } + int64_t frame_budget = duration > 0 + ? duration : MP_TIME_US_TO_NS(16667); + if (frame_budget <= 0 || frame_budget > MP_TIME_S_TO_NS(10)) diff --git a/third_party/patches/mpv-p1-ebml-defaults.patch b/third_party/patches/mpv-p1-ebml-defaults.patch new file mode 100644 index 0000000000..8f4b01c973 --- /dev/null +++ b/third_party/patches/mpv-p1-ebml-defaults.patch @@ -0,0 +1,336 @@ +diff --git a/TOOLS/matroska.py b/TOOLS/matroska.py +index 7627edd7..5b91bca3 100755 +--- a/TOOLS/matroska.py ++++ b/TOOLS/matroska.py +@@ -28,13 +28,13 @@ from math import ldexp + + elements_ebml = ( + "EBML, 1a45dfa3, sub", ( +- "EBMLVersion, 4286, uint", +- "EBMLReadVersion, 42f7, uint", +- "EBMLMaxIDLength, 42f2, uint", +- "EBMLMaxSizeLength, 42f3, uint", ++ "EBMLVersion, 4286, uint, default=1", ++ "EBMLReadVersion, 42f7, uint, default=1", ++ "EBMLMaxIDLength, 42f2, uint, default=4", ++ "EBMLMaxSizeLength, 42f3, uint, default=8", + "DocType, 4282, str", +- "DocTypeVersion, 4287, uint", +- "DocTypeReadVersion, 4285, uint", ++ "DocTypeVersion, 4287, uint, default=1", ++ "DocTypeReadVersion, 4285, uint, default=1", + ), + + "CRC32, bf, binary", +@@ -52,10 +52,10 @@ elements_matroska = ( + ), + + "Info*, 1549a966, sub", ( +- "SegmentUID, 73a4, binary, 16", +- "PrevUID, 3cb923, binary, 16", +- "NextUID, 3eb923, binary, 16", +- "TimecodeScale, 2ad7b1, uint", ++ "SegmentUID, 73a4, binary, length=16", ++ "PrevUID, 3cb923, binary, length=16", ++ "NextUID, 3eb923, binary, length=16", ++ "TimecodeScale, 2ad7b1, uint, default=1000000", + "DateUTC, 4461, sint", + "Title, 7ba9, str", + "MuxingApp, 4d80, str", +@@ -72,7 +72,7 @@ elements_matroska = ( + "DiscardPadding, 75A2, sint", + "BlockAdditions, 75A1, sub", ( + "BlockMore*, A6, sub", ( +- "BlockAddID, EE, uint", ++ "BlockAddID, EE, uint, default=1", + "BlockAdditional, A5, binary", + ), + ), +@@ -85,44 +85,44 @@ elements_matroska = ( + "TrackNumber, d7, uint", + "TrackUID, 73c5, uint", + "TrackType, 83, uint", +- "FlagEnabled, b9, uint", +- "FlagDefault, 88, uint", ++ "FlagEnabled, b9, uint, default=1", ++ "FlagDefault, 88, uint, default=1", + "FlagForced, 55aa, uint", + "FlagHearingImpaired, 55ab, uint", + "FlagVisualImpaired, 55ac, uint", + "FlagOriginal, 55ae, uint", + "FlagCommentary, 55af, uint", +- "FlagLacing, 9c, uint", ++ "FlagLacing, 9c, uint, default=1", + "MinCache, 6de7, uint", + "MaxCache, 6df8, uint", + "DefaultDuration, 23e383, uint", +- "TrackTimecodeScale, 23314f, float", ++ "TrackTimecodeScale, 23314f, float, default=1", + "MaxBlockAdditionID, 55ee, uint", + "Name, 536e, str", +- "Language, 22b59c, str", ++ "Language, 22b59c, str, default=eng", + "LanguageBCP47, 22b59d, str", + "CodecID, 86, str", + "CodecPrivate, 63a2, binary", + "CodecName, 258688, str", +- "CodecDecodeAll, aa, uint", ++ "CodecDecodeAll, aa, uint, default=1", + "CodecDelay, 56aa, uint", + "SeekPreRoll, 56bb, uint", + "Video, e0, sub", ( + "FlagInterlaced, 9a, uint", + "PixelWidth, b0, uint", + "PixelHeight, ba, uint", +- "DisplayWidth, 54b0, uint", +- "DisplayHeight, 54ba, uint", ++ "DisplayWidth, 54b0, uint, default=context", ++ "DisplayHeight, 54ba, uint, default=context", + "DisplayUnit, 54b2, uint", + "PixelCropTop, 54bb, uint", + "PixelCropLeft, 54cc, uint", + "PixelCropRight, 54dd, uint", + "PixelCropBottom, 54aa, uint", + "FrameRate, 2383e3, float", +- "ColourSpace, 2eb524, binary, 4", ++ "ColourSpace, 2eb524, binary, length=4", + "StereoMode, 53b8, uint", + "Colour, 55b0, sub", ( +- "MatrixCoefficients, 55B1, uint", ++ "MatrixCoefficients, 55B1, uint, default=2", + "BitsPerChannel, 55B2, uint", + "ChromaSubsamplingHorz, 55B3, uint", + "ChromaSubsamplingVert, 55B4, uint", +@@ -131,8 +131,8 @@ elements_matroska = ( + "ChromaSitingHorz, 55B7, uint", + "ChromaSitingVert, 55B8, uint", + "Range, 55B9, uint", +- "TransferCharacteristics, 55BA, uint", +- "Primaries, 55BB, uint", ++ "TransferCharacteristics, 55BA, uint, default=2", ++ "Primaries, 55BB, uint, default=2", + "MaxCLL, 55BC, uint", + "MaxFALL, 55BD, uint", + "MasteringMetadata, 55D0, sub", ( +@@ -157,15 +157,15 @@ elements_matroska = ( + ), + ), + "Audio, e1, sub", ( +- "SamplingFrequency, b5, float", +- "OutputSamplingFrequency, 78b5, float", +- "Channels, 9f, uint", ++ "SamplingFrequency, b5, float, default=8000", ++ "OutputSamplingFrequency, 78b5, float, default=context", ++ "Channels, 9f, uint, default=1", + "BitDepth, 6264, uint", + ), + "ContentEncodings, 6d80, sub", ( + "ContentEncoding*, 6240, sub", ( + "ContentEncodingOrder, 5031, uint", +- "ContentEncodingScope, 5032, uint", ++ "ContentEncodingScope, 5032, uint, default=1", + "ContentEncodingType, 5033, uint", + "ContentCompression, 5034, sub", ( + "ContentCompAlgo, 4254, uint", +@@ -215,12 +215,12 @@ elements_matroska = ( + "ChapterTimeStart, 91, uint", + "ChapterTimeEnd, 92, uint", + "ChapterFlagHidden, 98, uint", +- "ChapterFlagEnabled, 4598, uint", +- "ChapterSegmentUID, 6e67, binary, 16", ++ "ChapterFlagEnabled, 4598, uint, default=1", ++ "ChapterSegmentUID, 6e67, binary, length=16", + "ChapterSegmentEditionUID, 6ebc, uint", + "ChapterDisplay*, 80, sub", ( + "ChapString, 85, str", +- "ChapLanguage*, 437c, str", ++ "ChapLanguage*, 437c, str, default=eng", + "ChapLanguageBCP47*, 437d, str", + "ChapCountry*, 437e, str", + ), +@@ -230,7 +230,7 @@ elements_matroska = ( + "Tags*, 1254c367, sub", ( + "Tag*, 7373, sub", ( + "Targets, 63c0, sub", ( +- "TargetTypeValue, 68ca, uint", ++ "TargetTypeValue, 68ca, uint, default=50", + "TargetType, 63ca, str", + "TargetTrackUID, 63c5, uint", + "TargetEditionUID, 63c9, uint", +@@ -239,10 +239,10 @@ elements_matroska = ( + ), + "SimpleTag*, 67c8, sub", ( + "TagName, 45a3, str", +- "TagLanguage, 447a, str", ++ "TagLanguage, 447a, str, default=und", + "TagLanguageBCP47, 447b, str", + "TagString, 4487, str", +- "TagDefault, 4484, uint", ++ "TagDefault, 4484, uint, default=1", + ), + ), + ), +@@ -266,7 +266,8 @@ def camelcase_to_words(name): + + class MatroskaElement: + +- def __init__(self, name, elid, valtype, namespace, length=None): ++ def __init__(self, name, elid, valtype, namespace, length=None, ++ default=None): + self.name = name + self.definename = f"{namespace}_ID_{name.upper()}" + self.fieldname = camelcase_to_words(name) +@@ -274,6 +275,7 @@ class MatroskaElement: + self.elid = elid + self.valtype = valtype + self.length = int(length or "0") ++ self.default = default + if valtype == "sub": + self.ebmltype = "EBML_TYPE_SUBELEMENTS" + self.valname = "struct " + self.structname +@@ -292,6 +294,21 @@ class MatroskaElement: + self.subelements = subelements + self.subids = {x[0].elid for x in subelements} + ++ def default_initializer(self): ++ if self.default is None: ++ return "false, {0}" ++ if self.default == "context": ++ return "true, {0}" ++ if self.valtype == "uint": ++ return f"false, {{.u = {int(self.default)}}}" ++ if self.valtype == "sint": ++ return f"false, {{.i = {int(self.default)}}}" ++ if self.valtype == "float": ++ return f"false, {{.f = {float(self.default)}}}" ++ if self.valtype == "str": ++ return f'false, {{.s = "{self.default}"}}' ++ raise SyntaxError("Default not supported for type " + self.valtype) ++ + elementd: dict[str, MatroskaElement] = {} + elementlist: list[MatroskaElement] = [] + def parse_elems(elements, namespace): +@@ -299,11 +316,16 @@ def parse_elems(elements, namespace): + for el in elements: + if isinstance(el, str): + name, hexid, eltype, *rest = (x.strip() for x in el.split(",")) +- length = rest[0] if rest else None ++ attrs = {} ++ for extra in rest: ++ key, sep, value = extra.partition("=") ++ if not sep or key not in ("length", "default"): ++ raise SyntaxError("Invalid element attribute " + extra) ++ attrs[key] = value + hexid = hexid.lower() + multiple = name.endswith("*") + name = name.strip("*") +- new = MatroskaElement(name, hexid, eltype, namespace, length) ++ new = MatroskaElement(name, hexid, eltype, namespace, **attrs) + elementd[hexid] = new + elementlist.append(new) + subelements.append((new, multiple)) +@@ -366,7 +388,7 @@ def generate_c_definitions(out): + printf(out, "#undef N") + else: + printf(out, f'E("{el.name}", {el.fieldname}, {el.ebmltype}, ' +- f'{el.length})') ++ f'{el.length}, {el.default_initializer()})') + + def read(s, length): + t = s.read(length) +diff --git a/demux/ebml.c b/demux/ebml.c +index f967550f..8b734175 100644 +--- a/demux/ebml.c ++++ b/demux/ebml.c +@@ -210,8 +210,11 @@ int ebml_resync_cluster(struct mp_log *log, stream_t *s) + + + ++static_assert(sizeof(((struct ebml_elem_desc *)0)->defval) == sizeof(((struct ebml_elem_desc *)0)->defval.u), ++ "defval.u must cover the entire union for {0} initialization"); ++ + #define EVALARGS(F, ...) F(__VA_ARGS__) +-#define E(str, N, type, length) const struct ebml_elem_desc ebml_ ## N ## _desc = { str, type, length }; ++#define E(str, N, type, length, context, ...) const struct ebml_elem_desc ebml_ ## N ## _desc = { str, type, length, .context_default = context, .defval = __VA_ARGS__ }; + #define E_SN(str, count, N) const struct ebml_elem_desc ebml_ ## N ## _desc = { str, EBML_TYPE_SUBELEMENTS, sizeof(struct ebml_ ## N), count, (const struct ebml_field_desc[]){ + #define E_S(str, count) EVALARGS(E_SN, str, count, N) + #define FN(id, name, multiple, N) { id, multiple, offsetof(struct ebml_ ## N, name), offsetof(struct ebml_ ## N, n_ ## name), &ebml_##name##_desc}, +@@ -510,11 +513,13 @@ static void ebml_parse_element(struct ebml_parse_ctx *ctx, void *target, + else \ + subelptr = (fieldtype *) fieldptr + GETPTR(uintptr, uint64_t); +- if (length < 1 || length > 8) { ++ if (length > 8) { + MP_ERR(ctx, "uint invalid length %"PRIu64"\n", length); + goto error; + } +- *uintptr = ebml_parse_uint(data, length); ++ if (!length && ed->context_default) ++ goto skip; ++ *uintptr = length ? ebml_parse_uint(data, length) : ed->defval.u; + MP_TRACE(ctx, "uint %"PRIu64"\n", *uintptr); + break; + +@@ -525,7 +530,9 @@ static void ebml_parse_element(struct ebml_parse_ctx *ctx, void *target, + MP_ERR(ctx, "sint invalid length %"PRIu64"\n", length); + goto error; + } +- *sintptr = ebml_parse_sint(data, length); ++ if (!length && ed->context_default) ++ goto skip; ++ *sintptr = length ? ebml_parse_sint(data, length) : ed->defval.i; + MP_TRACE(ctx, "sint %"PRId64"\n", *sintptr); + break; + +@@ -536,7 +543,9 @@ static void ebml_parse_element(struct ebml_parse_ctx *ctx, void *target, + MP_ERR(ctx, "float invalid length %"PRIu64"\n", length); + goto error; + } +- *floatptr = ebml_parse_float(data, length); ++ if (!length && ed->context_default) ++ goto skip; ++ *floatptr = length ? ebml_parse_float(data, length) : ed->defval.f; + MP_DBG(ctx, "float %f\n", *floatptr); + break; + +@@ -547,7 +556,13 @@ static void ebml_parse_element(struct ebml_parse_ctx *ctx, void *target, + } + char **strptr; + GETPTR(strptr, char *); +- *strptr = talloc_strndup(ctx->talloc_ctx, data, length); ++ if (!length && ed->context_default) ++ goto skip; ++ if (!length && ed->defval.s) { ++ *strptr = talloc_strdup(ctx->talloc_ctx, ed->defval.s); ++ } else { ++ *strptr = talloc_strndup(ctx->talloc_ctx, data, length); ++ } + MP_TRACE(ctx, "string \"%s\"\n", *strptr); + break; + +@@ -583,6 +598,7 @@ static void ebml_parse_element(struct ebml_parse_ctx *ctx, void *target, + } + *countptr += 1; + error: ++ skip: + data += length; + } + } +diff --git a/demux/ebml.h b/demux/ebml.h +index e8817312..07cb84b1 100644 +--- a/demux/ebml.h ++++ b/demux/ebml.h +@@ -54,6 +54,13 @@ struct ebml_elem_desc { + int size; + int field_count; + const struct ebml_field_desc *fields; ++ bool context_default; // default derives from other elements ++ union { ++ uint64_t u; ++ int64_t i; ++ double f; ++ const char *s; ++ } defval; // default value of a zero-length element + }; + + struct ebml_parse_ctx { diff --git a/third_party/patches/mpv-p1-hls-edition.patch b/third_party/patches/mpv-p1-hls-edition.patch new file mode 100644 index 0000000000..dc1a67e7a2 --- /dev/null +++ b/third_party/patches/mpv-p1-hls-edition.patch @@ -0,0 +1,68 @@ +diff --git a/demux/demux_lavf.c b/demux/demux_lavf.c +index 4d91983e..35f3a7bd 100644 +--- a/demux/demux_lavf.c ++++ b/demux/demux_lavf.c +@@ -1038,6 +1038,7 @@ static void build_editions(demuxer_t *demuxer) + // lavf happened to discover them. + AVProgram **progs = talloc_memdup(NULL, avfc->programs, avfc->nb_programs * sizeof(progs[0])); + qsort(progs, avfc->nb_programs, sizeof(progs[0]), cmp_avprogram); ++ bool *nonempty = talloc_zero_array(progs, bool, avfc->nb_programs); + + int first_nonempty = -1; + for (unsigned i = 0; i < avfc->nb_programs; i++) { +@@ -1092,6 +1093,7 @@ static void build_editions(demuxer_t *demuxer) + if (title) + mp_tags_set_str(ed.metadata, "title", title); + ++ nonempty[i] = track_count > 0; + if (track_count > 0 && first_nonempty < 0) + first_nonempty = demuxer->num_editions; + +@@ -1104,39 +1106,24 @@ static void build_editions(demuxer_t *demuxer) + if (edition_id >= 0 && edition_id < demuxer->num_editions) + selected = edition_id; + +- // Select initial edition by best variant bitrate. Prefer the program's +- // video stream as the representative, falling back to audio for +- // audio-only variants (e.g. HLS audio-only renditions). ++ // Select initial edition by best variant bitrate from the program's ++ // metadata (HLS variant BANDWIDTH). + if (selected < 0 && hls_bitrate >= 0) { + int best = -1; + int best_bitrate = 0; + bool best_ok = false; + for (int n = 0; n < demuxer->num_editions; n++) { + AVProgram *prog = progs[n]; +- struct sh_stream *rep = NULL; +- for (unsigned j = 0; j < prog->nb_stream_indexes; j++) { +- unsigned idx = prog->stream_index[j]; +- if (idx >= priv->num_streams || !priv->streams[idx]->sh) +- continue; +- struct sh_stream *sh = priv->streams[idx]->sh; +- if (sh->hls_bitrate <= 0) +- continue; +- if (sh->type == STREAM_VIDEO) { +- rep = sh; +- break; +- } +- if (sh->type == STREAM_AUDIO && !rep) +- rep = sh; +- } +- if (!rep) ++ int bitrate = dict_get_decimal(prog->metadata, "variant_bitrate", 0); ++ if (bitrate <= 0 || !nonempty[n]) + continue; +- bool ok = rep->hls_bitrate <= hls_bitrate; ++ bool ok = bitrate <= hls_bitrate; + if (best < 0 || (ok && !best_ok) || +- (ok && best_ok && rep->hls_bitrate > best_bitrate) || +- (!ok && !best_ok && rep->hls_bitrate < best_bitrate)) ++ (ok && best_ok && bitrate > best_bitrate) || ++ (!ok && !best_ok && bitrate < best_bitrate)) + { + best = n; +- best_bitrate = rep->hls_bitrate; ++ best_bitrate = bitrate; + best_ok = ok; + } + } diff --git a/third_party/patches/mpv-p1-packed-rgb10.patch b/third_party/patches/mpv-p1-packed-rgb10.patch new file mode 100644 index 0000000000..cc9800712e --- /dev/null +++ b/third_party/patches/mpv-p1-packed-rgb10.patch @@ -0,0 +1,35 @@ +diff --git a/video/out/placebo/ra_pl.c b/video/out/placebo/ra_pl.c +index 14ae6277..5ef16c35 100644 +--- a/video/out/placebo/ra_pl.c ++++ b/video/out/placebo/ra_pl.c +@@ -103,6 +103,30 @@ struct ra *ra_create_pl(pl_gpu gpu, struct mp_log *log) + rafmt->component_depth[c] = plfmt->component_depth[c]; + } + ++ // Special formats for which libplacebo happens to have direct support. ++ if (strcmp(plfmt->name, "rgb10a2") == 0) { ++ rafmt->special_imgfmt = IMGFMT_X2BGR10; ++ struct ra_imgfmt_desc *desc = talloc_zero(rafmt, struct ra_imgfmt_desc); ++ rafmt->special_imgfmt_desc = desc; ++ desc->component_bits = 10; ++ desc->num_planes = 1; ++ desc->planes[0] = rafmt; ++ for (int c = 0; c < 3; c++) ++ desc->components[0][c] = c + 1; ++ desc->chroma_w = desc->chroma_h = 1; ++ } ++ if (strcmp(plfmt->name, "bgr10a2") == 0) { ++ rafmt->special_imgfmt = IMGFMT_X2RGB10; ++ struct ra_imgfmt_desc *desc = talloc_zero(rafmt, struct ra_imgfmt_desc); ++ rafmt->special_imgfmt_desc = desc; ++ desc->component_bits = 10; ++ desc->num_planes = 1; ++ desc->planes[0] = rafmt; ++ for (int c = 0; c < 3; c++) ++ desc->components[0][c] = 3 - c; ++ desc->chroma_w = desc->chroma_h = 1; ++ } ++ + MP_TARRAY_APPEND(ra, ra->formats, ra->num_formats, rafmt); + } + diff --git a/third_party/patches/mpv-p2-generic-uv.patch b/third_party/patches/mpv-p2-generic-uv.patch new file mode 100644 index 0000000000..8feea3c4d7 --- /dev/null +++ b/third_party/patches/mpv-p2-generic-uv.patch @@ -0,0 +1,203 @@ +diff --git a/video/out/hwdec/hwdec_aimagereader.comp b/video/out/hwdec/hwdec_aimagereader.comp +index d87d33affb34587900b6fb54fffa5cf21e59aa66..1f3bbb1f6d850d71959da1e1cd4882b5cc9b149f 100644 +--- a/video/out/hwdec/hwdec_aimagereader.comp ++++ b/video/out/hwdec/hwdec_aimagereader.comp +@@ -7,10 +7,9 @@ layout(set = 0, binding = 0) uniform sampler2D source_image; + layout(set = 0, binding = 1) writeonly uniform image2D target_image; + + layout(push_constant) uniform PushConstants { +- ivec2 crop_offset; +- ivec2 crop_size; ++ vec2 uv_offset; ++ vec2 uv_scale; + ivec2 output_size; +- ivec2 source_size; + } params; + + void main() +@@ -19,10 +18,7 @@ void main() + if (any(greaterThanEqual(position, params.output_size))) + return; + +- vec2 source_position = +- vec2(params.crop_offset) + +- (vec2(position) + vec2(0.5)) * vec2(params.crop_size) / +- vec2(params.output_size); +- vec2 uv = source_position / vec2(params.source_size); ++ vec2 uv = params.uv_offset + ++ (vec2(position) + vec2(0.5)) * params.uv_scale; + imageStore(target_image, position, textureLod(source_image, uv, 0.0)); + } +diff --git a/video/out/hwdec/hwdec_aimagereader.frag b/video/out/hwdec/hwdec_aimagereader.frag +index 6f172c23bcf9188199fc554cd5f880cc5ee46968..c640e6e0e9258313ace5162cb3a92030cb9fb632 100644 +--- a/video/out/hwdec/hwdec_aimagereader.frag ++++ b/video/out/hwdec/hwdec_aimagereader.frag +@@ -4,21 +4,17 @@ layout(set = 0, binding = 0) uniform sampler2D source_image; + layout(location = 0) out vec4 target_color; + + layout(push_constant) uniform PushConstants { +- ivec2 crop_offset; +- ivec2 crop_size; ++ vec2 uv_offset; ++ vec2 uv_scale; + ivec2 output_size; +- ivec2 source_size; + } params; + + void main() + { + ivec2 position = ivec2(gl_FragCoord.xy); +- vec2 source_position = +- vec2(params.crop_offset) + +- (vec2(position) + vec2(0.5)) * vec2(params.crop_size) / +- vec2(params.output_size); + // The imported AHardwareBuffer extent is authoritative for external-format + // images and avoids relying on driver image-size queries. +- vec2 uv = source_position / vec2(params.source_size); ++ vec2 uv = params.uv_offset + ++ (vec2(position) + vec2(0.5)) * params.uv_scale; + target_color = texture(source_image, uv); + } +diff --git a/video/out/hwdec/hwdec_aimagereader_vk_convert.c b/video/out/hwdec/hwdec_aimagereader_vk_convert.c +index bfba275f4bfe45e717924e580215dbb888d5125f..c408d0a0e979aa07a6a987d95e949ce3ff8c4248 100644 +--- a/video/out/hwdec/hwdec_aimagereader_vk_convert.c ++++ b/video/out/hwdec/hwdec_aimagereader_vk_convert.c +@@ -38,12 +38,21 @@ + #define FALLBACK_EXTERNAL_DESCRIPTOR_COUNT 4 + + struct conversion_push_constants { ++ float uv_offset[2]; ++ float uv_scale[2]; ++ int32_t output_size[2]; ++}; ++ ++struct conversion_geometry { + int32_t crop_offset[2]; + int32_t crop_size[2]; + int32_t output_size[2]; + int32_t source_size[2]; + }; + ++_Static_assert(sizeof(struct conversion_push_constants) == 24, ++ "generic Vulkan push constant layout changed"); ++ + enum output_precision { + OUTPUT_PRECISION_8_BIT, + OUTPUT_PRECISION_10_BIT, +@@ -140,7 +149,7 @@ struct aimagereader_vk_convert { + uint64_t input_serial; + struct vk_output outputs[OUTPUT_COUNT]; + bool conversion_geometry_valid; +- struct conversion_push_constants conversion_geometry; ++ struct conversion_geometry conversion_geometry; + }; + + static bool vk_success(struct aimagereader_vk_convert *p, VkResult result, +@@ -1683,17 +1692,17 @@ static void release_reclaimed_output(struct aimagereader_vk_convert *p, + + static void log_conversion_geometry( + struct aimagereader_vk_convert *p, +- const struct conversion_push_constants *push) ++ const struct conversion_geometry *geometry) + { + if (p->conversion_geometry_valid && +- p->conversion_geometry.crop_offset[0] == push->crop_offset[0] && +- p->conversion_geometry.crop_offset[1] == push->crop_offset[1] && +- p->conversion_geometry.crop_size[0] == push->crop_size[0] && +- p->conversion_geometry.crop_size[1] == push->crop_size[1] && +- p->conversion_geometry.output_size[0] == push->output_size[0] && +- p->conversion_geometry.output_size[1] == push->output_size[1] && +- p->conversion_geometry.source_size[0] == push->source_size[0] && +- p->conversion_geometry.source_size[1] == push->source_size[1]) ++ p->conversion_geometry.crop_offset[0] == geometry->crop_offset[0] && ++ p->conversion_geometry.crop_offset[1] == geometry->crop_offset[1] && ++ p->conversion_geometry.crop_size[0] == geometry->crop_size[0] && ++ p->conversion_geometry.crop_size[1] == geometry->crop_size[1] && ++ p->conversion_geometry.output_size[0] == geometry->output_size[0] && ++ p->conversion_geometry.output_size[1] == geometry->output_size[1] && ++ p->conversion_geometry.source_size[0] == geometry->source_size[0] && ++ p->conversion_geometry.source_size[1] == geometry->source_size[1]) + return; + + mp_info(p->log, "Vulkan conversion geometry: imported image %ux%u " +@@ -1702,14 +1711,14 @@ static void log_conversion_geometry( + "external format 0x%" PRIx64 ", output format %d\n", + p->source.desc.width, p->source.desc.height, + p->source.desc.stride, p->source.desc.format, +- push->crop_offset[0], push->crop_offset[1], +- push->crop_size[0], push->crop_size[1], ++ geometry->crop_offset[0], geometry->crop_offset[1], ++ geometry->crop_size[0], geometry->crop_size[1], + conversion_backend_name(p->backend), +- push->output_size[0], push->output_size[1], ++ geometry->output_size[0], geometry->output_size[1], + p->source.format_props.format, + p->source.format_props.externalFormat, p->output_format); + p->conversion_geometry_valid = true; +- p->conversion_geometry = *push; ++ p->conversion_geometry = *geometry; + } + + static bool record_conversion(struct aimagereader_vk_convert *p, +@@ -1778,7 +1787,6 @@ static bool record_conversion(struct aimagereader_vk_convert *p, + conversion_stage, 0, + 0, NULL, 0, NULL, MP_ARRAY_SIZE(acquire), acquire); + +- log_conversion_geometry(p, push); + if (use_compute) { + vkCmdBindPipeline(output->command, VK_PIPELINE_BIND_POINT_COMPUTE, + p->pipeline); +@@ -2039,6 +2047,8 @@ struct aimagereader_vk_convert *aimagereader_vk_convert_create( + p->required_backend == CONVERSION_BACKEND_NONE + ? "auto (narrowest format, compute tie-break)" + : conversion_backend_name(p->required_backend)); ++ mp_verbose(p->log, ++ "Generic Vulkan conversion uses CPU-precomputed UV transform\n"); + + p->GetImageFormatProperties2 = get_image_format_properties2(p->vk); + +@@ -2223,18 +2233,30 @@ static int map_image(struct aimagereader_vk_convert *p, AImage *image, + release_reclaimed_output(p, output, needs_reclaim); + return -1; + } +- const struct conversion_push_constants push = { ++ const int32_t crop_width = crop->right - crop->left; ++ const int32_t crop_height = crop->bottom - crop->top; ++ const struct conversion_geometry geometry = { + .crop_offset = {crop->left, crop->top}, +- .crop_size = { +- crop->right - crop->left, +- crop->bottom - crop->top, +- }, ++ .crop_size = {crop_width, crop_height}, + .output_size = {source.output_width, source.output_height}, + .source_size = { + source.desc.width, + source.desc.height, + }, + }; ++ const struct conversion_push_constants push = { ++ .uv_offset = { ++ (float)((double)crop->left / source.desc.width), ++ (float)((double)crop->top / source.desc.height), ++ }, ++ .uv_scale = { ++ (float)((double)crop_width / ++ ((double)source.output_width * source.desc.width)), ++ (float)((double)crop_height / ++ ((double)source.output_height * source.desc.height)), ++ }, ++ .output_size = {source.output_width, source.output_height}, ++ }; + int release_fence = -1; + bool release_exported = false; + if (!record_conversion(p, output, input, &push)) { +@@ -2242,6 +2264,7 @@ static int map_image(struct aimagereader_vk_convert *p, AImage *image, + release_reclaimed_output(p, output, needs_reclaim); + return -1; + } ++ log_conversion_geometry(p, &geometry); + bool submitted = submit_conversion(p, output, needs_reclaim, + acquire_fence, &release_fence, + &release_exported); + diff --git a/webhome-devkit/docs/应用完整开发文档.md b/webhome-devkit/docs/应用完整开发文档.md index 02669c00f0..21e134e3dc 100644 --- a/webhome-devkit/docs/应用完整开发文档.md +++ b/webhome-devkit/docs/应用完整开发文档.md @@ -81,13 +81,13 @@ Gradle 任务由两个 flavor 维度和构建类型组成,例如 `:app:assembl 普通 APK 打包必须安装: -- JDK 21。JDK 17 会编译失败。 +- 需要 JDK 21。 - Git。 - Python 3.10。Chaquo 运行时固定为 3.10,并会在构建时安装 `chaquo/requirements.txt`;只有 Python 3.11/3.12/3.13 不够。 - Android SDK Command-line Tools、Platform 37.0、Build Tools 37.0.0 和 Platform Tools。 - 可访问 Maven Central、Google Maven、Gradle Plugin Portal、JitPack 的网络。 -Android Studio 仅是可选 IDE,不是项目依赖。Gradle Wrapper 和仓库脚本不会读取 Android Studio 的安装目录或内置 JBR;命令行构建只使用 `JAVA_HOME`/`PATH` 中的 JDK,以及 `ANDROID_HOME`、`ANDROID_SDK_ROOT` 或 `local.properties` 指定的 Android SDK。 +Gradle Wrapper 和仓库脚本使用 `JAVA_HOME`/`PATH` 中的 JDK,以及 `ANDROID_HOME`、`ANDROID_SDK_ROOT` 或 `local.properties` 指定的 Android SDK。 普通 Gradle 打包不编译 MPV、IJK、FFmpeg、OpenSSL、DVD 或 JNI,因而不要求安装 NDK、Perl、`pkg-config` 等 native 工具。只有修改 native 源码、补丁或锁定版本时才安装对应工具链:按 3.5 节使用 NDK `29.0.14206865` 重建 MPV/FFmpeg/libplacebo/JNI,按 3.5.1 节使用 NDK `28.2.13676358` 重建 IJK/DVD。两套 ARM ABI 都不再需要 NDK 21。 @@ -147,7 +147,7 @@ test -x "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" bash gradlew --version ``` -命令行构建需要根目录有 `local.properties`。它是普通文本配置,在 clone 后进入仓库根目录直接生成,不需要 Android Studio: +命令行构建需要根目录有 `local.properties`。它是普通文本配置,在 clone 后进入仓库根目录直接生成: ```bash export ANDROID_HOME="$HOME/Library/Android/sdk" @@ -166,7 +166,7 @@ Linux 常见 SDK 路径是 `$HOME/Android/Sdk`;Windows 的 `local.properties` yes | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses ``` -`platforms;android-37.0` 是当前 `sdkmanager` 返回的实际包名;Gradle 中仍写 `compileSdk=37`。如果 `cmdline-tools/latest/bin/sdkmanager` 不存在,请安装官方 Android SDK Command-line Tools,并将其按 `cmdline-tools/latest/` 目录结构放入 SDK;Android Studio 的 SDK Manager 仅是可选的图形化安装方式。 +`platforms;android-37.0` 是当前 `sdkmanager` 返回的实际包名;Gradle 中仍写 `compileSdk=37`。如果 `cmdline-tools/latest/bin/sdkmanager` 不存在,请安装官方 Android SDK Command-line Tools,并将其按 `cmdline-tools/latest/` 目录结构放入 SDK。 ### 3.3 从零 clone 到打包 @@ -304,12 +304,12 @@ app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libplayer.so `build_mpv_player_jni.sh` 只重建 `libplayer.so`,而且要求对应 ABI 的 MPV prefix 已由 `scripts/build_mpv_native.sh` 生成。如果修改的是 `libmpv.so`、FFmpeg、libplacebo、MPV commit 或 native lock,应先用 native 脚本完成整套编译、FFmpeg SONAME 重命名、strip 和依赖检查。仅重编相同 client/stream callback API 的 MPV/FFmpeg 时理论上可以复用 `libplayer.so`;修改 `stream_cb.h`、光盘控制补丁、JNI 源码或发布一套新的可复现 lock 时,建议两端一起重建。 -当前 `libmpv.so` 已启用 OpenGL、Vulkan、MediaCodec AImageReader/AHardwareBuffer、libcurl 和 HTTP/2。截至 2026-08-17,两套 ABI assets 已按当前 lock、构建脚本和补丁集通过能力标记与 ELF 校验: +当前 `libmpv.so` 已启用 OpenGL、Vulkan、MediaCodec AImageReader/AHardwareBuffer、libcurl 和 HTTP/2。截至 2026-08-29,两套 ABI assets 已按当前 lock、构建脚本和补丁集通过能力标记与 ELF 校验: | ABI | MPV | FFmpeg | libplacebo | 网络后端 | 状态 | | --- | --- | --- | --- | --- | --- | -| `arm64-v8a` | `0.41.0-940-gcca559b41` | `04482c8d13ac`(9.0-fongmi) | `7.375.0` / `b694a21bf2dc` | curl 8.21.0 + nghttp2 1.69.0 | 已按 `third_party/mpv-native-lock.json` 重编,并通过能力、ELF 与 APK 资产哈希校验 | -| `armeabi-v7a` | `0.41.0-940-gcca559b41` | `04482c8d13ac`(9.0-fongmi) | `7.375.0` / `b694a21bf2dc` | curl 8.21.0 + nghttp2 1.69.0 | 已使用同一源码 lock 独立重编并通过校验,不能跨 ABI 复制 | +| `arm64-v8a` | `0.41.0-940-gcca559b41` | `177f090e0503`(9.0.1-fongmi) | `7.375.0` / `b694a21bf2dc` | curl 8.21.0 + nghttp2 1.69.0 | C0-M 双 ABI、ELF、APK 和 arm64 手机播放/生命周期验证通过 | +| `armeabi-v7a` | `0.41.0-940-gcca559b41` | `177f090e0503`(9.0.1-fongmi) | `7.375.0` / `b694a21bf2dc` | curl 8.21.0 + nghttp2 1.69.0 | C0-M 独立重建及 ELF/资产验证通过,不能跨 ABI 复制 | 两套 ABI 的源码锁定: @@ -317,7 +317,7 @@ app/src/armeabi_v7a/assets/mpv-libs/armeabi-v7a/libplayer.so | --- | --- | | mpv-android 构建框架/JNI 参考 | `99a60ad2141d5ace94453590903c2c6b9a0a2443` | | MPV | `cca559b41ceb0bb7731cf6ef2e1f33276cd30c42`(`0.41.0-940-gcca559b41`) | -| FFmpeg | `04482c8d13ac27b2a9fe93f5d388929eef8af5f4`(9.0-fongmi) | +| FFmpeg | `177f090e0503b7e013922ca903bde14b1c375f18`(9.0.1-fongmi,C0-M 已验证) | | libplacebo | `b694a21bf2dc176c1e98b8a13c6421a0de5f3da5`(7.375.0 / API 375) | | curl | 8.21.0,MbedTLS,仅 HTTP/HTTPS,启用 HTTP/2 | | nghttp2 | 1.69.0 | @@ -551,7 +551,7 @@ GitHub Actions 正式发布需要配置 release signing secrets;本地 debug | `Unsupported class file major version` 或 `invalid source release: 21` | 当前终端没有使用 JDK 21 | | `Chaquopy ... is not a valid Python 3.10 command` 或找不到 `python3.10` | 安装主机 Python 3.10,并确保 `python3.10 --version` 可在当前终端执行;仅安装系统默认 Python 3.12 不够 | | `SDK location not found` | 缺少 `local.properties`,或 `sdk.dir` 指向错误 | -| `.../cmdline-tools/latest/bin/sdkmanager: No such file or directory` | 安装官方 Android SDK Command-line Tools,确认其位于 `$ANDROID_HOME/cmdline-tools/latest/`,并检查 `ANDROID_HOME`;不要求安装 Android Studio | +| `.../cmdline-tools/latest/bin/sdkmanager: No such file or directory` | 安装官方 Android SDK Command-line Tools,确认其位于 `$ANDROID_HOME/cmdline-tools/latest/`,并检查 `ANDROID_HOME` | | `failed to find target with hash string 'android-37'` | 安装 Android SDK Platform 37 | | `NDK clang++ not found` | 重建 MPV/JNI 时安装 `29.0.14206865`;重建 IJK/DVD 时安装 `28.2.13676358`,并让 `ANDROID_NDK_HOME` 与对应 lock 一致 | | `Missing tool: perl` | macOS 检查系统 Perl;Ubuntu 安装 `perl` | diff --git a/webhome-devkit/skills/upstream-integration-governor/SKILL.md b/webhome-devkit/skills/upstream-integration-governor/SKILL.md new file mode 100644 index 0000000000..66d524b443 --- /dev/null +++ b/webhome-devkit/skills/upstream-integration-governor/SKILL.md @@ -0,0 +1,114 @@ +--- +name: upstream-integration-governor +description: Inventory related upstream repositories, generate or refresh exhaustive commit-ledger assessment documents, and evaluate or implement dependency integrations safely, efficiently, and reversibly. Use when Codex is asked to inspect, compare, assess, port, merge, cherry-pick, rebase, rebuild, or update upstream commits, forks, locks, patches, AARs, native libraries, or binary dependency packages—especially WebHTV FFmpeg, AndroidX media/Media3/nextlib, mpv, mpv-android, libplacebo, IJK, JNI, Exo, MPV, or cross-repository player work; also use for regression, performance, provenance, rollback, commit/tag, staged rollout, and durable checkpoint planning around those changes. +--- + +# Upstream Integration Governor + +Turn upstream changes into bounded, evidence-backed, user-decidable stages and, only after approval, reversible WebHTV changes. Do not use this long workflow for an ordinary App bug unless it actually crosses an upstream/native contract. + +For maintenance of this Skill, governance text, or task-guard wording, follow the root `AGENTS.md` governance-maintenance fast path. Do not invoke this upstream workflow, load its references, research best practices, forward-test, or create a temporary repository. Make one bounded patch and one combined validation pass, then stop. + +## Select one bounded lane first + +- `assessment`: use a 45-minute progress-review cadence, each batch focused on one related function cluster or at most 25 straightforward commits. Only the assessment document and explicit governance/evidence files may change. +- `upstream`: use a 45-minute progress-review cadence around one approved atomic implementation unit. Declare all source, lock, patch, artifact, App, test, and documentation paths before editing. +- Never silently turn assessment into implementation or a narrow App fix into upstream research. + +Start `bash .codex/scripts/task_guard.sh` using the matching lane. Check it after each repository/query batch and before a build, native command, or large diff. At 70% of a cadence, checkpoint before opening new work. At the boundary, preserve concrete progress; continue a converging route with one bounded next action, or replan a stalled/repeated route and immediately resume. Cadences never cap total task time or review count. Never lower verification quality, call an unverified candidate complete, or abandon the requested result because time elapsed. + +## Stable task IDs and one-document ownership + +- Use `docs/upstream-player-dependency-merge-assessment-2026-08-20.md` as the stable task index and exhaustive commit ledger. Resolve or allocate the task ID there before opening task-specific documentation. +- Preserve the established families: `E*`/`E*-*` for Exo, `E-SP*` for Exo performance, `P*`/`P*-*` for MPV, and `C*`/`C*-*` for common work. Assigned IDs are immutable and must not be renumbered or reused. +- A started task owns exactly one `docs/-.md`. Put research, alternatives, recommendation, approval, implementation, repeated corrections, validation, full commit/tag records, rollback, current status, and the one next action in that file. +- Never create additional `plans/`, assessment, implementation, fix, or dated continuation documents for the same task. Continue appending to its unique file. The master assessment is the only exception and only supplies the cross-task index and complete commit ledger. + +## Build or refresh an upstream assessment ledger + +Use this mode when the user asks to梳理 new upstream updates, rebuild the player dependency merge plan, or produce a document comparable to the existing dated assessment. + +1. Discover the repository graph from the prior assessment, `.gitmodules`, lock files, source/version manifests, Gradle/native build scripts, patch directories, artifact provenance, and repository documentation. Include direct upstreams, WebHTV forks, dependency/source repositories, and packaging repositories that can change the shipped player behavior; record why each repository is in scope and how revisions flow between them. +2. Freeze exact local and upstream baselines before judging commits: repository URL/path, branch, previous assessed head, current head, ancestry, relevant lock or artifact hash, access date, and any proxy or source-access limitation. Never infer a missing hash from conversation memory. +3. Enumerate the complete commit range in each repository using full 40-character IDs. Inspect actual diffs, parents, tests, follow-ups, reverts, rebases/equivalents, downstream consumers, and final-tree behavior. Give every commit one explicit disposition such as already implemented, partially implemented, superseded, irrelevant, candidate, blocked, or implemented; do not omit merge, cleanup, or low-value commits merely because they are inconvenient. +4. Map cross-repository chains rather than presenting isolated lists. Show which source commit feeds which fork/lock/patch/artifact/App change, which commits are companions, and which ordering or binary rebuild dependency makes them one functional stage. +5. Compare the ledger with current WebHTV code and Git history before creating tasks. Existing local behavior is the baseline contract; detect equivalent implementations, later fixes, partial coverage, and code paths that make an upstream change unreachable. Mark covered or meaningless work as ignored instead of manufacturing a task. +6. Preserve a closed historical assessment. When a materially new upstream wave begins, create `docs/upstream-player-dependency-merge-assessment-YYYY-MM-DD.md`, link its predecessor, and record the new baselines; when continuing the same active wave, update its existing dated document. The document must remain the exhaustive cross-task index and link each actionable item to its single `docs/-.md` file. +7. Organize actionable work into reversible `Exo`, `MPV`, and `common` stages with the selection order `Exo -> MPV -> common`. For every stage record the user-visible playback capability, repository/commit chain, current coverage, benefits, risks and disadvantages, compatibility/performance/package-size impact, best-practice evidence, WebHTV adaptation, recommendation, acceptance criteria, verification, rollout, rollback, and next action. + +For a request that only asks for the next task, do not mutate the ledger or code. Recover the current state, identify exactly one unambiguous next candidate, and return the following decision packet in ordinary user-facing language: + +```text +任务编号和名称: +所属分类:Exo / MPV / 通用 +要实现的实际能力: +当前项目已有实现: +涉及仓库及完整 commit ID: +收益: +缺点与风险: +与现有功能的关系: +建议:实施 / 暂缓 / 忽略 +最小实施步骤: +预计需要的验证: +``` + +Stop after that packet. Do not implement until the user explicitly approves the candidate. When estimating approved work, report current-agent wall-clock execution time and separate code work, native/Gradle build time, device or user-dependent validation, and commit/tag/document closure when those phases apply. + +## Mandatory best-practice review before implementation + +This gate applies to every proposed upstream merge stage and every material new player/dependency requirement. It is not optional merely because a commit appears small or its upstream title sounds authoritative. + +1. Before implementation, create or update the unique `docs/-.md` and link it from the assessment index. Its best-practice section is the durable decision record; a separate `plans/` file or conversation summary is insufficient. +2. Perform a focused but deep external review. Search all applicable categories: exact upstream source, history, tests, and follow-ups; official platform/specification/project documentation; PRs, issues, reverts, and maintainer discussions; mature related-project implementations and tests; and relevant academic papers, technical posts, blogs, benchmarks, or field reports. Inapplicable categories must be explicitly marked with a reason. +3. Inspect complete sources and revisions, not snippets. Record full commit IDs, URLs/paths, access dates, evidence grade, relevant code or excerpt, applicability to WebHTV, caveats, and how each source changes the decision. Research must use the configured proxy when needed and must not be represented as complete when network/source access failed. +4. Review the current WebHTV code before choosing a port: concrete files/symbols, callers and data flow, existing equivalent/partial implementations, local patches and safeguards, build/package reachability, and relevant tests or device evidence. +5. Compare `no change`, unmodified upstream, and a WebHTV-adapted design. The plan must state whether the upstream design should be optimized, corrected, supplemented, completed, or rejected for this workload, with explicit tradeoffs and acceptance/rollback criteria. +6. Pause for user approval after the plan is decision-ready. No code, lock, build, patch, or binary edit is allowed before approval. Keep the investigation bounded by one decision-shaped question; stop when more sources cannot change the decision and record any remaining uncertainty as a gate. + +## Load only the needed references + +- Read `references/integration-workflow.md` completely when starting a stage, changing stage design, or implementing. For a continuation with a valid checkpoint, read the checkpoint and only the directly relevant workflow section. +- Read `references/evidence-and-research.md` completely only when a decision depends on an unresolved correctness, best-practice, compatibility, performance, security, or architecture claim. +- Read `references/webhtv-player-gates.md` completely before recommending or implementing player/native behavior. A ledger-only continuation may read the relevant player section after checkpoint recovery. +- Run `scripts/verify_upstream_checkpoint.sh ` at recovery points and before handoff. It is read-only. + +Do not load references “just in case.” The active question decides what enters context. + +## Core workflow + +1. **Recover durable state.** Read root `AGENTS.md`, `README.md`, the assessment task index, the unique task document and its latest checkpoint, relevant locks/build docs, `git status`, branch, and HEAD. Reconcile discrepancies before continuing. +2. **Fix authority and scope.** State assessment-only or approved implementation; list repositories, exact ranges, declared paths, exclusions, review boundary, cheapest decisive verification, and approval gates. +3. **Freeze the baseline.** Record full source/local hashes, ancestry, artifacts and hashes, patches, toolchain, current behavior, representative inputs, diagnostics, dirty protected files, and rollback anchor. +4. **Build a complete commit ledger.** Enumerate every commit in range and inspect actual diffs, parents, final tree, tests, issues, consumers, rebases/equivalents/reverts, and local coverage. +5. **Run the mandatory best-practice review.** Use the gate above and `references/evidence-and-research.md`; use at most three query reformulations for one decision question and normally stop after five applicable primary sources plus two independent corroborating sources, while covering every applicable source category. +6. **Create functional stages.** Group associated commits across repositories into independently implementable `Exo`, `MPV`, or `common` stages. Preserve `Exo -> MPV`; explain when common work must ride with a player. +7. **Write the decision packet and plan.** Write it into the unique `docs/-.md`; include full commit IDs, benefit, current gap, design, alternatives, preserved contracts, risks, performance/security/ABI/license/provenance impact, validation, rollout, rollback, recommendation, and user decision field. Link that file from the assessment index. +8. **Pause at material decisions.** Do not implement an unapproved stage or silently expand scope. A changed architecture, product behavior, binary ownership, or earlier decision requires a plan update and direction. +9. **Implement narrowly after approval.** Use a branch/worktree where appropriate, record rollback, port one logical unit, preserve local fixes, and prefer adaptation over blind cherry-pick when contracts differ. +10. **Validate by risk.** Run the smallest decisive check first. Do not rerun an unchanged command to filter output; retain and inspect its first result. Broaden only for residual risk. +11. **Record immediately.** Update the durable document after each research batch, implementation unit, and validation phase with exact hashes, result, rollback, and one next action. +12. **Close the unit.** For approved code changes, use the task guard to create the atomic commit and annotated local recovery tag. Record artifact hashes, tests, deviations, remaining risks, and rollback. Never push or move published tags without explicit permission. + +## Non-negotiable output rules + +- Use full 40-character commit IDs in source ledgers and implementation records. +- Give every in-scope commit a disposition; never omit inconvenient or low-value commits. +- A commit ledger is exhaustive, but web research is not repeated per commit. Research a shared uncertainty once and link affected commits to that evidence. +- “Deep research” means source-backed coverage of every applicable category in the mandatory gate plus a concrete local-code review; it does not mean unbounded browsing or collecting duplicate commentary. +- Mark observations, inferences, recommendations, approvals, and verified results distinctly. +- Treat current behavior and local patches as contracts until evidence and user approval say otherwise. +- Do not convert a successful build into a claim of behavioral, performance, ABI, or lifecycle correctness. +- Do not use conversation history as the sole record. Maintain checkpoints using `references/integration-workflow.md`. +- Two failed attempts using the same theory/build path require a new hypothesis or smaller unit; they do not justify an open-ended third attempt, reduced acceptance criteria, or abandoning the task. +- Do not tag uncommitted edits. Use atomic commits as rollback units and annotated tags only for meaningful committed recovery states. +- After an atomic commit, create the local annotated recovery tag immediately in one non-interactive, signing-disabled command. Do not re-run validation or provenance review between commit and tag; target a tag phase under 5 seconds and never repeat an unchanged failing tag command. + +## WebHTV default ordering + +1. Complete decision-ready Exo stages and common companions. +2. Implement only approved Exo stages and stabilize their artifacts. +3. Re-evaluate shared FFmpeg/source assumptions from Exo evidence. +4. Complete and implement approved MPV stages as a separate binary chain. +5. Attach common work to a player only when API, ownership, or compatibility requires it; otherwise keep it independently reversible. + +Continue from `docs/upstream-player-dependency-merge-assessment-2026-08-20.md`; do not repeat completed analysis unless observed heads or material evidence changed.