From caaef3935c22b775aa87d6f5319df1c06b873427 Mon Sep 17 00:00:00 2001 From: Martin Wimpress Date: Thu, 19 Mar 2026 10:13:07 +0000 Subject: [PATCH 1/3] chore: update to Go 1.26.1 Signed-off-by: Martin Wimpress --- .envrc | 1 + .github/workflows/build.yml | 2 +- .github/workflows/release.yml | 2 +- flake.lock | 6 +++--- flake.nix | 2 +- go.mod | 2 +- third_party/ffmpeg-statigo | 2 +- 7 files changed, 9 insertions(+), 8 deletions(-) diff --git a/.envrc b/.envrc index a5dbbcb..0a9cd1d 100644 --- a/.envrc +++ b/.envrc @@ -1 +1,2 @@ +nix_direnv_manual_reload use flake . diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fede2c8..7038c97 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -47,7 +47,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v6 with: - go-version: '1.24' + go-version-file: go.mod - name: Download ffmpeg-statigo libraries run: | diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f8cdf5c..89a0cfa 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -103,7 +103,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v6 with: - go-version: '1.24' + go-version-file: go.mod - name: Download ffmpeg-statigo libraries run: | diff --git a/flake.lock b/flake.lock index 6d0ac08..10290dd 100644 --- a/flake.lock +++ b/flake.lock @@ -20,11 +20,11 @@ }, "nixpkgs": { "locked": { - "lastModified": 1767892417, - "narHash": "sha256-dhhvQY67aboBk8b0/u0XB6vwHdgbROZT3fJAjyNh5Ww=", + "lastModified": 1773821835, + "narHash": "sha256-TJ3lSQtW0E2JrznGVm8hOQGVpXjJyXY2guAxku2O9A4=", "owner": "nixos", "repo": "nixpkgs", - "rev": "3497aa5c9457a9d88d71fa93a4a8368816fbeeba", + "rev": "b40629efe5d6ec48dd1efba650c797ddbd39ace0", "type": "github" }, "original": { diff --git a/flake.nix b/flake.nix index 2ab1350..d6cc8c8 100644 --- a/flake.nix +++ b/flake.nix @@ -27,7 +27,7 @@ ffmpeg-full gnugrep gcc - go + go_1_26 just vhs ] diff --git a/go.mod b/go.mod index 5a5e0a7..db1346b 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/linuxmatters/jivefire -go 1.24.2 +go 1.26.1 require ( github.com/alecthomas/kong v1.14.0 diff --git a/third_party/ffmpeg-statigo b/third_party/ffmpeg-statigo index 4b9e396..5f355e3 160000 --- a/third_party/ffmpeg-statigo +++ b/third_party/ffmpeg-statigo @@ -1 +1 @@ -Subproject commit 4b9e3969d5e2d7140db5743b9c42b525110920bf +Subproject commit 5f355e38cfde415c6322040f613ed36da998ff4f From b402ffb87142dc4e33e7e94cb9a1304ee6170970 Mon Sep 17 00:00:00 2001 From: Martin Wimpress Date: Thu, 19 Mar 2026 10:23:53 +0000 Subject: [PATCH 2/3] feat: fit tailor community help files Signed-off-by: Martin Wimpress --- .github/FUNDING.yml | 14 +++ .github/ISSUE_TEMPLATE/bug_report.yml | 92 ++++++++++++++ .github/ISSUE_TEMPLATE/config.yml | 8 ++ .github/ISSUE_TEMPLATE/feature_request.yml | 64 ++++++++++ .github/pull_request_template.md | 14 +++ .github/workflows/tailor-automerge.yml | 76 ++++++++++++ .github/workflows/tailor.yml | 52 ++++++++ .tailor.yml | 134 +++++++++++++++++++++ CODE_OF_CONDUCT.md | 91 ++++++++++++++ CONTRIBUTING.md | 11 ++ SECURITY.md | 17 +++ SUPPORT.md | 34 ++++++ cubic.yaml | 32 +++++ 13 files changed, 639 insertions(+) create mode 100644 .github/FUNDING.yml create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml create mode 100644 .github/pull_request_template.md create mode 100644 .github/workflows/tailor-automerge.yml create mode 100644 .github/workflows/tailor.yml create mode 100644 .tailor.yml create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 SECURITY.md create mode 100644 SUPPORT.md create mode 100644 cubic.yaml diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..c843c94 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,14 @@ +# These are supported funding model platforms + +github: flexiondotorg +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry +polar: # Replace with a single Polar username +buy_me_a_coffee: # Replace with a single Buy Me a Coffee username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..8e5d25a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,92 @@ +name: 🐛 Bug Report +description: Report a bug or issue +labels: ["bug"] +body: + - type: markdown + attributes: + value: | + Please fill out the information below to help us diagnose and fix the issue. + + - type: textarea + id: steps + attributes: + label: Steps to Reproduce + description: Steps to reproduce the behavior + placeholder: | + 1. Run command: `...` + 2. Do something else: `...` + 3. Error occurs + value: | + 1. + 2. + 3. + validations: + required: true + + - type: textarea + id: expected + attributes: + label: Expected Behavior + description: What you expected to happen + placeholder: Describe the expected outcome + validations: + required: true + + - type: textarea + id: actual + attributes: + label: Actual Behavior + description: What actually happened + placeholder: Describe what actually occurred + validations: + required: true + + - type: textarea + id: error-output + attributes: + label: Error Output + description: Full error message or output (if any) + render: shell + placeholder: Paste the complete error message here + validations: + required: false + + - type: input + id: version + attributes: + label: Version + description: The version or commit hash of this project you are using + placeholder: e.g., 1.0.0, latest main branch, commit abc123def + validations: + required: true + + - type: textarea + id: environment + attributes: + label: Environment + description: Any relevant environment details + placeholder: e.g., operating system, runtime version, browser, container + validations: + required: false + + - type: textarea + id: additional-context + attributes: + label: Additional Context + description: Any other context about the problem + placeholder: Add any other relevant information, screenshots, or context + validations: + required: false + + - type: checkboxes + id: terms + attributes: + label: Checklist + description: Please confirm the following + options: + - label: I have searched existing issues to avoid duplicates + required: true + - label: I have provided all the requested information above + required: true + - label: I can reproduce this issue consistently + required: false diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..6cf9d62 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,8 @@ +blank_issues_enabled: false +contact_links: + - name: 🛟 Support + url: https://github.com/linuxmatters/jivefire/blob/HEAD/SUPPORT.md + about: Check the support guide before opening an issue. +# - name: Code of Conduct Report +# url: https://yourproject.org/community-report/ +# about: Report a Code of Conduct violation privately to the moderation team. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..299ca92 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,64 @@ +name: ✨ Feature Request +description: Suggest a new feature or enhancement +labels: ["enhancement"] +body: + - type: markdown + attributes: + value: | + Please provide details about your idea below. + + - type: textarea + id: problem + attributes: + label: Problem Statement + description: Is your feature request related to a problem? Please describe. + placeholder: A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + validations: + required: true + + - type: textarea + id: solution + attributes: + label: Proposed Solution + description: Describe the solution you'd like + placeholder: A clear and concise description of what you want to happen. + validations: + required: true + + - type: textarea + id: alternatives + attributes: + label: Alternatives Considered + description: Describe alternatives you've considered + placeholder: A clear and concise description of any alternative solutions or features you've considered. + validations: + required: false + + - type: textarea + id: use-case + attributes: + label: Use Case + description: Describe your specific use case + placeholder: How would you use this feature? What workflow would it improve? + validations: + required: true + + - type: textarea + id: additional-context + attributes: + label: Additional Context + description: Add any other context about the feature request + placeholder: Add any other context, screenshots, mockups, or examples about the feature request here. + validations: + required: false + + - type: checkboxes + id: terms + attributes: + label: Checklist + description: Please confirm the following + options: + - label: I have searched existing issues to avoid duplicates + required: true + - label: I have considered if this feature fits the project scope + required: true diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..eda3ba9 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,14 @@ +# Description + + + +Closes # + +## Additional Context + + + +## Checklist + +- [ ] I have performed a self-review of my code +- [ ] I have tested my changes and confirmed there are no regressions diff --git a/.github/workflows/tailor-automerge.yml b/.github/workflows/tailor-automerge.yml new file mode 100644 index 0000000..41a30ce --- /dev/null +++ b/.github/workflows/tailor-automerge.yml @@ -0,0 +1,76 @@ +name: Tailor automerge 🤖 + +on: + pull_request: + workflow_dispatch: + +permissions: + contents: write + pull-requests: write + +jobs: + automerge: + runs-on: ubuntu-slim + if: github.event_name == 'pull_request' + steps: + - name: Fetch Dependabot metadata + if: github.event.pull_request.user.login == 'dependabot[bot]' + id: metadata + uses: dependabot/fetch-metadata@v2 + with: + github-token: "${{ secrets.GITHUB_TOKEN }}" + skip-commit-verification: true + + - name: Automerge GitHub Actions updates + if: >- + github.event.pull_request.user.login == 'dependabot[bot]' + && steps.metadata.outputs.package-ecosystem == 'github_actions' + run: gh pr merge --auto --squash "$PR_URL" + env: + PR_URL: ${{ github.event.pull_request.html_url }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Automerge patch and minor dependency updates + if: >- + github.event.pull_request.user.login == 'dependabot[bot]' + && steps.metadata.outputs.package-ecosystem != 'github_actions' + && ( + steps.metadata.outputs.update-type == 'version-update:semver-patch' + || steps.metadata.outputs.update-type == 'version-update:semver-minor' + ) + run: gh pr merge --auto --squash "$PR_URL" + env: + PR_URL: ${{ github.event.pull_request.html_url }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Automerge flake.lock update + if: >- + github.event.pull_request.user.login == 'github-actions[bot]' + && startsWith(github.event.pull_request.head.ref, 'update_flake_lock') + run: gh pr merge --auto --squash "$PR_URL" + env: + PR_URL: ${{ github.event.pull_request.html_url }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + automerge-existing: + runs-on: ubuntu-slim + if: github.event_name == 'workflow_dispatch' + steps: + - name: Merge open Dependabot PRs + run: | + gh pr list --repo "$GITHUB_REPOSITORY" \ + --author "app/dependabot" \ + --state open \ + --json number,url \ + --jq '.[].url' | + while read -r pr_url; do + echo "::group::Merging $pr_url" + if gh pr merge --squash "$pr_url"; then + echo "Merged $pr_url" + else + echo "::warning::Failed to merge $pr_url" + fi + echo "::endgroup::" + done + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/tailor.yml b/.github/workflows/tailor.yml new file mode 100644 index 0000000..d482351 --- /dev/null +++ b/.github/workflows/tailor.yml @@ -0,0 +1,52 @@ +name: Tailor 🪡 +on: + schedule: + - cron: "0 9 * * 1" # Weekly + workflow_dispatch: + +permissions: + contents: write + issues: write + pull-requests: write + actions: write + +jobs: + alter: + runs-on: ubuntu-slim + env: + GH_TOKEN: ${{ secrets.TAILOR_TOKEN || secrets.GITHUB_TOKEN }} + steps: + - uses: actions/checkout@v6 + + - name: Tailor + uses: wimpysworld/tailor@v0 + with: + alter: true + + - name: Create PR + uses: peter-evans/create-pull-request@v8 + with: + branch: tailor-alter + title: "chore: alter tailor swatches" + + update-flake-lock: + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + steps: + - uses: actions/checkout@v6 + + - name: Check for flake.lock + id: check + run: test -f flake.lock && echo "found=true" >> "$GITHUB_OUTPUT" || echo "found=false" >> "$GITHUB_OUTPUT" + + - name: Install Nix + if: steps.check.outputs.found == 'true' + uses: DeterminateSystems/determinate-nix-action@v3 + + - name: Update flake.lock + if: steps.check.outputs.found == 'true' + uses: DeterminateSystems/update-flake-lock@v28 + with: + pr-title: "chore: update flake.lock" diff --git a/.tailor.yml b/.tailor.yml new file mode 100644 index 0000000..c314eec --- /dev/null +++ b/.tailor.yml @@ -0,0 +1,134 @@ +# Initially fitted by tailor on 2026-03-19 +license: GPL-3.0 + +repository: + description: Spin your podcast .wav into a groovy MP4 visualiser with Cava-inspired real-time audio frequencies 🔥 + homepage: https://linuxmatters.sh + has_wiki: false + has_discussions: false + has_projects: false + has_issues: true + allow_merge_commit: false + allow_squash_merge: true + allow_rebase_merge: true + squash_merge_commit_title: COMMIT_OR_PR_TITLE + squash_merge_commit_message: COMMIT_MESSAGES + merge_commit_title: MERGE_MESSAGE + merge_commit_message: PR_TITLE + delete_branch_on_merge: true + allow_update_branch: false + allow_auto_merge: true + web_commit_signoff_required: false + default_workflow_permissions: read + can_approve_pull_request_reviews: false + topics: + - audio-visualization + - audio-visualizer + - cava + - mp4 + - podcast + - youtube + +labels: + - name: bug + color: d20f39 + description: "Something isn't working" + + - name: documentation + color: 04a5e5 + description: Documentation improvement + + - name: duplicate + color: 8839ef + description: Already exists + + - name: enhancement + color: 1e66f5 + description: New feature request + + - name: good first issue + color: 40a02b + description: Good for newcomers + + - name: help wanted + color: 179299 + description: Extra attention needed + + - name: invalid + color: e64553 + description: Not valid or relevant + + - name: question + color: 7287fd + description: Needs more information + + - name: wontfix + color: dc8a78 + description: Will not be worked on + + - name: dependencies + color: fe640b + description: Dependency update + + - name: github_actions + color: ea76cb + description: GitHub Actions update + + - name: hacktoberfest-accepted + color: df8e1d + description: Hacktoberfest contribution + +swatches: + - path: .github/workflows/tailor.yml + alteration: always + + - path: .github/dependabot.yml + alteration: first-fit + + - path: .github/FUNDING.yml + alteration: first-fit + + - path: .github/ISSUE_TEMPLATE/bug_report.yml + alteration: always + + - path: .github/ISSUE_TEMPLATE/feature_request.yml + alteration: always + + - path: .github/ISSUE_TEMPLATE/config.yml + alteration: first-fit + + - path: .github/pull_request_template.md + alteration: always + + - path: SECURITY.md + alteration: always + + - path: CODE_OF_CONDUCT.md + alteration: always + + - path: CONTRIBUTING.md + alteration: always + + - path: SUPPORT.md + alteration: always + + - path: justfile + alteration: first-fit + + - path: flake.nix + alteration: first-fit + + - path: .gitignore + alteration: first-fit + + - path: .envrc + alteration: first-fit + + - path: cubic.yaml + alteration: first-fit + + - path: .tailor.yml + alteration: always + + - path: .github/workflows/tailor-automerge.yml + alteration: triggered diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..123612d --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,91 @@ +# Contributor Covenant 3.0 Code of Conduct + +## Our Pledge + +We pledge to make our community welcoming, safe, and equitable for all. + +We are committed to fostering an environment that respects and promotes the dignity, rights, and contributions of all individuals, regardless of characteristics including race, ethnicity, caste, color, age, physical characteristics, neurodiversity, disability, sex or gender, gender identity or expression, sexual orientation, language, philosophy or religion, national or social origin, socio-economic position, level of education, or other status. The same privileges of participation are extended to everyone who participates in good faith and in accordance with this Covenant. + + +## Encouraged Behaviors + +While acknowledging differences in social norms, we all strive to meet our community's expectations for positive behavior. We also understand that our words and actions may be interpreted differently than we intend based on culture, background, or native language. + +With these considerations in mind, we agree to behave mindfully toward each other and act in ways that center our shared values, including: + +1. Respecting the **purpose of our community**, our activities, and our ways of gathering. +2. Engaging **kindly and honestly** with others. +3. Respecting **different viewpoints** and experiences. +4. **Taking responsibility** for our actions and contributions. +5. Gracefully giving and accepting **constructive feedback**. +6. Committing to **repairing harm** when it occurs. +7. Behaving in other ways that promote and sustain the **well-being of our community**. + + +## Restricted Behaviors + +We agree to restrict the following behaviors in our community. Instances, threats, and promotion of these behaviors are violations of this Code of Conduct. + +1. **Harassment.** Violating explicitly expressed boundaries or engaging in unnecessary personal attention after any clear request to stop. +2. **Character attacks.** Making insulting, demeaning, or pejorative comments directed at a community member or group of people. +3. **Stereotyping or discrimination.** Characterizing anyone’s personality or behavior on the basis of immutable identities or traits. +4. **Sexualization.** Behaving in a way that would generally be considered inappropriately intimate in the context or purpose of the community. +5. **Violating confidentiality**. Sharing or acting on someone's personal or private information without their permission. +6. **Endangerment.** Causing, encouraging, or threatening violence or other harm toward any person or group. +7. Behaving in other ways that **threaten the well-being** of our community. + +### Other Restrictions + +1. **Misleading identity.** Impersonating someone else for any reason, or pretending to be someone else to evade enforcement actions. +2. **Failing to credit sources.** Not properly crediting the sources of content you contribute. +3. **Promotional materials**. Sharing marketing or other commercial content in a way that is outside the norms of the community. +4. **Irresponsible communication.** Failing to responsibly present content which includes, links or describes any other restricted behaviors. + + +## Reporting an Issue + +Tensions can occur between community members even when they are trying their best to collaborate. Not every conflict represents a code of conduct violation, and this Code of Conduct reinforces encouraged behaviors and norms that can help avoid conflicts and minimize harm. + +When an incident does occur, it is important to report it promptly. To report a possible violation, use the contact details available in the project's repository. + +Community Moderators take reports of violations seriously and will make every effort to respond in a timely manner. They will investigate all reports of code of conduct violations, reviewing messages, logs, and recordings, or interviewing witnesses and other participants. Community Moderators will keep investigation and enforcement actions as transparent as possible while prioritizing safety and confidentiality. In order to honor these values, enforcement actions are carried out in private with the involved parties, but communicating to the whole community may be part of a mutually agreed upon resolution. + + +## Addressing and Repairing Harm + +These remedies and repairs are guidelines for this project's code of conduct enforcement process. + +If an investigation by the Community Moderators finds that this Code of Conduct has been violated, the following enforcement ladder may be used to determine how best to repair harm, based on the incident's impact on the individuals involved and the community as a whole. Depending on the severity of a violation, lower rungs on the ladder may be skipped. + +1) Warning + 1) Event: A violation involving a single incident or series of incidents. + 2) Consequence: A private, written warning from the Community Moderators. + 3) Repair: Examples of repair include a private written apology, acknowledgement of responsibility, and seeking clarification on expectations. +2) Temporarily Limited Activities + 1) Event: A repeated incidence of a violation that previously resulted in a warning, or the first incidence of a more serious violation. + 2) Consequence: A private, written warning with a time-limited cooldown period designed to underscore the seriousness of the situation and give the community members involved time to process the incident. The cooldown period may be limited to particular communication channels or interactions with particular community members. + 3) Repair: Examples of repair may include making an apology, using the cooldown period to reflect on actions and impact, and being thoughtful about re-entering community spaces after the period is over. +3) Temporary Suspension + 1) Event: A pattern of repeated violation which the Community Moderators have tried to address with warnings, or a single serious violation. + 2) Consequence: A private written warning with conditions for return from suspension. In general, temporary suspensions give the person being suspended time to reflect upon their behavior and possible corrective actions. + 3) Repair: Examples of repair include respecting the spirit of the suspension, meeting the specified conditions for return, and being thoughtful about how to reintegrate with the community when the suspension is lifted. +4) Permanent Ban + 1) Event: A pattern of repeated code of conduct violations that other steps on the ladder have failed to resolve, or a violation so serious that the Community Moderators determine there is no way to keep the community safe with this person as a member. + 2) Consequence: Access to all community spaces, tools, and communication channels is removed. In general, permanent bans should be rarely used, should have strong reasoning behind them, and should only be resorted to if working through other remedies has failed to change the behavior. + 3) Repair: There is no possible repair in cases of this severity. + +This enforcement ladder is intended as a guideline. It does not limit the ability of Community Managers to use their discretion and judgment, in keeping with the best interests of our community. + + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public or other spaces. Examples of representing our community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event. + + +## Attribution + +This Code of Conduct is adapted from the Contributor Covenant, version 3.0, permanently available at [https://www.contributor-covenant.org/version/3/0/](https://www.contributor-covenant.org/version/3/0/). + +Contributor Covenant is stewarded by the Organization for Ethical Source and licensed under CC BY-SA 4.0. To view a copy of this license, visit [https://creativecommons.org/licenses/by-sa/4.0/](https://creativecommons.org/licenses/by-sa/4.0/) + +For answers to common questions about Contributor Covenant, see the FAQ at [https://www.contributor-covenant.org/faq](https://www.contributor-covenant.org/faq). Translations are provided at [https://www.contributor-covenant.org/translations](https://www.contributor-covenant.org/translations). Additional enforcement and community guideline resources can be found at [https://www.contributor-covenant.org/resources](https://www.contributor-covenant.org/resources). The enforcement ladder was inspired by the work of [Mozilla’s code of conduct team](https://github.com/mozilla/inclusion). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..e668708 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,11 @@ +# Contributing + +Contributions are welcome and appreciated. + +- **Report bugs and request features** in [Issues](../../issues) +- **Submit pull requests** to fix bugs or add new features +- Commit messages must conform to the [Conventional Commits](https://www.conventionalcommits.org/) specification +- **Improve documentation** directly via pull requests +- All contributors are expected to follow the [Code of Conduct](CODE_OF_CONDUCT.md) +- Security issues must be reported privately; see [SECURITY.md](SECURITY.md) +- By contributing, you agree that your contributions will be licensed under the project [licence](LICENSE) diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..7aa3ba7 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,17 @@ +# Security Policy + +## Supported Versions + +Only the latest release is supported. Security fixes are released as patch versions. + +## Reporting a Vulnerability + +**Do not open a public issue for security vulnerabilities.** + +[Report vulnerabilities privately](https://github.com/linuxmatters/jivefire/security/advisories/new). Include: + +- Steps to reproduce +- Affected versions +- Potential impact + +This project is maintained on a best-efforts basis. There are no guaranteed response times for security reports. diff --git a/SUPPORT.md b/SUPPORT.md new file mode 100644 index 0000000..e124b64 --- /dev/null +++ b/SUPPORT.md @@ -0,0 +1,34 @@ +# Support + +## Getting Help + +Before opening an issue, check the existing resources: + +- **[README](../../#readme)** for installation, usage, and configuration +- **[Open issues](../../issues)** for known bugs and planned features +- **[Closed issues](../../issues?q=is%3Aissue+is%3Aclosed)** for previously resolved problems +- **[Discussions](../../discussions)** for questions and community help, if enabled + +## Reporting Bugs + +Use the [bug report template](../../issues/new?template=bug_report.yml) and include: + +- Steps to reproduce +- Expected and actual behaviour +- Version and environment details + +To fix a bug yourself, see [CONTRIBUTING.md](CONTRIBUTING.md). + +## Requesting Features + +Use the [feature request template](../../issues/new?template=feature_request.yml) and describe: + +- The problem you are trying to solve +- Your proposed solution +- Your specific use case + +## What to Expect + +- This project is maintained on a best-efforts basis. +- There are no guaranteed response times or support SLAs. +- Security issues should be reported privately per [SECURITY.md](SECURITY.md). diff --git a/cubic.yaml b/cubic.yaml new file mode 100644 index 0000000..755be4f --- /dev/null +++ b/cubic.yaml @@ -0,0 +1,32 @@ +# yaml-language-server: $schema=https://cubic.dev/schema/cubic-repository-config.schema.json +version: 1 + +reviews: + enabled: true + sensitivity: medium + incremental_commits: true + check_drafts: false + architecture_diagrams: false + resolve_threads_when_addressed: true + custom_instructions: "" + ignore: + files: + - "dist/**" + - "build/**" + pr_titles: + - "wip:*" + pr_labels: + - "wontfix" + head_branches: [] + base_branches: [] + custom_rules: [] + +pr_descriptions: + cubic_review_link: false + generate: false + instructions: "" + +issues: + fix_commits_to_pr: false + fix_with_cubic_buttons: false + pr_comment_fixes: false From a9796682f1580efa1ce4c516d914a0a9d8f430cb Mon Sep 17 00:00:00 2001 From: Martin Wimpress Date: Thu, 19 Mar 2026 14:09:55 +0000 Subject: [PATCH 3/3] refactor: apply linting fixes across codebase - Align formatting, spacing, and naming conventions - Fix golangci-lint violations in audio, encoder, and renderer packages - Update build configuration and CI workflow - Add .golangci.yml for linter standardisation Signed-off-by: Martin Wimpress --- .github/workflows/release.yml | 6 +- .gitignore | 2 +- .golangci.yml | 67 ++++++++++++++ cmd/bench-yuv/main.go | 52 ++++++----- cmd/jivefire/main.go | 13 +-- flake.nix | 5 + internal/audio/analyzer.go | 24 +++-- internal/audio/analyzer_test.go | 2 +- internal/audio/decoder.go | 4 +- internal/audio/ffmpeg_decoder.go | 71 ++++++++------- internal/audio/fft.go | 13 +-- internal/audio/fft_test.go | 20 ++-- internal/audio/metadata.go | 12 +-- internal/audio/reader.go | 2 +- internal/audio/reader_test.go | 21 ++--- internal/audio/shared_buffer.go | 18 ++-- internal/audio/shared_buffer_test.go | 59 ++++++------ internal/cli/help.go | 8 +- internal/config/config_test.go | 4 +- internal/encoder/encoder.go | 121 +++++++++++-------------- internal/encoder/encoder_test.go | 6 +- internal/encoder/frame.go | 74 +++++++-------- internal/encoder/hwaccel.go | 6 +- internal/encoder/sws_benchmark_test.go | 114 +++++++++++------------ internal/renderer/frame.go | 16 ++-- internal/renderer/frame_bench_test.go | 4 +- internal/renderer/thumbnail.go | 4 +- internal/ui/preview.go | 26 ++---- internal/ui/progress.go | 77 +++++++--------- justfile | 8 ++ 30 files changed, 435 insertions(+), 424 deletions(-) create mode 100644 .golangci.yml diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 89a0cfa..e48e808 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -20,7 +20,7 @@ jobs: - name: Get version from tag id: get_version - run: echo "version=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT + run: echo "version=${GITHUB_REF#refs/tags/}" >> "$GITHUB_OUTPUT" - name: Generate changelog id: changelog @@ -31,7 +31,7 @@ jobs: # Generate changelog between tags if [ -n "$PREV_TAG" ]; then echo "## Changes since $PREV_TAG" > CHANGELOG.md - git log $PREV_TAG..HEAD --pretty=format:"* %s (%h)" >> CHANGELOG.md + git log "$PREV_TAG..HEAD" --pretty=format:"* %s (%h)" >> CHANGELOG.md else echo "## Initial Release" > CHANGELOG.md git log --pretty=format:"* %s (%h)" >> CHANGELOG.md @@ -112,7 +112,7 @@ jobs: - name: Get version from tag id: get_version - run: echo "version=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT + run: echo "version=${GITHUB_REF#refs/tags/}" >> "$GITHUB_OUTPUT" - name: Build binary run: | diff --git a/.gitignore b/.gitignore index 9433010..96dc80b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,3 @@ .direnv -jivefire +/jivefire testdata/ diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..482acf5 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,67 @@ +version: "2" +linters: + enable: + - bodyclose + - copyloopvar + - dupword + - errorlint + - gocritic + - gosec + - misspell + - modernize + - noctx + - revive + - staticcheck + - unconvert + - unparam + - usestdlibvars + - wastedassign + settings: + gosec: + excludes: + - G306 + govet: + enable-all: true + disable: + - fieldalignment + - shadow + revive: + rules: + - name: blank-imports + - name: context-as-argument + - name: dot-imports + - name: error-return + - name: error-strings + - name: error-naming + - name: exported + - name: increment-decrement + - name: var-naming + - name: range + - name: receiver-naming + - name: time-naming + - name: unexported-return + - name: indent-error-flow + - name: errorf + - name: empty-block + - name: superfluous-else + - name: unreachable-code + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + enable: + - gofumpt + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/cmd/bench-yuv/main.go b/cmd/bench-yuv/main.go index bb9e154..12de939 100644 --- a/cmd/bench-yuv/main.go +++ b/cmd/bench-yuv/main.go @@ -36,27 +36,27 @@ const ( ) func rgbToY(r, g, b int32) uint8 { - return uint8((yR*r + yG*g + yB*b + 1<<15) >> 16) + return uint8((yR*r + yG*g + yB*b + 1<<15) >> 16) //nolint:gosec // result is clamped to 0-255 } func rgbToCb(r, g, b int32) uint8 { cb := cbR*r + cbG*g + cbB*b + 257<<15 - if uint32(cb)&0xff000000 == 0 { + if uint32(cb)&0xff000000 == 0 { //nolint:gosec // intentional bit manipulation cb >>= 16 } else { cb = ^(cb >> 31) } - return uint8(cb) + return uint8(cb) //nolint:gosec // value is clamped by branch above } func rgbToCr(r, g, b int32) uint8 { cr := crR*r + crG*g + crB*b + 257<<15 - if uint32(cr)&0xff000000 == 0 { + if uint32(cr)&0xff000000 == 0 { //nolint:gosec // intentional bit manipulation cr >>= 16 } else { cr = ^(cr >> 31) } - return uint8(cr) + return uint8(cr) //nolint:gosec // value is clamped by branch above } func parallelRows(height int, fn func(startY, endY int)) { @@ -70,7 +70,7 @@ func parallelRows(height int, fn func(startY, endY int)) { var wg sync.WaitGroup wg.Add(numCPU) - for worker := 0; worker < numCPU; worker++ { + for worker := range numCPU { startY := worker * rowsPerWorker endY := startY + rowsPerWorker if worker == numCPU-1 { @@ -91,9 +91,9 @@ func convertRGBToYUVGo(rgbData []byte, yuvFrame *ffmpeg.AVFrame, width, height i uPlane := yuvFrame.Data().Get(1) vPlane := yuvFrame.Data().Get(2) - yLinesize := int(yuvFrame.Linesize().Get(0)) - uLinesize := int(yuvFrame.Linesize().Get(1)) - vLinesize := int(yuvFrame.Linesize().Get(2)) + yLinesize := yuvFrame.Linesize().Get(0) + uLinesize := yuvFrame.Linesize().Get(1) + vLinesize := yuvFrame.Linesize().Get(2) parallelRows(height, func(startY, endY int) { evenStart := startY @@ -103,13 +103,13 @@ func convertRGBToYUVGo(rgbData []byte, yuvFrame *ffmpeg.AVFrame, width, height i // Process even rows: Y + UV for y := evenStart; y < endY; y += 2 { - yPtr := unsafe.Add(unsafe.Pointer(yPlane), y*yLinesize) + yPtr := unsafe.Add(yPlane, y*yLinesize) uvY := y >> 1 - uRowPtr := unsafe.Add(unsafe.Pointer(uPlane), uvY*uLinesize) - vRowPtr := unsafe.Add(unsafe.Pointer(vPlane), uvY*vLinesize) + uRowPtr := unsafe.Add(uPlane, uvY*uLinesize) + vRowPtr := unsafe.Add(vPlane, uvY*vLinesize) rgbIdx := y * width * 3 - for x := 0; x < width; x++ { + for x := range width { r := int32(rgbData[rgbIdx]) g := int32(rgbData[rgbIdx+1]) b := int32(rgbData[rgbIdx+2]) @@ -131,10 +131,10 @@ func convertRGBToYUVGo(rgbData []byte, yuvFrame *ffmpeg.AVFrame, width, height i oddStart++ } for y := oddStart; y < endY; y += 2 { - yPtr := unsafe.Add(unsafe.Pointer(yPlane), y*yLinesize) + yPtr := unsafe.Add(yPlane, y*yLinesize) rgbIdx := y * width * 3 - for x := 0; x < width; x++ { + for x := range width { r := int32(rgbData[rgbIdx]) g := int32(rgbData[rgbIdx+1]) b := int32(rgbData[rgbIdx+2]) @@ -151,15 +151,15 @@ func convertSwscale(rgbData []byte, yuvFrame *ffmpeg.AVFrame, swsCtx *ffmpeg.Sws srcLinesize := srcFrame.Linesize().Get(0) srcData := srcFrame.Data().Get(0) - for y := 0; y < height; y++ { - srcOffset := y * int(srcLinesize) + for y := range height { + srcOffset := y * srcLinesize rgbOffset := y * width * 3 for x := 0; x < width*3; x++ { - *(*uint8)(unsafe.Add(unsafe.Pointer(srcData), srcOffset+x)) = rgbData[rgbOffset+x] + *(*uint8)(unsafe.Add(srcData, srcOffset+x)) = rgbData[rgbOffset+x] } } - ffmpeg.SwsScaleFrame(swsCtx, yuvFrame, srcFrame) + _, _ = ffmpeg.SwsScaleFrame(swsCtx, yuvFrame, srcFrame) } func main() { @@ -167,6 +167,11 @@ func main() { impl := flag.String("impl", "go", "implementation: go or swscale") flag.Parse() + if *impl != "go" && *impl != "swscale" { + fmt.Fprintf(os.Stderr, "Unknown implementation: %s (use 'go' or 'swscale')\n", *impl) + os.Exit(1) + } + // Create test RGB data rgbSize := width * height * 3 rgbData := make([]byte, rgbSize) @@ -181,7 +186,7 @@ func main() { yuvFrame.SetWidth(width) yuvFrame.SetHeight(height) yuvFrame.SetFormat(int(ffmpeg.AVPixFmtYuv420P)) - ffmpeg.AVFrameGetBuffer(yuvFrame, 0) + _, _ = ffmpeg.AVFrameGetBuffer(yuvFrame, 0) defer ffmpeg.AVFrameFree(&yuvFrame) switch *impl { @@ -199,21 +204,18 @@ func main() { swsCtx.SetDstH(height) swsCtx.SetDstFormat(int(ffmpeg.AVPixFmtYuv420P)) swsCtx.SetFlags(uint(ffmpeg.SwsBilinear)) - ffmpeg.SwsInitContext(swsCtx, nil, nil) + _, _ = ffmpeg.SwsInitContext(swsCtx, nil, nil) defer ffmpeg.SwsFreecontext(swsCtx) srcFrame := ffmpeg.AVFrameAlloc() srcFrame.SetWidth(width) srcFrame.SetHeight(height) srcFrame.SetFormat(int(ffmpeg.AVPixFmtRgb24)) - ffmpeg.AVFrameGetBuffer(srcFrame, 0) + _, _ = ffmpeg.AVFrameGetBuffer(srcFrame, 0) defer ffmpeg.AVFrameFree(&srcFrame) for i := 0; i < *iterations; i++ { convertSwscale(rgbData, yuvFrame, swsCtx, srcFrame, width, height) } - default: - fmt.Fprintf(os.Stderr, "Unknown implementation: %s (use 'go' or 'swscale')\n", *impl) - os.Exit(1) } } diff --git a/cmd/jivefire/main.go b/cmd/jivefire/main.go index 6af4bcc..94f1b1d 100644 --- a/cmd/jivefire/main.go +++ b/cmd/jivefire/main.go @@ -1,6 +1,7 @@ package main import ( + "errors" "fmt" "image" "io" @@ -72,7 +73,7 @@ func main() { // Show help if no arguments provided if CLI.Input == "" && CLI.Output == "" { - ctx.PrintUsage(true) + _ = ctx.PrintUsage(true) os.Exit(0) } @@ -201,7 +202,7 @@ func generateVideo(inputFile string, outputFile string, channels int, noPreview thumbnailDuration := time.Since(thumbnailStartTime) // Get audio metadata upfront for Pass 1 progress estimation - metadata, err := audio.GetAudioMetadata(inputFile) + metadata, err := audio.GetMetadata(inputFile) if err != nil { cli.PrintError(fmt.Sprintf("reading audio metadata: %v", err)) os.Exit(1) @@ -217,7 +218,7 @@ func generateVideo(inputFile string, outputFile string, channels int, noPreview p := tea.NewProgram(model, tea.WithAltScreen()) // Shared state between goroutines - var profile *audio.AudioProfile + var profile *audio.Profile var analysisErr error // Run both passes in a single goroutine @@ -279,7 +280,7 @@ func generateVideo(inputFile string, outputFile string, channels int, noPreview } } -func runPass2(p *tea.Program, inputFile string, outputFile string, channels int, noPreview bool, hwAccel encoder.HWAccelType, runtimeConfig *config.RuntimeConfig, profile *audio.AudioProfile, thumbnailDuration time.Duration, overallStartTime time.Time) { +func runPass2(p *tea.Program, inputFile string, outputFile string, channels int, noPreview bool, hwAccel encoder.HWAccelType, runtimeConfig *config.RuntimeConfig, profile *audio.Profile, thumbnailDuration time.Duration, overallStartTime time.Time) { // Open streaming reader for Pass 2 reader, err := audio.NewStreamingReader(inputFile) if err != nil { @@ -386,7 +387,7 @@ func runPass2(p *tea.Program, inputFile string, outputFile string, channels int, for len(initialSamples) < config.FFTSize { chunk, err := reader.ReadChunk(config.FFTSize - len(initialSamples)) if err != nil { - if err == io.EOF { + if errors.Is(err, io.EOF) { break // Use what we have } cli.PrintError(fmt.Sprintf("error reading initial audio chunk: %v", err)) @@ -559,7 +560,7 @@ func runPass2(p *tea.Program, inputFile string, outputFile string, channels int, for len(newSamples) < samplesPerFrame { chunk, err := reader.ReadChunk(samplesPerFrame - len(newSamples)) if err != nil { - if err == io.EOF { + if errors.Is(err, io.EOF) { // If we got no new samples at all, we're done if len(newSamples) == 0 { // Break out of the frame loop - no more audio diff --git a/flake.nix b/flake.nix index d6cc8c8..62e91fe 100644 --- a/flake.nix +++ b/flake.nix @@ -23,11 +23,16 @@ packages = with pkgs; [ + actionlint + cosign curl ffmpeg-full gnugrep gcc go_1_26 + gocyclo + golangci-lint + ineffassign just vhs ] diff --git a/internal/audio/analyzer.go b/internal/audio/analyzer.go index 3115df3..43807ca 100644 --- a/internal/audio/analyzer.go +++ b/internal/audio/analyzer.go @@ -1,6 +1,7 @@ package audio import ( + "errors" "fmt" "io" "math" @@ -21,8 +22,8 @@ type FrameAnalysis struct { BarMagnitudes [config.NumBars]float64 } -// AudioProfile holds complete audio analysis results -type AudioProfile struct { +// Profile holds complete audio analysis results. +type Profile struct { // Total number of frames in audio NumFrames int @@ -46,8 +47,7 @@ type AudioProfile struct { type ProgressCallback func(frame, totalFrames int, currentRMS, currentPeak float64, barHeights []float64, duration time.Duration) // AnalyzeAudio performs Pass 1: stream through audio and collect statistics -func AnalyzeAudio(filename string, progressCb ProgressCallback) (*AudioProfile, error) { - +func AnalyzeAudio(filename string, progressCb ProgressCallback) (*Profile, error) { // Open streaming reader reader, err := NewStreamingReader(filename) if err != nil { @@ -55,7 +55,7 @@ func AnalyzeAudio(filename string, progressCb ProgressCallback) (*AudioProfile, } defer reader.Close() - profile := &AudioProfile{ + profile := &Profile{ NumFrames: 0, // Will be set after we count actual samples Frames: make([]FrameAnalysis, 0), // Will grow as we read SampleRate: reader.SampleRate(), @@ -81,7 +81,7 @@ func AnalyzeAudio(filename string, progressCb ProgressCallback) (*AudioProfile, for len(initialSamples) < config.FFTSize { chunk, err := reader.ReadChunk(config.FFTSize - len(initialSamples)) if err != nil { - if err == io.EOF { + if errors.Is(err, io.EOF) { break // Use what we have } return nil, fmt.Errorf("error reading initial chunk: %w", err) @@ -119,7 +119,7 @@ func AnalyzeAudio(filename string, progressCb ProgressCallback) (*AudioProfile, if progressCb != nil && frameNum%3 == 0 { // Convert bar magnitudes to slice for progress update barHeights := make([]float64, config.NumBars) - for i := 0; i < config.NumBars; i++ { + for i := range config.NumBars { barHeights[i] = analysis.BarMagnitudes[i] } @@ -135,13 +135,13 @@ func AnalyzeAudio(filename string, progressCb ProgressCallback) (*AudioProfile, for len(newSamples) < samplesPerFrame { chunk, err := reader.ReadChunk(samplesPerFrame - len(newSamples)) if err != nil { - if err == io.EOF { + if errors.Is(err, io.EOF) { // If we got some samples, use them; otherwise we're done if len(newSamples) == 0 { // Send final progress update if progressCb != nil { barHeights := make([]float64, config.NumBars) - for i := 0; i < config.NumBars; i++ { + for i := range config.NumBars { barHeights[i] = analysis.BarMagnitudes[i] } elapsed := time.Since(startTime) @@ -215,12 +215,10 @@ func analyzeFrame(coeffs []complex128, audioChunk []float64) FrameAnalysis { maxFreqBin := halfSize binsPerBar := maxFreqBin / config.NumBars - for bar := 0; bar < config.NumBars; bar++ { + for bar := range config.NumBars { start := bar * binsPerBar end := start + binsPerBar - if end > maxFreqBin { - end = maxFreqBin - } + end = min(end, maxFreqBin) var sum float64 for i := start; i < end; i++ { diff --git a/internal/audio/analyzer_test.go b/internal/audio/analyzer_test.go index 8220214..0c25d9c 100644 --- a/internal/audio/analyzer_test.go +++ b/internal/audio/analyzer_test.go @@ -84,7 +84,7 @@ func TestAnalyzeFrameStatistics(t *testing.T) { } // Check bar magnitudes - for bar := 0; bar < config.NumBars; bar++ { + for bar := range config.NumBars { if frame.BarMagnitudes[bar] < 0 { t.Errorf("Frame %d, Bar %d: negative magnitude: %.6f", i, bar, frame.BarMagnitudes[bar]) } diff --git a/internal/audio/decoder.go b/internal/audio/decoder.go index 1004f61..1148889 100644 --- a/internal/audio/decoder.go +++ b/internal/audio/decoder.go @@ -2,8 +2,8 @@ package audio import "io" -// AudioDecoder defines the interface for all audio format decoders -type AudioDecoder interface { +// Decoder defines the interface for all audio format decoders +type Decoder interface { // ReadChunk reads the next chunk of samples as float64 // Returns nil when EOF is reached ReadChunk(numSamples int) ([]float64, error) diff --git a/internal/audio/ffmpeg_decoder.go b/internal/audio/ffmpeg_decoder.go index 71abce6..3c9df5f 100644 --- a/internal/audio/ffmpeg_decoder.go +++ b/internal/audio/ffmpeg_decoder.go @@ -9,7 +9,7 @@ import ( ffmpeg "github.com/linuxmatters/ffmpeg-statigo" ) -// FFmpegDecoder implements AudioDecoder using FFmpeg's libavformat/libavcodec. +// FFmpegDecoder implements Decoder using FFmpeg's libavformat/libavcodec. // This provides support for any audio format FFmpeg can decode. type FFmpegDecoder struct { formatCtx *ffmpeg.AVFormatContext @@ -69,7 +69,7 @@ func NewFFmpegDecoder(filename string) (*FFmpegDecoder, error) { return nil, fmt.Errorf("no audio stream found in file") } - audioStream := streams.Get(uintptr(d.streamIndex)) + audioStream := streams.Get(uintptr(d.streamIndex)) //nolint:gosec // stream index is non-negative // Find decoder decoder := ffmpeg.AVCodecFindDecoder(audioStream.Codecpar().CodecId()) @@ -182,7 +182,7 @@ func (d *FFmpegDecoder) ReadChunk(numSamples int) ([]float64, error) { } // Send packet to decoder - ret, err = ffmpeg.AVCodecSendPacket(d.codecCtx, d.packet) + _, err = ffmpeg.AVCodecSendPacket(d.codecCtx, d.packet) ffmpeg.AVPacketUnref(d.packet) if err != nil { return nil, fmt.Errorf("failed to send packet to decoder: %w", err) @@ -190,7 +190,7 @@ func (d *FFmpegDecoder) ReadChunk(numSamples int) ([]float64, error) { // Receive decoded frames for { - ret, err = ffmpeg.AVCodecReceiveFrame(d.codecCtx, d.frame) + _, err = ffmpeg.AVCodecReceiveFrame(d.codecCtx, d.frame) if err != nil { if errors.Is(err, ffmpeg.AVErrorEOF) || errors.Is(err, ffmpeg.EAgain) { break @@ -228,7 +228,8 @@ func (d *FFmpegDecoder) extractSamples() ([]float64, error) { // Determine if format is planar (planar formats start at 5) isPlanar := sampleFormat >= 5 - if isPlanar && channels == 2 { + switch { + case isPlanar && channels == 2: // Planar stereo - separate buffers for left and right leftPtr := d.frame.Data().Get(0) rightPtr := d.frame.Data().Get(1) @@ -238,18 +239,18 @@ func (d *FFmpegDecoder) extractSamples() ([]float64, error) { switch sampleFormat { case 6: // AVSampleFmtS16P - planar 16-bit signed - leftSlice := (*[1 << 30]byte)(unsafe.Pointer(leftPtr))[: nbSamples*2 : nbSamples*2] - rightSlice := (*[1 << 30]byte)(unsafe.Pointer(rightPtr))[: nbSamples*2 : nbSamples*2] - for i := 0; i < nbSamples; i++ { + leftSlice := (*[1 << 30]byte)(leftPtr)[: nbSamples*2 : nbSamples*2] + rightSlice := (*[1 << 30]byte)(rightPtr)[: nbSamples*2 : nbSamples*2] + for i := range nbSamples { leftVal := int16(leftSlice[i*2]) | int16(leftSlice[i*2+1])<<8 rightVal := int16(rightSlice[i*2]) | int16(rightSlice[i*2+1])<<8 samples[i] = (float64(leftVal) + float64(rightVal)) / (2 * 32768.0) } case 7: // AVSampleFmtS32P - planar 32-bit signed (FLAC) - leftSlice := (*[1 << 30]byte)(unsafe.Pointer(leftPtr))[: nbSamples*4 : nbSamples*4] - rightSlice := (*[1 << 30]byte)(unsafe.Pointer(rightPtr))[: nbSamples*4 : nbSamples*4] - for i := 0; i < nbSamples; i++ { + leftSlice := (*[1 << 30]byte)(leftPtr)[: nbSamples*4 : nbSamples*4] + rightSlice := (*[1 << 30]byte)(rightPtr)[: nbSamples*4 : nbSamples*4] + for i := range nbSamples { leftVal := int32(leftSlice[i*4]) | int32(leftSlice[i*4+1])<<8 | int32(leftSlice[i*4+2])<<16 | @@ -262,9 +263,9 @@ func (d *FFmpegDecoder) extractSamples() ([]float64, error) { } case 8: // AVSampleFmtFltp - planar float - leftSlice := (*[1 << 30]byte)(unsafe.Pointer(leftPtr))[: nbSamples*4 : nbSamples*4] - rightSlice := (*[1 << 30]byte)(unsafe.Pointer(rightPtr))[: nbSamples*4 : nbSamples*4] - for i := 0; i < nbSamples; i++ { + leftSlice := (*[1 << 30]byte)(leftPtr)[: nbSamples*4 : nbSamples*4] + rightSlice := (*[1 << 30]byte)(rightPtr)[: nbSamples*4 : nbSamples*4] + for i := range nbSamples { leftBits := uint32(leftSlice[i*4]) | uint32(leftSlice[i*4+1])<<8 | uint32(leftSlice[i*4+2])<<16 | @@ -283,7 +284,7 @@ func (d *FFmpegDecoder) extractSamples() ([]float64, error) { default: return nil, fmt.Errorf("unsupported planar sample format: %d", sampleFormat) } - } else if isPlanar && channels == 1 { + case isPlanar && channels == 1: // Planar mono - just one buffer dataPtr := d.frame.Data().Get(0) if dataPtr == nil { @@ -292,15 +293,15 @@ func (d *FFmpegDecoder) extractSamples() ([]float64, error) { switch sampleFormat { case 6: // AVSampleFmtS16P - dataSlice := (*[1 << 30]byte)(unsafe.Pointer(dataPtr))[: nbSamples*2 : nbSamples*2] - for i := 0; i < nbSamples; i++ { + dataSlice := (*[1 << 30]byte)(dataPtr)[: nbSamples*2 : nbSamples*2] + for i := range nbSamples { val := int16(dataSlice[i*2]) | int16(dataSlice[i*2+1])<<8 samples[i] = float64(val) / 32768.0 } case 7: // AVSampleFmtS32P - dataSlice := (*[1 << 30]byte)(unsafe.Pointer(dataPtr))[: nbSamples*4 : nbSamples*4] - for i := 0; i < nbSamples; i++ { + dataSlice := (*[1 << 30]byte)(dataPtr)[: nbSamples*4 : nbSamples*4] + for i := range nbSamples { val := int32(dataSlice[i*4]) | int32(dataSlice[i*4+1])<<8 | int32(dataSlice[i*4+2])<<16 | @@ -309,8 +310,8 @@ func (d *FFmpegDecoder) extractSamples() ([]float64, error) { } case 8: // AVSampleFmtFltp - dataSlice := (*[1 << 30]byte)(unsafe.Pointer(dataPtr))[: nbSamples*4 : nbSamples*4] - for i := 0; i < nbSamples; i++ { + dataSlice := (*[1 << 30]byte)(dataPtr)[: nbSamples*4 : nbSamples*4] + for i := range nbSamples { bits := uint32(dataSlice[i*4]) | uint32(dataSlice[i*4+1])<<8 | uint32(dataSlice[i*4+2])<<16 | @@ -321,7 +322,7 @@ func (d *FFmpegDecoder) extractSamples() ([]float64, error) { default: return nil, fmt.Errorf("unsupported planar mono format: %d", sampleFormat) } - } else { + default: // Interleaved formats dataPtr := d.frame.Data().Get(0) if dataPtr == nil { @@ -331,15 +332,15 @@ func (d *FFmpegDecoder) extractSamples() ([]float64, error) { switch sampleFormat { case 1: // AVSampleFmtS16 - interleaved 16-bit signed if channels == 1 { - dataSlice := (*[1 << 30]byte)(unsafe.Pointer(dataPtr))[: nbSamples*2 : nbSamples*2] - for i := 0; i < nbSamples; i++ { + dataSlice := (*[1 << 30]byte)(dataPtr)[: nbSamples*2 : nbSamples*2] + for i := range nbSamples { val := int16(dataSlice[i*2]) | int16(dataSlice[i*2+1])<<8 samples[i] = float64(val) / 32768.0 } } else { // Stereo interleaved: L R L R ... - dataSlice := (*[1 << 30]byte)(unsafe.Pointer(dataPtr))[: nbSamples*4 : nbSamples*4] - for i := 0; i < nbSamples; i++ { + dataSlice := (*[1 << 30]byte)(dataPtr)[: nbSamples*4 : nbSamples*4] + for i := range nbSamples { leftVal := int16(dataSlice[i*4]) | int16(dataSlice[i*4+1])<<8 rightVal := int16(dataSlice[i*4+2]) | int16(dataSlice[i*4+3])<<8 samples[i] = (float64(leftVal) + float64(rightVal)) / (2 * 32768.0) @@ -348,8 +349,8 @@ func (d *FFmpegDecoder) extractSamples() ([]float64, error) { case 2: // AVSampleFmtS32 - interleaved 32-bit signed (FLAC) if channels == 1 { - dataSlice := (*[1 << 30]byte)(unsafe.Pointer(dataPtr))[: nbSamples*4 : nbSamples*4] - for i := 0; i < nbSamples; i++ { + dataSlice := (*[1 << 30]byte)(dataPtr)[: nbSamples*4 : nbSamples*4] + for i := range nbSamples { val := int32(dataSlice[i*4]) | int32(dataSlice[i*4+1])<<8 | int32(dataSlice[i*4+2])<<16 | @@ -358,8 +359,8 @@ func (d *FFmpegDecoder) extractSamples() ([]float64, error) { } } else { // Stereo interleaved - dataSlice := (*[1 << 30]byte)(unsafe.Pointer(dataPtr))[: nbSamples*8 : nbSamples*8] - for i := 0; i < nbSamples; i++ { + dataSlice := (*[1 << 30]byte)(dataPtr)[: nbSamples*8 : nbSamples*8] + for i := range nbSamples { leftVal := int32(dataSlice[i*8]) | int32(dataSlice[i*8+1])<<8 | int32(dataSlice[i*8+2])<<16 | @@ -374,8 +375,8 @@ func (d *FFmpegDecoder) extractSamples() ([]float64, error) { case 3: // AVSampleFmtFlt - interleaved float if channels == 1 { - dataSlice := (*[1 << 30]byte)(unsafe.Pointer(dataPtr))[: nbSamples*4 : nbSamples*4] - for i := 0; i < nbSamples; i++ { + dataSlice := (*[1 << 30]byte)(dataPtr)[: nbSamples*4 : nbSamples*4] + for i := range nbSamples { bits := uint32(dataSlice[i*4]) | uint32(dataSlice[i*4+1])<<8 | uint32(dataSlice[i*4+2])<<16 | @@ -384,8 +385,8 @@ func (d *FFmpegDecoder) extractSamples() ([]float64, error) { } } else { // Stereo interleaved - dataSlice := (*[1 << 30]byte)(unsafe.Pointer(dataPtr))[: nbSamples*8 : nbSamples*8] - for i := 0; i < nbSamples; i++ { + dataSlice := (*[1 << 30]byte)(dataPtr)[: nbSamples*8 : nbSamples*8] + for i := range nbSamples { leftBits := uint32(dataSlice[i*8]) | uint32(dataSlice[i*8+1])<<8 | uint32(dataSlice[i*8+2])<<16 | @@ -443,7 +444,7 @@ func (d *FFmpegDecoder) SeekToSample(samplePos int64) error { d.sampleBuffer = d.sampleBuffer[:0] // Convert sample position to timestamp - stream := d.formatCtx.Streams().Get(uintptr(d.streamIndex)) + stream := d.formatCtx.Streams().Get(uintptr(d.streamIndex)) //nolint:gosec // stream index is non-negative timeBase := stream.TimeBase() // Calculate timestamp: samplePos / sampleRate * timeBase.Den / timeBase.Num diff --git a/internal/audio/fft.go b/internal/audio/fft.go index 3a64f84..294821e 100644 --- a/internal/audio/fft.go +++ b/internal/audio/fft.go @@ -33,12 +33,10 @@ func BinFFT(coeffs []complex128, sensitivity float64, baseScale float64, result binsPerBar := maxFreqBin / config.NumBars - for bar := 0; bar < config.NumBars; bar++ { + for bar := range config.NumBars { start := bar * binsPerBar end := start + binsPerBar - if end > maxFreqBin { - end = maxFreqBin - } + end = min(end, maxFreqBin) // Average magnitude in this range var sum float64 @@ -104,7 +102,7 @@ func NewProcessor() *Processor { // Pre-compute Hanning window coefficients once window := make([]float64, config.FFTSize) n := float64(config.FFTSize - 1) - for i := 0; i < config.FFTSize; i++ { + for i := range config.FFTSize { window[i] = 0.5 * (1 - math.Cos(2*math.Pi*float64(i)/n)) } return &Processor{ @@ -125,12 +123,11 @@ func (p *Processor) ProcessChunk(samples []float64) []complex128 { } // Apply Hanning window using pre-computed coefficients (faster than trig per sample) - for i := 0; i < config.FFTSize; i++ { + for i := range config.FFTSize { p.windowedBuffer[i] = chunk[i] * p.hanningWindow[i] } - // Convert to complex128 for gofft - // gofft works in-place, modifying the input array + // Convert to complex128 for gofft which works in-place, modifying the input array fftInput := gofft.Float64ToComplex128Array(p.windowedBuffer) // Compute FFT in-place diff --git a/internal/audio/fft_test.go b/internal/audio/fft_test.go index c17f26a..5d61ab0 100644 --- a/internal/audio/fft_test.go +++ b/internal/audio/fft_test.go @@ -31,7 +31,7 @@ func TestBinFFT_KnownSineWave(t *testing.T) { // Generate 1 second of 440 Hz sine wave at 44.1 kHz numSamples := int(float64(sampleRate) * duration) sine := make([]float64, numSamples) - for i := 0; i < numSamples; i++ { + for i := range numSamples { t := float64(i) / float64(sampleRate) sine[i] = math.Sin(2 * math.Pi * frequency * t) } @@ -200,7 +200,7 @@ func TestBinFFT_EnergyDistribution(t *testing.T) { // Create a broadband signal (white noise-ish via multiple frequencies) signal := make([]float64, fftSize) - for i := 0; i < fftSize; i++ { + for i := range fftSize { signal[i] = 0.1 * (math.Sin(2*math.Pi*100*float64(i)/float64(fftSize)) + math.Sin(2*math.Pi*500*float64(i)/float64(fftSize)) + math.Sin(2*math.Pi*1000*float64(i)/float64(fftSize))) @@ -300,7 +300,7 @@ func TestRearrangeFrequenciesCenterOut_Symmetry(t *testing.T) { // Create input with distinct values (0-31 ascending) input := make([]float64, numBars) - for i := 0; i < numBars; i++ { + for i := range numBars { input[i] = float64(i) } @@ -308,7 +308,7 @@ func TestRearrangeFrequenciesCenterOut_Symmetry(t *testing.T) { RearrangeFrequenciesCenterOut(input, result) // Verify perfect symmetry around center - for i := 0; i < center; i++ { + for i := range center { leftIdx := center - 1 - i rightIdx := center + i @@ -334,7 +334,7 @@ func TestRearrangeFrequenciesCenterOut_ExpectedMapping(t *testing.T) { // Create input representing increasing frequency (bar 0 = lowest, 31 = highest) // After rearrangement: lowest frequencies should be at center, highest at edges input := make([]float64, numBars) - for i := 0; i < numBars; i++ { + for i := range numBars { input[i] = float64(i) } @@ -395,7 +395,7 @@ func TestRearrangeFrequenciesCenterOut_EdgeCases(t *testing.T) { // Verify symmetry for this case center := tc.size / 2 - for i := 0; i < center; i++ { + for i := range center { leftIdx := center - 1 - i rightIdx := center + i @@ -422,7 +422,7 @@ func TestRearrangeFrequenciesCenterOut_SmallInput(t *testing.T) { // Output should be symmetric: // - Bars 0-1 mirrored from center going left (1 and 2) // - Bars 2-3 mirrored from center going right (1 and 2) - // Expected result: [input[1], input[0], input[0], input[1]] = [2, 1, 1, 2] + // Expected values: [input[1], input[0], then input[0], input[1]] = [2, 1, 1, 2] expected := []float64{2, 1, 1, 2} for i, v := range result { @@ -498,7 +498,7 @@ func TestApplyHanning_KnownValues(t *testing.T) { } // Verify symmetry around center - for i := 0; i < 4; i++ { + for i := range 4 { if math.Abs(windowed[i]-windowed[7-i]) > epsilon { t.Errorf("Symmetry violation at i=%d: windowed[%d]=%.10f != windowed[%d]=%.10f", i, i, windowed[i], 7-i, windowed[7-i]) @@ -616,7 +616,7 @@ func BenchmarkHanningPrecomputed(b *testing.B) { // Pre-compute Hanning window (same as NewProcessor) window := make([]float64, 2048) n := float64(2048 - 1) - for i := 0; i < 2048; i++ { + for i := range 2048 { window[i] = 0.5 * (1 - math.Cos(2*math.Pi*float64(i)/n)) } output := make([]float64, 2048) @@ -631,7 +631,7 @@ func BenchmarkHanningPrecomputed(b *testing.B) { for i := 0; i < b.N; i++ { // Just multiply - no trig, no allocation - for j := 0; j < 2048; j++ { + for j := range 2048 { output[j] = samples[j] * window[j] } } diff --git a/internal/audio/metadata.go b/internal/audio/metadata.go index 59e0baa..4dfdc44 100644 --- a/internal/audio/metadata.go +++ b/internal/audio/metadata.go @@ -6,16 +6,16 @@ import ( ffmpeg "github.com/linuxmatters/ffmpeg-statigo" ) -// AudioMetadata holds information about an audio file -type AudioMetadata struct { +// Metadata holds information about an audio file +type Metadata struct { SampleRate int Channels int NumSamples int64 Duration float64 // in seconds } -// GetAudioMetadata uses ffmpeg to extract accurate audio file metadata -func GetAudioMetadata(filename string) (*AudioMetadata, error) { +// GetMetadata uses ffmpeg to extract accurate audio file metadata +func GetMetadata(filename string) (*Metadata, error) { // Open audio file var inputCtx *ffmpeg.AVFormatContext audioPath := ffmpeg.ToCStr(filename) @@ -56,7 +56,7 @@ func GetAudioMetadata(filename string) (*AudioMetadata, error) { codecpar := audioStream.Codecpar() // Extract metadata - sampleRate := int(codecpar.SampleRate()) + sampleRate := codecpar.SampleRate() channels := codecpar.ChLayout().NbChannels() // Calculate duration and total samples @@ -64,7 +64,7 @@ func GetAudioMetadata(filename string) (*AudioMetadata, error) { duration := float64(audioStream.Duration()) * float64(audioStream.TimeBase().Num()) / float64(audioStream.TimeBase().Den()) numSamples := int64(duration * float64(sampleRate)) - return &AudioMetadata{ + return &Metadata{ SampleRate: sampleRate, Channels: channels, NumSamples: numSamples, diff --git a/internal/audio/reader.go b/internal/audio/reader.go index a7814b9..a882f3c 100644 --- a/internal/audio/reader.go +++ b/internal/audio/reader.go @@ -6,7 +6,7 @@ import ( // StreamingReader provides chunk-based audio reading for multiple formats type StreamingReader struct { - decoder AudioDecoder + decoder Decoder } // NewStreamingReader creates a streaming audio reader for the given file. diff --git a/internal/audio/reader_test.go b/internal/audio/reader_test.go index 0ccadef..78c6e9f 100644 --- a/internal/audio/reader_test.go +++ b/internal/audio/reader_test.go @@ -1,6 +1,7 @@ package audio import ( + "errors" "io" "testing" ) @@ -13,7 +14,7 @@ func TestNewStreamingReader(t *testing.T) { defer reader.Close() // Get metadata to verify file was opened correctly - metadata, err := GetAudioMetadata("../../testdata/LMP0.mp3") + metadata, err := GetMetadata("../../testdata/LMP0.mp3") if err != nil { t.Fatalf("Failed to get metadata: %v", err) } @@ -80,7 +81,7 @@ func TestStreamingReaderMultipleChunks(t *testing.T) { for { chunk, err := reader.ReadChunk(chunkSize) - if err == io.EOF { + if errors.Is(err, io.EOF) { break } if err != nil { @@ -115,7 +116,7 @@ func TestStreamingReaderEOF(t *testing.T) { defer reader.Close() // Get total sample count via metadata - metadata, err := GetAudioMetadata("../../testdata/LMP0.mp3") + metadata, err := GetMetadata("../../testdata/LMP0.mp3") if err != nil { t.Fatalf("Failed to get metadata: %v", err) } @@ -125,7 +126,7 @@ func TestStreamingReaderEOF(t *testing.T) { for { _, err := reader.ReadChunk(chunkSize) - if err == io.EOF { + if errors.Is(err, io.EOF) { // Expected EOF break } @@ -136,7 +137,7 @@ func TestStreamingReaderEOF(t *testing.T) { // Try reading again - should get EOF immediately _, err = reader.ReadChunk(chunkSize) - if err != io.EOF { + if !errors.Is(err, io.EOF) { t.Errorf("Expected EOF on second read past end, got: %v", err) } @@ -174,7 +175,7 @@ func TestStreamingReaderMultipleReads(t *testing.T) { chunkSize := 2048 for { chunk, err := reader1.ReadChunk(chunkSize) - if err == io.EOF { + if errors.Is(err, io.EOF) { break } if err != nil { @@ -194,7 +195,7 @@ func TestStreamingReaderMultipleReads(t *testing.T) { chunkSize2 := 4096 for { chunk, err := reader2.ReadChunk(chunkSize2) - if err == io.EOF { + if errors.Is(err, io.EOF) { break } if err != nil { @@ -210,11 +211,9 @@ func TestStreamingReaderMultipleReads(t *testing.T) { // Compare first 100 samples (should be identical) compareCount := 100 - if len(samples1) < compareCount { - compareCount = len(samples1) - } + compareCount = min(compareCount, len(samples1)) - for i := 0; i < compareCount; i++ { + for i := range compareCount { if samples1[i] != samples2[i] { t.Errorf("Sample %d mismatch: pass1=%f, pass2=%f", i, samples1[i], samples2[i]) } diff --git a/internal/audio/shared_buffer.go b/internal/audio/shared_buffer.go index 8b4317b..45793b6 100644 --- a/internal/audio/shared_buffer.go +++ b/internal/audio/shared_buffer.go @@ -81,10 +81,7 @@ func (b *SharedAudioBuffer) ReadForFFT(numSamples int) ([]float64, error) { } // Read up to numSamples - toRead := numSamples - if toRead > available { - toRead = available - } + toRead := min(numSamples, available) result := make([]float64, toRead) copy(result, b.samples[b.fftReadPos:b.fftReadPos+toRead]) @@ -107,7 +104,7 @@ func (b *SharedAudioBuffer) ReadForEncoder(numSamples int) ([]float32, error) { // If we have enough samples, return them if available >= numSamples { result := make([]float32, numSamples) - for i := 0; i < numSamples; i++ { + for i := range numSamples { result[i] = float32(b.samples[b.encoderReadPos+i]) } b.encoderReadPos += numSamples @@ -121,7 +118,7 @@ func (b *SharedAudioBuffer) ReadForEncoder(numSamples int) ([]float32, error) { } // Return remaining samples (partial frame) result := make([]float32, available) - for i := 0; i < available; i++ { + for i := range available { result[i] = float32(b.samples[b.encoderReadPos+i]) } b.encoderReadPos += available @@ -146,7 +143,7 @@ func (b *SharedAudioBuffer) ReadForEncoderNonBlocking(numSamples int) ([]float32 // If we have enough samples, return them if available >= numSamples { result := make([]float32, numSamples) - for i := 0; i < numSamples; i++ { + for i := range numSamples { result[i] = float32(b.samples[b.encoderReadPos+i]) } b.encoderReadPos += numSamples @@ -156,7 +153,7 @@ func (b *SharedAudioBuffer) ReadForEncoderNonBlocking(numSamples int) ([]float32 // Buffer closed - return whatever we have if b.closed && available > 0 { result := make([]float32, available) - for i := 0; i < available; i++ { + for i := range available { result[i] = float32(b.samples[b.encoderReadPos+i]) } b.encoderReadPos += available @@ -228,10 +225,7 @@ func (b *SharedAudioBuffer) CompactBuffer() { defer b.mu.Unlock() // Find the minimum read position (samples consumed by both) - minPos := b.fftReadPos - if b.encoderReadPos < minPos { - minPos = b.encoderReadPos - } + minPos := min(b.fftReadPos, b.encoderReadPos) if minPos == 0 { return // Nothing to compact diff --git a/internal/audio/shared_buffer_test.go b/internal/audio/shared_buffer_test.go index 4a598dc..d143a04 100644 --- a/internal/audio/shared_buffer_test.go +++ b/internal/audio/shared_buffer_test.go @@ -1,6 +1,7 @@ package audio import ( + "errors" "sync" "testing" "time" @@ -90,12 +91,10 @@ func TestSharedAudioBuffer_EncoderBlocking(t *testing.T) { // Start a goroutine that will write samples after a delay var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { time.Sleep(50 * time.Millisecond) - buf.Write([]float64{1.0, 2.0, 3.0, 4.0}) - }() + _ = buf.Write([]float64{1.0, 2.0, 3.0, 4.0}) + }) // This should block until samples are available start := time.Now() @@ -119,7 +118,7 @@ func TestSharedAudioBuffer_CloseUnblocksReaders(t *testing.T) { buf := NewSharedAudioBuffer(1024) // Write partial data - buf.Write([]float64{1.0, 2.0}) + _ = buf.Write([]float64{1.0, 2.0}) // Start a goroutine that will close after a delay go func() { @@ -145,7 +144,7 @@ func TestSharedAudioBuffer_CloseUnblocksReaders(t *testing.T) { // Next read should return ErrBufferClosed _, err = buf.ReadForEncoder(1) - if err != ErrBufferClosed { + if !errors.Is(err, ErrBufferClosed) { t.Errorf("Expected ErrBufferClosed, got %v", err) } } @@ -163,7 +162,7 @@ func TestSharedAudioBuffer_NonBlockingReturnsNil(t *testing.T) { } // Write some but not enough - buf.Write([]float64{1.0, 2.0}) + _ = buf.Write([]float64{1.0, 2.0}) samples, err = buf.ReadForEncoderNonBlocking(10) if err != nil { @@ -174,7 +173,7 @@ func TestSharedAudioBuffer_NonBlockingReturnsNil(t *testing.T) { } // Now write enough - buf.Write([]float64{3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0}) + _ = buf.Write([]float64{3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0}) samples, err = buf.ReadForEncoderNonBlocking(10) if err != nil { @@ -193,11 +192,11 @@ func TestSharedAudioBuffer_Compact(t *testing.T) { for i := range samples { samples[i] = float64(i) } - buf.Write(samples) + _ = buf.Write(samples) // Both consumers read 50 samples - buf.ReadForFFT(50) - buf.ReadForEncoderNonBlocking(50) + _, _ = buf.ReadForFFT(50) + _, _ = buf.ReadForEncoderNonBlocking(50) // Compact should remove the first 50 buf.CompactBuffer() @@ -229,11 +228,11 @@ func TestSharedAudioBuffer_CompactPartial(t *testing.T) { for i := range samples { samples[i] = float64(i) } - buf.Write(samples) + _ = buf.Write(samples) // FFT reads 70, encoder reads 30 - buf.ReadForFFT(70) - buf.ReadForEncoderNonBlocking(30) + _, _ = buf.ReadForFFT(70) + _, _ = buf.ReadForEncoderNonBlocking(30) // Compact should only remove 30 (the minimum) buf.CompactBuffer() @@ -255,8 +254,8 @@ func TestSharedAudioBuffer_CompactPartial(t *testing.T) { func TestSharedAudioBuffer_Reset(t *testing.T) { buf := NewSharedAudioBuffer(1024) - buf.Write([]float64{1.0, 2.0, 3.0}) - buf.ReadForFFT(2) + _ = buf.Write([]float64{1.0, 2.0, 3.0}) + _, _ = buf.ReadForFFT(2) buf.Close() // Reset @@ -287,7 +286,7 @@ func TestSharedAudioBuffer_WriteAfterClose(t *testing.T) { buf.Close() err := buf.Write([]float64{1.0}) - if err != ErrBufferClosed { + if !errors.Is(err, ErrBufferClosed) { t.Errorf("Write after close should return ErrBufferClosed, got %v", err) } } @@ -301,12 +300,10 @@ func TestSharedAudioBuffer_ConcurrentAccess(t *testing.T) { var wg sync.WaitGroup // Writer goroutine - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { for i := 0; i < numSamples; i += chunkSize { chunk := make([]float64, chunkSize) - for j := 0; j < chunkSize; j++ { + for j := range chunkSize { chunk[j] = float64(i + j) } if err := buf.Write(chunk); err != nil { @@ -315,36 +312,32 @@ func TestSharedAudioBuffer_ConcurrentAccess(t *testing.T) { } } buf.Close() - }() + }) // FFT reader goroutine fftTotal := 0 - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { for { samples, err := buf.ReadForFFT(512) - if err == ErrBufferClosed { + if errors.Is(err, ErrBufferClosed) { break } fftTotal += len(samples) time.Sleep(time.Microsecond) // Simulate some work } - }() + }) // Encoder reader goroutine encTotal := 0 - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { for { samples, err := buf.ReadForEncoder(1024) - if err == ErrBufferClosed { + if errors.Is(err, ErrBufferClosed) { break } encTotal += len(samples) } - }() + }) wg.Wait() diff --git a/internal/cli/help.go b/internal/cli/help.go index 165c5c7..2d5109c 100644 --- a/internal/cli/help.go +++ b/internal/cli/help.go @@ -52,7 +52,7 @@ func StyledHelpPrinter(options kong.HelpOptions) kong.HelpPrinter { // Usage sb.WriteString(helpSectionStyle.Render("Usage:")) sb.WriteString("\n ") - sb.WriteString(fmt.Sprintf("%s [ []] [flags]", ctx.Model.Name)) + fmt.Fprintf(&sb, "%s [ []] [flags]", ctx.Model.Name) sb.WriteString("\n") // Arguments section @@ -114,7 +114,7 @@ func getArguments(ctx *kong.Context) []argument { var args []argument // Parse arguments from the model - for _, arg := range ctx.Model.Node.Positional { + for _, arg := range ctx.Model.Positional { name := arg.Summary() help := arg.Help args = append(args, argument{name: name, help: help}) @@ -133,12 +133,12 @@ func getFlags(ctx *kong.Context) []flag { }) // Parse flags from the model - for _, f := range ctx.Model.Node.Flags { + for _, f := range ctx.Model.Flags { if f.Name == "help" { continue // Already added } - flagStr := "" + var flagStr string if f.Short != 0 { flagStr = fmt.Sprintf("-%c, --%s", f.Short, f.Name) } else { diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 50028e6..42227e8 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -614,6 +614,4 @@ func TestRuntimeConfig_NilFields(t *testing.T) { } // ptrUint8 is a helper to create pointers to uint8 values for testing. -func ptrUint8(v uint8) *uint8 { - return &v -} +func ptrUint8(v uint8) *uint8 { return &v } //nolint:modernize // pointer-to-value helper for tests diff --git a/internal/encoder/encoder.go b/internal/encoder/encoder.go index 17907e7..ea00ce0 100644 --- a/internal/encoder/encoder.go +++ b/internal/encoder/encoder.go @@ -48,7 +48,7 @@ func NewAudioFIFO(frameSize int) *AudioFIFO { buffer: make([]float32, 0, 4096), // Start with reasonable capacity frameSize: frameSize, pool: &sync.Pool{ - New: func() interface{} { + New: func() any { s := make([]float32, frameSize) return &s }, @@ -278,25 +278,23 @@ func (e *Encoder) Initialize() error { if e.hwEncoder != nil { // Hardware encoder options - if err := e.setHWEncoderOptions(&opts); err != nil { - return fmt.Errorf("failed to set hardware encoder options: %w", err) - } + e.setHWEncoderOptions(&opts) } else { // Software encoder (x264) options optimized for visualization content // CRF 24 = good quality for busy visualizations - ffmpeg.AVDictSet(&opts, ffmpeg.ToCStr("crf"), ffmpeg.ToCStr("24"), 0) + _, _ = ffmpeg.AVDictSet(&opts, ffmpeg.ToCStr("crf"), ffmpeg.ToCStr("24"), 0) // Faster preset prioritizes encoding speed - ffmpeg.AVDictSet(&opts, ffmpeg.ToCStr("preset"), ffmpeg.ToCStr("veryfast"), 0) + _, _ = ffmpeg.AVDictSet(&opts, ffmpeg.ToCStr("preset"), ffmpeg.ToCStr("veryfast"), 0) // Tune for animation content - ffmpeg.AVDictSet(&opts, ffmpeg.ToCStr("tune"), ffmpeg.ToCStr("animation"), 0) + _, _ = ffmpeg.AVDictSet(&opts, ffmpeg.ToCStr("tune"), ffmpeg.ToCStr("animation"), 0) // Main profile for faster encoding and broad compatibility - ffmpeg.AVDictSet(&opts, ffmpeg.ToCStr("profile"), ffmpeg.ToCStr("main"), 0) + _, _ = ffmpeg.AVDictSet(&opts, ffmpeg.ToCStr("profile"), ffmpeg.ToCStr("main"), 0) // Single reference frame (simple vertical bar motion doesn't need multiple refs) - ffmpeg.AVDictSet(&opts, ffmpeg.ToCStr("ref"), ffmpeg.ToCStr("1"), 0) + _, _ = ffmpeg.AVDictSet(&opts, ffmpeg.ToCStr("ref"), ffmpeg.ToCStr("1"), 0) // Reduce b-frames for faster encoding (predictable bar motion) - ffmpeg.AVDictSet(&opts, ffmpeg.ToCStr("bf"), ffmpeg.ToCStr("1"), 0) + _, _ = ffmpeg.AVDictSet(&opts, ffmpeg.ToCStr("bf"), ffmpeg.ToCStr("1"), 0) // Simpler subpixel motion estimation (bars move in discrete pixels) - ffmpeg.AVDictSet(&opts, ffmpeg.ToCStr("subme"), ffmpeg.ToCStr("4"), 0) + _, _ = ffmpeg.AVDictSet(&opts, ffmpeg.ToCStr("subme"), ffmpeg.ToCStr("4"), 0) } // Open codec with options @@ -336,71 +334,69 @@ func (e *Encoder) Initialize() error { } // setHWEncoderOptions configures encoder-specific options for hardware encoders -func (e *Encoder) setHWEncoderOptions(opts **ffmpeg.AVDictionary) error { +func (e *Encoder) setHWEncoderOptions(opts **ffmpeg.AVDictionary) { if e.hwEncoder == nil { - return nil + return } switch e.hwEncoder.Type { case HWAccelNVENC: // NVENC options optimized for fast visualisation encoding // Preset p2 = faster encoding with acceptable quality (p1=fastest, p7=slowest) - ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("preset"), ffmpeg.ToCStr("p1"), 0) + _, _ = ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("preset"), ffmpeg.ToCStr("p1"), 0) // Low latency tuning - reduces pipeline delay - ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("tune"), ffmpeg.ToCStr("ull"), 0) + _, _ = ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("tune"), ffmpeg.ToCStr("ull"), 0) // Target quality (CQ mode) - similar to CRF, lower=better (0-51) - ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("rc"), ffmpeg.ToCStr("vbr"), 0) - ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("cq"), ffmpeg.ToCStr("24"), 0) + _, _ = ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("rc"), ffmpeg.ToCStr("vbr"), 0) + _, _ = ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("cq"), ffmpeg.ToCStr("24"), 0) // Main profile for broad compatibility - ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("profile"), ffmpeg.ToCStr("main"), 0) + _, _ = ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("profile"), ffmpeg.ToCStr("main"), 0) // No B-frames for faster encoding (visualisation has low motion) - ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("bf"), ffmpeg.ToCStr("0"), 0) + _, _ = ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("bf"), ffmpeg.ToCStr("0"), 0) // Zero latency mode - no reordering delay - ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("zerolatency"), ffmpeg.ToCStr("1"), 0) + _, _ = ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("zerolatency"), ffmpeg.ToCStr("1"), 0) case HWAccelQSV: // Intel Quick Sync Video options - ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("preset"), ffmpeg.ToCStr("medium"), 0) - ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("global_quality"), ffmpeg.ToCStr("24"), 0) - ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("profile"), ffmpeg.ToCStr("main"), 0) + _, _ = ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("preset"), ffmpeg.ToCStr("medium"), 0) + _, _ = ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("global_quality"), ffmpeg.ToCStr("24"), 0) + _, _ = ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("profile"), ffmpeg.ToCStr("main"), 0) case HWAccelVulkan: // Vulkan Video options optimized for fast visualisation encoding - ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("content"), ffmpeg.ToCStr("rendered"), 0) + _, _ = ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("content"), ffmpeg.ToCStr("rendered"), 0) // Quality level (0-51, lower=better) - same as NVENC CQ - ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("qp"), ffmpeg.ToCStr("24"), 0) + _, _ = ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("qp"), ffmpeg.ToCStr("24"), 0) // Low latency tuning - reduces pipeline delay - ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("tune"), ffmpeg.ToCStr("ull"), 0) + _, _ = ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("tune"), ffmpeg.ToCStr("ull"), 0) // Increase async depth for more parallelism (default=2) - ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("async_depth"), ffmpeg.ToCStr("4"), 0) + _, _ = ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("async_depth"), ffmpeg.ToCStr("4"), 0) // Main profile for broad compatibility - ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("profile"), ffmpeg.ToCStr("main"), 0) + _, _ = ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("profile"), ffmpeg.ToCStr("main"), 0) // Minimal B-frame depth (1 is minimum) - ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("b_depth"), ffmpeg.ToCStr("1"), 0) + _, _ = ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("b_depth"), ffmpeg.ToCStr("1"), 0) case HWAccelVAAPI: // VA-API options optimized for fast visualisation encoding // Quality level (1-51, lower=better) - CQP rate control - ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("qp"), ffmpeg.ToCStr("24"), 0) + _, _ = ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("qp"), ffmpeg.ToCStr("24"), 0) // Main profile for broad compatibility - ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("profile"), ffmpeg.ToCStr("main"), 0) + _, _ = ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("profile"), ffmpeg.ToCStr("main"), 0) // Low latency: disable B-frames for faster encoding - ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("bf"), ffmpeg.ToCStr("0"), 0) + _, _ = ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("bf"), ffmpeg.ToCStr("0"), 0) case HWAccelVideoToolbox: // Apple VideoToolbox options optimised for fast visualisation encoding // Note: VideoToolbox does not support constant quality (CRF/CQ) encoding. // It uses bitrate-based rate control only, so we cannot set quality levels // like other hardware encoders. The encoder will use default VBR settings. - ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("profile"), ffmpeg.ToCStr("main"), 0) - ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("level"), ffmpeg.ToCStr("4.1"), 0) + _, _ = ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("profile"), ffmpeg.ToCStr("main"), 0) + _, _ = ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("level"), ffmpeg.ToCStr("4.1"), 0) // Real-time encoding hint - prioritises speed for live/visualisation use - ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("realtime"), ffmpeg.ToCStr("1"), 0) + _, _ = ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("realtime"), ffmpeg.ToCStr("1"), 0) // Require hardware encoding - fail if hardware unavailable - ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("allow_sw"), ffmpeg.ToCStr("0"), 0) + _, _ = ffmpeg.AVDictSet(opts, ffmpeg.ToCStr("allow_sw"), ffmpeg.ToCStr("0"), 0) } - - return nil } // setupHWFramesContext creates and configures the hardware frames context @@ -662,9 +658,7 @@ func (e *Encoder) writeFrameRGBASoftware(rgbaData []byte) error { } // Convert RGBA directly to YUV420P (skips RGB24 intermediate) - if err := convertRGBAToYUV(rgbaData, yuvFrame, e.config.Width, e.config.Height); err != nil { - return fmt.Errorf("RGBA to YUV conversion failed: %w", err) - } + convertRGBAToYUV(rgbaData, yuvFrame, e.config.Width, e.config.Height) // Set presentation timestamp yuvFrame.SetPts(e.nextVideoPts) @@ -707,10 +701,10 @@ func (e *Encoder) writeFrameRGBADirect(rgbaData []byte) error { // Copy row by row (frame may have padding) srcStride := width * 4 - for y := 0; y < height; y++ { + for y := range height { srcOffset := y * srcStride dstOffset := y * linesize - copy(unsafe.Slice((*byte)(unsafe.Pointer(uintptr(unsafe.Pointer(data))+uintptr(dstOffset))), srcStride), + copy(unsafe.Slice((*byte)(unsafe.Add(data, dstOffset)), srcStride), //nolint:gosec // offset is within allocated frame rgbaData[srcOffset:srcOffset+srcStride]) } @@ -740,9 +734,7 @@ func (e *Encoder) writeFrameHWUpload(rgbaData []byte) error { nv12Frame := e.hwNV12Frame // Convert RGBA → NV12 using parallel Go conversion (much faster than SwsScaleFrame) - if err := convertRGBAToNV12(rgbaData, nv12Frame, width, height); err != nil { - return fmt.Errorf("failed to convert RGBA to NV12: %w", err) - } + convertRGBAToNV12(rgbaData, nv12Frame, width, height) // Allocate hardware frame from pool // Note: hwFrame must be allocated per-call as it's returned to pool after encoding @@ -803,9 +795,7 @@ func (e *Encoder) WriteFrame(rgbData []byte) error { } // Convert RGB to YUV420p using stdlib-optimized implementation - if err := convertRGBToYUV(rgbData, yuvFrame, e.config.Width, e.config.Height); err != nil { - return fmt.Errorf("RGB to YUV conversion failed: %w", err) - } + convertRGBToYUV(rgbData, yuvFrame, e.config.Width, e.config.Height) // Set presentation timestamp yuvFrame.SetPts(e.nextVideoPts) @@ -821,7 +811,7 @@ func (e *Encoder) WriteFrame(rgbData []byte) error { for { pkt := ffmpeg.AVPacketAlloc() - ret, err := ffmpeg.AVCodecReceivePacket(e.videoCodec, pkt) + _, err := ffmpeg.AVCodecReceivePacket(e.videoCodec, pkt) if err != nil { ffmpeg.AVPacketFree(&pkt) // EAGAIN and EOF are expected - means no more packets available @@ -852,7 +842,7 @@ func (e *Encoder) receiveAndWriteVideoPackets() error { for { pkt := ffmpeg.AVPacketAlloc() - ret, err := ffmpeg.AVCodecReceivePacket(e.videoCodec, pkt) + _, err := ffmpeg.AVCodecReceivePacket(e.videoCodec, pkt) if err != nil { ffmpeg.AVPacketFree(&pkt) // EAGAIN and EOF are expected - means no more packets available @@ -867,7 +857,7 @@ func (e *Encoder) receiveAndWriteVideoPackets() error { ffmpeg.AVPacketRescaleTs(pkt, e.videoCodec.TimeBase(), e.videoStream.TimeBase()) // Write packet to output - ret, err = ffmpeg.AVInterleavedWriteFrame(e.formatCtx, pkt) + ret, err := ffmpeg.AVInterleavedWriteFrame(e.formatCtx, pkt) ffmpeg.AVPacketFree(&pkt) if err := checkFFmpeg(ret, err, "write packet"); err != nil { @@ -903,7 +893,7 @@ func (e *Encoder) WriteAudioSamples(samples []float32) error { frameSamples := e.audioFIFO.Pop(samplesPerFrame) // Make frame writable and write samples - ffmpeg.AVFrameMakeWritable(e.audioEncFrame) + _, _ = ffmpeg.AVFrameMakeWritable(e.audioEncFrame) var writeErr error if outputChannels == 2 { @@ -933,7 +923,7 @@ func (e *Encoder) WriteAudioSamples(samples []float32) error { // Receive encoded packets for { encodedPkt := ffmpeg.AVPacketAlloc() - ret, err = ffmpeg.AVCodecReceivePacket(e.audioCodec, encodedPkt) + _, err = ffmpeg.AVCodecReceivePacket(e.audioCodec, encodedPkt) if err != nil { ffmpeg.AVPacketFree(&encodedPkt) // EAGAIN and EOF are expected - means no more packets available @@ -983,7 +973,7 @@ func (e *Encoder) FlushAudioEncoder() error { // Return partial slice to pool (safe even for non-pooled sizes) e.audioFIFO.ReturnSlice(partialSamples) - ffmpeg.AVFrameMakeWritable(e.audioEncFrame) + _, _ = ffmpeg.AVFrameMakeWritable(e.audioEncFrame) var writeErr error if outputChannels == 2 { @@ -1006,7 +996,7 @@ func (e *Encoder) FlushAudioEncoder() error { } // Flush encoder by sending NULL frame - ffmpeg.AVCodecSendFrame(e.audioCodec, nil) + _, _ = ffmpeg.AVCodecSendFrame(e.audioCodec, nil) // Receive all remaining packets for { @@ -1020,7 +1010,7 @@ func (e *Encoder) FlushAudioEncoder() error { encodedPkt.SetStreamIndex(e.audioStream.Index()) ffmpeg.AVPacketRescaleTs(encodedPkt, e.audioCodec.TimeBase(), e.audioStream.TimeBase()) - ffmpeg.AVInterleavedWriteFrame(e.formatCtx, encodedPkt) + _, _ = ffmpeg.AVInterleavedWriteFrame(e.formatCtx, encodedPkt) ffmpeg.AVPacketFree(&encodedPkt) } @@ -1039,10 +1029,10 @@ func writeMonoFloats(frame *ffmpeg.AVFrame, samples []float32) error { } // Convert to byte slice for writing - data := (*[1 << 30]byte)(unsafe.Pointer(dataPtr))[: nbSamples*4 : nbSamples*4] + data := (*[1 << 30]byte)(dataPtr)[: nbSamples*4 : nbSamples*4] // Write samples to channel - for i := 0; i < nbSamples; i++ { + for i := range nbSamples { // Write channel - direct float32 byte copy sampleFloat := samples[i] copy(data[i*4:(i+1)*4], (*[4]byte)(unsafe.Pointer(&sampleFloat))[:]) @@ -1064,11 +1054,11 @@ func writeStereoFloats(frame *ffmpeg.AVFrame, samples []float32) error { } // Convert to byte slices for writing - leftData := (*[1 << 30]byte)(unsafe.Pointer(leftPtr))[: nbSamples*4 : nbSamples*4] - rightData := (*[1 << 30]byte)(unsafe.Pointer(rightPtr))[: nbSamples*4 : nbSamples*4] + leftData := (*[1 << 30]byte)(leftPtr)[: nbSamples*4 : nbSamples*4] + rightData := (*[1 << 30]byte)(rightPtr)[: nbSamples*4 : nbSamples*4] // Write samples to both channels - for i := 0; i < nbSamples; i++ { + for i := range nbSamples { // Write left channel - direct float32 byte copy leftFloat := samples[i*2] copy(leftData[i*4:(i+1)*4], (*[4]byte)(unsafe.Pointer(&leftFloat))[:]) @@ -1083,10 +1073,9 @@ func writeStereoFloats(frame *ffmpeg.AVFrame, samples []float32) error { // Close finalizes the output file and frees resources func (e *Encoder) Close() error { - // Flush encoder if e.videoCodec != nil { - ffmpeg.AVCodecSendFrame(e.videoCodec, nil) + _, _ = ffmpeg.AVCodecSendFrame(e.videoCodec, nil) // Drain remaining packets for { @@ -1101,7 +1090,7 @@ func (e *Encoder) Close() error { if ret >= 0 { pkt.SetStreamIndex(e.videoStream.Index()) ffmpeg.AVPacketRescaleTs(pkt, e.videoCodec.TimeBase(), e.videoStream.TimeBase()) - ffmpeg.AVInterleavedWriteFrame(e.formatCtx, pkt) + _, _ = ffmpeg.AVInterleavedWriteFrame(e.formatCtx, pkt) } ffmpeg.AVPacketFree(&pkt) @@ -1110,7 +1099,7 @@ func (e *Encoder) Close() error { // Write trailer if e.formatCtx != nil { - ffmpeg.AVWriteTrailer(e.formatCtx) + _, _ = ffmpeg.AVWriteTrailer(e.formatCtx) // Close output file if e.formatCtx.Pb() != nil { diff --git a/internal/encoder/encoder_test.go b/internal/encoder/encoder_test.go index 88ffa09..80b6f38 100644 --- a/internal/encoder/encoder_test.go +++ b/internal/encoder/encoder_test.go @@ -233,10 +233,10 @@ func TestAudioFIFO_SequentialOperations(t *testing.T) { fifo := NewAudioFIFO(1024) // Push and pop multiple times - for round := 0; round < 5; round++ { + for round := range 5 { // Push 10 samples samples := make([]float32, 10) - for i := 0; i < 10; i++ { + for i := range 10 { samples[i] = float32(round*10 + i) } fifo.Push(samples) @@ -281,7 +281,7 @@ func TestAudioFIFO_LargeValues(t *testing.T) { // Push a large number of samples largeCount := 100000 samples := make([]float32, largeCount) - for i := 0; i < largeCount; i++ { + for i := range largeCount { samples[i] = float32(i) } fifo.Push(samples) diff --git a/internal/encoder/frame.go b/internal/encoder/frame.go index 0122a8f..9271582 100644 --- a/internal/encoder/frame.go +++ b/internal/encoder/frame.go @@ -34,7 +34,7 @@ const ( // //go:inline func rgbToY(r, g, b int32) uint8 { - return uint8((yR*r + yG*g + yB*b + 1<<15) >> 16) + return uint8((yR*r + yG*g + yB*b + 1<<15) >> 16) //nolint:gosec // result is clamped to 0-255 } // rgbToCb converts RGB to Cb (blue-difference chroma) with branchless clamping. @@ -42,12 +42,12 @@ func rgbToY(r, g, b int32) uint8 { //go:inline func rgbToCb(r, g, b int32) uint8 { cb := cbR*r + cbG*g + cbB*b + 257<<15 - if uint32(cb)&0xff000000 == 0 { + if uint32(cb)&0xff000000 == 0 { //nolint:gosec // intentional bit manipulation cb >>= 16 } else { cb = ^(cb >> 31) } - return uint8(cb) + return uint8(cb) //nolint:gosec // value is clamped by branch above } // rgbToCr converts RGB to Cr (red-difference chroma) with branchless clamping. @@ -55,12 +55,12 @@ func rgbToCb(r, g, b int32) uint8 { //go:inline func rgbToCr(r, g, b int32) uint8 { cr := crR*r + crG*g + crB*b + 257<<15 - if uint32(cr)&0xff000000 == 0 { + if uint32(cr)&0xff000000 == 0 { //nolint:gosec // intentional bit manipulation cr >>= 16 } else { cr = ^(cr >> 31) } - return uint8(cr) + return uint8(cr) //nolint:gosec // value is clamped by branch above } // parallelRows executes fn across height rows using all CPU cores. @@ -75,7 +75,7 @@ func parallelRows(height int, fn func(startY, endY int)) { var wg sync.WaitGroup wg.Add(numCPU) - for worker := 0; worker < numCPU; worker++ { + for worker := range numCPU { startY := worker * rowsPerWorker endY := startY + rowsPerWorker if worker == numCPU-1 { @@ -92,14 +92,14 @@ func parallelRows(height int, fn func(startY, endY int)) { } // convertRGBToYUV converts RGB24 data to YUV420P (planar) format. -func convertRGBToYUV(rgbData []byte, yuvFrame *ffmpeg.AVFrame, width, height int) error { +func convertRGBToYUV(rgbData []byte, yuvFrame *ffmpeg.AVFrame, width, height int) { yPlane := yuvFrame.Data().Get(0) uPlane := yuvFrame.Data().Get(1) vPlane := yuvFrame.Data().Get(2) - yLinesize := int(yuvFrame.Linesize().Get(0)) - uLinesize := int(yuvFrame.Linesize().Get(1)) - vLinesize := int(yuvFrame.Linesize().Get(2)) + yLinesize := yuvFrame.Linesize().Get(0) + uLinesize := yuvFrame.Linesize().Get(1) + vLinesize := yuvFrame.Linesize().Get(2) parallelRows(height, func(startY, endY int) { // Align startY to even for correct UV row calculation @@ -110,13 +110,13 @@ func convertRGBToYUV(rgbData []byte, yuvFrame *ffmpeg.AVFrame, width, height int // Process even rows: Y + UV for y := evenStart; y < endY; y += 2 { - yPtr := unsafe.Add(unsafe.Pointer(yPlane), y*yLinesize) + yPtr := unsafe.Add(yPlane, y*yLinesize) uvY := y >> 1 - uRowPtr := unsafe.Add(unsafe.Pointer(uPlane), uvY*uLinesize) - vRowPtr := unsafe.Add(unsafe.Pointer(vPlane), uvY*vLinesize) + uRowPtr := unsafe.Add(uPlane, uvY*uLinesize) + vRowPtr := unsafe.Add(vPlane, uvY*vLinesize) rgbIdx := y * width * 3 - for x := 0; x < width; x++ { + for x := range width { r := int32(rgbData[rgbIdx]) g := int32(rgbData[rgbIdx+1]) b := int32(rgbData[rgbIdx+2]) @@ -139,10 +139,10 @@ func convertRGBToYUV(rgbData []byte, yuvFrame *ffmpeg.AVFrame, width, height int oddStart++ } for y := oddStart; y < endY; y += 2 { - yPtr := unsafe.Add(unsafe.Pointer(yPlane), y*yLinesize) + yPtr := unsafe.Add(yPlane, y*yLinesize) rgbIdx := y * width * 3 - for x := 0; x < width; x++ { + for x := range width { r := int32(rgbData[rgbIdx]) g := int32(rgbData[rgbIdx+1]) b := int32(rgbData[rgbIdx+2]) @@ -152,20 +152,18 @@ func convertRGBToYUV(rgbData []byte, yuvFrame *ffmpeg.AVFrame, width, height int } } }) - - return nil } // convertRGBAToYUV converts RGBA data directly to YUV420P (planar) format. // Skips the intermediate RGB24 buffer allocation for significantly faster software encoding. -func convertRGBAToYUV(rgbaData []byte, yuvFrame *ffmpeg.AVFrame, width, height int) error { +func convertRGBAToYUV(rgbaData []byte, yuvFrame *ffmpeg.AVFrame, width, height int) { yPlane := yuvFrame.Data().Get(0) uPlane := yuvFrame.Data().Get(1) vPlane := yuvFrame.Data().Get(2) - yLinesize := int(yuvFrame.Linesize().Get(0)) - uLinesize := int(yuvFrame.Linesize().Get(1)) - vLinesize := int(yuvFrame.Linesize().Get(2)) + yLinesize := yuvFrame.Linesize().Get(0) + uLinesize := yuvFrame.Linesize().Get(1) + vLinesize := yuvFrame.Linesize().Get(2) parallelRows(height, func(startY, endY int) { // Align startY to even for correct UV row calculation @@ -176,13 +174,13 @@ func convertRGBAToYUV(rgbaData []byte, yuvFrame *ffmpeg.AVFrame, width, height i // Process even rows: Y + UV for y := evenStart; y < endY; y += 2 { - yPtr := unsafe.Add(unsafe.Pointer(yPlane), y*yLinesize) + yPtr := unsafe.Add(yPlane, y*yLinesize) uvY := y >> 1 - uRowPtr := unsafe.Add(unsafe.Pointer(uPlane), uvY*uLinesize) - vRowPtr := unsafe.Add(unsafe.Pointer(vPlane), uvY*vLinesize) + uRowPtr := unsafe.Add(uPlane, uvY*uLinesize) + vRowPtr := unsafe.Add(vPlane, uvY*vLinesize) rgbaIdx := y * width * 4 - for x := 0; x < width; x++ { + for x := range width { r := int32(rgbaData[rgbaIdx]) g := int32(rgbaData[rgbaIdx+1]) b := int32(rgbaData[rgbaIdx+2]) @@ -205,10 +203,10 @@ func convertRGBAToYUV(rgbaData []byte, yuvFrame *ffmpeg.AVFrame, width, height i oddStart++ } for y := oddStart; y < endY; y += 2 { - yPtr := unsafe.Add(unsafe.Pointer(yPlane), y*yLinesize) + yPtr := unsafe.Add(yPlane, y*yLinesize) rgbaIdx := y * width * 4 - for x := 0; x < width; x++ { + for x := range width { r := int32(rgbaData[rgbaIdx]) g := int32(rgbaData[rgbaIdx+1]) b := int32(rgbaData[rgbaIdx+2]) @@ -218,18 +216,16 @@ func convertRGBAToYUV(rgbaData []byte, yuvFrame *ffmpeg.AVFrame, width, height i } } }) - - return nil } // convertRGBAToNV12 converts RGBA data to NV12 (semi-planar) format. // NV12 has a Y plane followed by interleaved UV plane. -func convertRGBAToNV12(rgbaData []byte, nv12Frame *ffmpeg.AVFrame, width, height int) error { +func convertRGBAToNV12(rgbaData []byte, nv12Frame *ffmpeg.AVFrame, width, height int) { yPlane := nv12Frame.Data().Get(0) uvPlane := nv12Frame.Data().Get(1) - yLinesize := int(nv12Frame.Linesize().Get(0)) - uvLinesize := int(nv12Frame.Linesize().Get(1)) + yLinesize := nv12Frame.Linesize().Get(0) + uvLinesize := nv12Frame.Linesize().Get(1) parallelRows(height, func(startY, endY int) { // Align startY to even for correct UV row calculation @@ -240,12 +236,12 @@ func convertRGBAToNV12(rgbaData []byte, nv12Frame *ffmpeg.AVFrame, width, height // Process even rows: Y + UV for y := evenStart; y < endY; y += 2 { - yPtr := unsafe.Add(unsafe.Pointer(yPlane), y*yLinesize) + yPtr := unsafe.Add(yPlane, y*yLinesize) uvY := y >> 1 - uvRowPtr := unsafe.Add(unsafe.Pointer(uvPlane), uvY*uvLinesize) + uvRowPtr := unsafe.Add(uvPlane, uvY*uvLinesize) rgbaIdx := y * width * 4 - for x := 0; x < width; x++ { + for x := range width { r := int32(rgbaData[rgbaIdx]) g := int32(rgbaData[rgbaIdx+1]) b := int32(rgbaData[rgbaIdx+2]) @@ -269,10 +265,10 @@ func convertRGBAToNV12(rgbaData []byte, nv12Frame *ffmpeg.AVFrame, width, height oddStart++ } for y := oddStart; y < endY; y += 2 { - yPtr := unsafe.Add(unsafe.Pointer(yPlane), y*yLinesize) + yPtr := unsafe.Add(yPlane, y*yLinesize) rgbaIdx := y * width * 4 - for x := 0; x < width; x++ { + for x := range width { r := int32(rgbaData[rgbaIdx]) g := int32(rgbaData[rgbaIdx+1]) b := int32(rgbaData[rgbaIdx+2]) @@ -282,6 +278,4 @@ func convertRGBAToNV12(rgbaData []byte, nv12Frame *ffmpeg.AVFrame, width, height } } }) - - return nil } diff --git a/internal/encoder/hwaccel.go b/internal/encoder/hwaccel.go index 51b66f4..65adcb2 100644 --- a/internal/encoder/hwaccel.go +++ b/internal/encoder/hwaccel.go @@ -186,11 +186,7 @@ func testEncoderAvailable(encoderName string, deviceType ffmpeg.AVHWDeviceType, // Try to open the encoder - this is the definitive test ret, _ = ffmpeg.AVCodecOpen2(codecCtx, codec, nil) - if ret < 0 { - return false - } - - return true + return ret >= 0 } // DetectHWEncoders probes for available hardware encoders diff --git a/internal/encoder/sws_benchmark_test.go b/internal/encoder/sws_benchmark_test.go index b658308..cadff9a 100644 --- a/internal/encoder/sws_benchmark_test.go +++ b/internal/encoder/sws_benchmark_test.go @@ -40,7 +40,7 @@ const ( ) // Current Go implementation (copied from encoder/frame.go for comparison) -func convertRGBToYUVGo(rgbData []byte, yuvFrame *ffmpeg.AVFrame, width, height int) error { +func convertRGBToYUVGo(rgbData []byte, yuvFrame *ffmpeg.AVFrame, width, height int) { yPlane := yuvFrame.Data().Get(0) uPlane := yuvFrame.Data().Get(1) vPlane := yuvFrame.Data().Get(2) @@ -71,7 +71,7 @@ func convertRGBToYUVGo(rgbData []byte, yuvFrame *ffmpeg.AVFrame, width, height i var wg sync.WaitGroup wg.Add(numCPU) - for worker := 0; worker < numCPU; worker++ { + for worker := range numCPU { startY := worker * rowsPerWorker endY := startY + rowsPerWorker if worker == numCPU-1 { @@ -82,18 +82,18 @@ func convertRGBToYUVGo(rgbData []byte, yuvFrame *ffmpeg.AVFrame, width, height i defer wg.Done() for y := startY; y < endY; y++ { - yOffset := y * int(yLinesize) - yPtr := unsafe.Add(unsafe.Pointer(yPlane), yOffset) + yOffset := y * yLinesize + yPtr := unsafe.Add(yPlane, yOffset) rgbIdx := y * width * 3 - for x := 0; x < width; x++ { + for x := range width { r1 := int32(rgbData[rgbIdx]) g1 := int32(rgbData[rgbIdx+1]) b1 := int32(rgbData[rgbIdx+2]) rgbIdx += 3 yy := (yR*r1 + yG*g1 + yB*b1 + 1<<15) >> 16 - *(*uint8)(unsafe.Add(yPtr, x)) = uint8(yy) + *(*uint8)(unsafe.Add(yPtr, x)) = uint8(yy) //nolint:gosec // result is clamped to 0-255 if (y&1) == 0 && (x&1) == 0 { cb := cbR*r1 + cbG*g1 + cbB*b1 + 257<<15 @@ -112,11 +112,11 @@ func convertRGBToYUVGo(rgbData []byte, yuvFrame *ffmpeg.AVFrame, width, height i uvY := y >> 1 uvX := x >> 1 - uOffset := uvY*int(uLinesize) + uvX - vOffset := uvY*int(vLinesize) + uvX + uOffset := uvY*uLinesize + uvX + vOffset := uvY*vLinesize + uvX - *(*uint8)(unsafe.Add(unsafe.Pointer(uPlane), uOffset)) = uint8(cb) - *(*uint8)(unsafe.Add(unsafe.Pointer(vPlane), vOffset)) = uint8(cr) + *(*uint8)(unsafe.Add(uPlane, uOffset)) = uint8(cb) //nolint:gosec // value is clamped + *(*uint8)(unsafe.Add(vPlane, vOffset)) = uint8(cr) //nolint:gosec // value is clamped } } } @@ -124,7 +124,6 @@ func convertRGBToYUVGo(rgbData []byte, yuvFrame *ffmpeg.AVFrame, width, height i } wg.Wait() - return nil } // SwsConverter wraps FFmpeg's swscale for RGB24 → YUV420P conversion @@ -185,10 +184,10 @@ func (c *SwsConverter) Convert(rgbData []byte, dstFrame *ffmpeg.AVFrame) error { srcData := c.srcFrame.Data().Get(0) for y := 0; y < c.height; y++ { - srcOffset := y * int(srcLinesize) + srcOffset := y * srcLinesize rgbOffset := y * c.width * 3 for x := 0; x < c.width*3; x++ { - *(*uint8)(unsafe.Add(unsafe.Pointer(srcData), srcOffset+x)) = rgbData[rgbOffset+x] + *(*uint8)(unsafe.Add(srcData, srcOffset+x)) = rgbData[rgbOffset+x] } } @@ -206,9 +205,9 @@ func (c *SwsConverter) Close() { } } -func createTestFrames(width, height int) ([]byte, *ffmpeg.AVFrame) { +func createTestFrames() ([]byte, *ffmpeg.AVFrame) { // Create RGB test data with some pattern - rgbSize := width * height * 3 + rgbSize := benchWidth * benchHeight * 3 rgbData := make([]byte, rgbSize) for i := 0; i < rgbSize; i += 3 { rgbData[i] = uint8(i % 256) // R @@ -218,10 +217,10 @@ func createTestFrames(width, height int) ([]byte, *ffmpeg.AVFrame) { // Allocate YUV frame yuvFrame := ffmpeg.AVFrameAlloc() - yuvFrame.SetWidth(width) - yuvFrame.SetHeight(height) + yuvFrame.SetWidth(benchWidth) + yuvFrame.SetHeight(benchHeight) yuvFrame.SetFormat(int(ffmpeg.AVPixFmtYuv420P)) - ffmpeg.AVFrameGetBuffer(yuvFrame, 0) + _, _ = ffmpeg.AVFrameGetBuffer(yuvFrame, 0) return rgbData, yuvFrame } @@ -233,7 +232,7 @@ func createTestFrames(width, height int) ([]byte, *ffmpeg.AVFrame) { // BenchmarkGoRGBToYUV measures the parallelised Go implementation. // This is the production code path used by Jivefire. func BenchmarkGoRGBToYUV(b *testing.B) { - rgbData, yuvFrame := createTestFrames(benchWidth, benchHeight) + rgbData, yuvFrame := createTestFrames() defer ffmpeg.AVFrameFree(&yuvFrame) b.ResetTimer() @@ -245,7 +244,7 @@ func BenchmarkGoRGBToYUV(b *testing.B) { // BenchmarkSwscaleRGBToYUV measures FFmpeg's swscale library. // Single-threaded but SIMD-optimised. func BenchmarkSwscaleRGBToYUV(b *testing.B) { - rgbData, yuvFrame := createTestFrames(benchWidth, benchHeight) + rgbData, yuvFrame := createTestFrames() defer ffmpeg.AVFrameFree(&yuvFrame) converter, err := NewSwsConverter(benchWidth, benchHeight) @@ -256,7 +255,7 @@ func BenchmarkSwscaleRGBToYUV(b *testing.B) { b.ResetTimer() for i := 0; i < b.N; i++ { - converter.Convert(rgbData, yuvFrame) + _ = converter.Convert(rgbData, yuvFrame) } } @@ -278,7 +277,7 @@ func BenchmarkRGBAToYUVDirect(b *testing.B) { yuvFrame.SetWidth(benchWidth) yuvFrame.SetHeight(benchHeight) yuvFrame.SetFormat(int(ffmpeg.AVPixFmtYuv420P)) - ffmpeg.AVFrameGetBuffer(yuvFrame, 0) + _, _ = ffmpeg.AVFrameGetBuffer(yuvFrame, 0) defer ffmpeg.AVFrameFree(&yuvFrame) b.ResetTimer() @@ -308,7 +307,7 @@ func BenchmarkRGBAToYUVViaRGB24(b *testing.B) { yuvFrame.SetWidth(benchWidth) yuvFrame.SetHeight(benchHeight) yuvFrame.SetFormat(int(ffmpeg.AVPixFmtYuv420P)) - ffmpeg.AVFrameGetBuffer(yuvFrame, 0) + _, _ = ffmpeg.AVFrameGetBuffer(yuvFrame, 0) defer ffmpeg.AVFrameFree(&yuvFrame) b.ResetTimer() @@ -349,21 +348,18 @@ func TestRGBAConversionEquivalence(t *testing.T) { yuvDirect.SetWidth(benchWidth) yuvDirect.SetHeight(benchHeight) yuvDirect.SetFormat(int(ffmpeg.AVPixFmtYuv420P)) - ffmpeg.AVFrameGetBuffer(yuvDirect, 0) + _, _ = ffmpeg.AVFrameGetBuffer(yuvDirect, 0) defer ffmpeg.AVFrameFree(&yuvDirect) yuvViaRGB := ffmpeg.AVFrameAlloc() yuvViaRGB.SetWidth(benchWidth) yuvViaRGB.SetHeight(benchHeight) yuvViaRGB.SetFormat(int(ffmpeg.AVPixFmtYuv420P)) - ffmpeg.AVFrameGetBuffer(yuvViaRGB, 0) + _, _ = ffmpeg.AVFrameGetBuffer(yuvViaRGB, 0) defer ffmpeg.AVFrameFree(&yuvViaRGB) // Convert using direct path - err := convertRGBAToYUV(rgbaData, yuvDirect, benchWidth, benchHeight) - if err != nil { - t.Fatalf("Direct RGBA→YUV conversion failed: %v", err) - } + convertRGBAToYUV(rgbaData, yuvDirect, benchWidth, benchHeight) // Convert using via-RGB24 path rgb24Size := benchWidth * benchHeight * 3 @@ -377,10 +373,7 @@ func TestRGBAConversionEquivalence(t *testing.T) { srcIdx += 4 dstIdx += 3 } - err = convertRGBToYUV(rgb24Data, yuvViaRGB, benchWidth, benchHeight) - if err != nil { - t.Fatalf("Via-RGB24 conversion failed: %v", err) - } + convertRGBToYUV(rgb24Data, yuvViaRGB, benchWidth, benchHeight) // Compare Y planes (should be identical) yLinesize := yuvDirect.Linesize().Get(0) @@ -388,11 +381,11 @@ func TestRGBAConversionEquivalence(t *testing.T) { yPlaneViaRGB := yuvViaRGB.Data().Get(0) yDiffCount := 0 - for y := 0; y < benchHeight; y++ { - for x := 0; x < benchWidth; x++ { - offset := y*int(yLinesize) + x - directVal := *(*uint8)(unsafe.Add(unsafe.Pointer(yPlaneDirect), offset)) - viaRGBVal := *(*uint8)(unsafe.Add(unsafe.Pointer(yPlaneViaRGB), offset)) + for y := range benchHeight { + for x := range benchWidth { + offset := y*yLinesize + x + directVal := *(*uint8)(unsafe.Add(yPlaneDirect, offset)) + viaRGBVal := *(*uint8)(unsafe.Add(yPlaneViaRGB, offset)) if directVal != viaRGBVal { yDiffCount++ } @@ -405,11 +398,11 @@ func TestRGBAConversionEquivalence(t *testing.T) { uPlaneViaRGB := yuvViaRGB.Data().Get(1) uDiffCount := 0 - for y := 0; y < benchHeight/2; y++ { - for x := 0; x < benchWidth/2; x++ { - offset := y*int(uLinesize) + x - directVal := *(*uint8)(unsafe.Add(unsafe.Pointer(uPlaneDirect), offset)) - viaRGBVal := *(*uint8)(unsafe.Add(unsafe.Pointer(uPlaneViaRGB), offset)) + for y := range benchHeight / 2 { + for x := range benchWidth / 2 { + offset := y*uLinesize + x + directVal := *(*uint8)(unsafe.Add(uPlaneDirect, offset)) + viaRGBVal := *(*uint8)(unsafe.Add(uPlaneViaRGB, offset)) if directVal != viaRGBVal { uDiffCount++ } @@ -422,11 +415,11 @@ func TestRGBAConversionEquivalence(t *testing.T) { vPlaneViaRGB := yuvViaRGB.Data().Get(2) vDiffCount := 0 - for y := 0; y < benchHeight/2; y++ { - for x := 0; x < benchWidth/2; x++ { - offset := y*int(vLinesize) + x - directVal := *(*uint8)(unsafe.Add(unsafe.Pointer(vPlaneDirect), offset)) - viaRGBVal := *(*uint8)(unsafe.Add(unsafe.Pointer(vPlaneViaRGB), offset)) + for y := range benchHeight / 2 { + for x := range benchWidth / 2 { + offset := y*vLinesize + x + directVal := *(*uint8)(unsafe.Add(vPlaneDirect, offset)) + viaRGBVal := *(*uint8)(unsafe.Add(vPlaneViaRGB, offset)) if directVal != viaRGBVal { vDiffCount++ } @@ -446,17 +439,14 @@ func TestRGBAConversionEquivalence(t *testing.T) { // Some pixel differences are expected due to different rounding in coefficient // implementations (Go uses integer arithmetic, FFmpeg uses floating-point). func TestConversionEquivalence(t *testing.T) { - rgbData, yuvFrameGo := createTestFrames(benchWidth, benchHeight) + rgbData, yuvFrameGo := createTestFrames() defer ffmpeg.AVFrameFree(&yuvFrameGo) - _, yuvFrameSws := createTestFrames(benchWidth, benchHeight) + _, yuvFrameSws := createTestFrames() defer ffmpeg.AVFrameFree(&yuvFrameSws) // Convert with Go implementation - err := convertRGBToYUVGo(rgbData, yuvFrameGo, benchWidth, benchHeight) - if err != nil { - t.Fatalf("Go conversion failed: %v", err) - } + convertRGBToYUVGo(rgbData, yuvFrameGo, benchWidth, benchHeight) // Convert with swscale converter, err := NewSwsConverter(benchWidth, benchHeight) @@ -477,11 +467,11 @@ func TestConversionEquivalence(t *testing.T) { diffCount := 0 maxDiff := 0 - for y := 0; y < benchHeight; y++ { - for x := 0; x < benchWidth; x++ { - offset := y*int(yLinesize) + x - goVal := *(*uint8)(unsafe.Add(unsafe.Pointer(yPlaneGo), offset)) - swsVal := *(*uint8)(unsafe.Add(unsafe.Pointer(yPlaneSws), offset)) + for y := range benchHeight { + for x := range benchWidth { + offset := y*yLinesize + x + goVal := *(*uint8)(unsafe.Add(yPlaneGo, offset)) + swsVal := *(*uint8)(unsafe.Add(yPlaneSws, offset)) diff := int(goVal) - int(swsVal) if diff < 0 { diff = -diff @@ -509,9 +499,7 @@ func TestBenchmarkSummary(t *testing.T) { t.Skip("Skipping summary in short mode") } - const iterations = 100 - - rgbData, yuvFrame := createTestFrames(benchWidth, benchHeight) + rgbData, yuvFrame := createTestFrames() defer ffmpeg.AVFrameFree(&yuvFrame) // Benchmark Go implementation @@ -530,7 +518,7 @@ func TestBenchmarkSummary(t *testing.T) { swsStart := testing.Benchmark(func(b *testing.B) { for i := 0; i < b.N; i++ { - converter.Convert(rgbData, yuvFrame) + _ = converter.Convert(rgbData, yuvFrame) } }) diff --git a/internal/renderer/frame.go b/internal/renderer/frame.go index f2d5d1d..893b1c6 100644 --- a/internal/renderer/frame.go +++ b/internal/renderer/frame.go @@ -33,7 +33,7 @@ type Frame struct { } var framePool = sync.Pool{ - New: func() interface{} { + New: func() any { return image.NewRGBA(image.Rect(0, 0, config.Width, config.Height)) }, } @@ -54,7 +54,7 @@ func NewFrame(bgImage *image.RGBA, fontFace font.Face, episodeNum int, title str // Pre-compute intensity gradient table (0.5 to 1.0 range for opaque gradient) // This creates a fade from dim at tips to bright at center without alpha blending intensityTable := make([]uint8, maxBarHeight) - for i := 0; i < maxBarHeight; i++ { + for i := range maxBarHeight { distanceFromCenter := float64(i) / float64(maxBarHeight) intensityFactor := 1.0 - (distanceFromCenter * 0.5) // 0.5 at tips, 1.0 at center intensityTable[i] = uint8(intensityFactor * 255) @@ -63,7 +63,7 @@ func NewFrame(bgImage *image.RGBA, fontFace font.Face, episodeNum int, title str // Pre-compute bar colors at different intensity levels (0-255) // Colors are fully opaque - RGB values dimmed by intensity, alpha always 255 barColorTable := make([][3]uint8, 256) - for intensity := 0; intensity < 256; intensity++ { + for intensity := range 256 { factor := float64(intensity) / 255.0 barColorTable[intensity][0] = uint8(float64(barR) * factor) barColorTable[intensity][1] = uint8(float64(barG) * factor) @@ -72,7 +72,7 @@ func NewFrame(bgImage *image.RGBA, fontFace font.Face, episodeNum int, title str // Pre-render framing line pattern (text color from config) framingLineData := make([]byte, totalWidth*4) - for px := 0; px < totalWidth; px++ { + for px := range totalWidth { offset := px * 4 framingLineData[offset] = textR // R framingLineData[offset+1] = textG // G @@ -151,7 +151,7 @@ func (f *Frame) drawBars(barHeights []float64) { // Render only left half (bars 0-31), upward only halfBars := config.NumBars / 2 - for i := 0; i < halfBars; i++ { + for i := range halfBars { barHeight := int(barHeights[i]) if barHeight <= 0 { continue @@ -178,7 +178,7 @@ func (f *Frame) drawBars(barHeights []float64) { // 1. Vertical mirror: bars 0-31 upward → bars 0-31 downward // 2. Horizontal mirror: bars 0-31 upward → bars 32-63 upward // 3. Both mirrors: bars 0-31 upward → bars 32-63 downward - for i := 0; i < halfBars; i++ { + for i := range halfBars { barHeight := int(barHeights[i]) if barHeight <= 0 { continue @@ -218,7 +218,7 @@ func (f *Frame) renderBar(x, yStart, yEnd, barHeight int, pixelPattern []byte) { colors := &f.barColorTable[intensity] // Fill pixel pattern once for this scanline - for px := 0; px < config.BarWidth; px++ { + for px := range config.BarWidth { offset := px * 4 pixelPattern[offset] = colors[0] pixelPattern[offset+1] = colors[1] @@ -239,7 +239,7 @@ func (f *Frame) mirrorBarVertical(x, yStart, yEnd int) { downStart := f.centerY + config.CenterGap/2 // Copy each scanline from upward bar in reverse order - for i := 0; i < upwardHeight; i++ { + for i := range upwardHeight { srcY := yEnd - 1 - i // Read from bottom of upward bar dstY := downStart + i // Write to top of downward bar diff --git a/internal/renderer/frame_bench_test.go b/internal/renderer/frame_bench_test.go index a534291..c2914ad 100644 --- a/internal/renderer/frame_bench_test.go +++ b/internal/renderer/frame_bench_test.go @@ -72,8 +72,8 @@ func BenchmarkFrameWithText(b *testing.B) { func TestFrameRendering(t *testing.T) { bgImage := image.NewRGBA(image.Rect(0, 0, config.Width, config.Height)) // Fill with a simple pattern - for y := 0; y < config.Height; y++ { - for x := 0; x < config.Width; x++ { + for y := range config.Height { + for x := range config.Width { offset := y*bgImage.Stride + x*4 bgImage.Pix[offset] = uint8(x % 256) bgImage.Pix[offset+1] = uint8(y % 256) diff --git a/internal/renderer/thumbnail.go b/internal/renderer/thumbnail.go index 0f0ce9c..1a374e1 100644 --- a/internal/renderer/thumbnail.go +++ b/internal/renderer/thumbnail.go @@ -206,9 +206,7 @@ func drawThumbnailText(img *image.RGBA, face font.Face, line1, line2 string, run // Calculate total text block dimensions maxWidth := width1 - if width2 > maxWidth { - maxWidth = width2 - } + maxWidth = max(maxWidth, width2) totalHeight := height1 + lineSpacing + height2 // Create a temporary image for drawing text (larger to accommodate rotation) diff --git a/internal/ui/preview.go b/internal/ui/preview.go index 5ededff..a33b3b6 100644 --- a/internal/ui/preview.go +++ b/internal/ui/preview.go @@ -66,9 +66,9 @@ func DownsampleFrame(frame *image.RGBA, config PreviewConfig) [][]color.RGBA { // Calculate average RGB values if pixelCount > 0 { preview[row][col] = color.RGBA{ - R: uint8(sumR / pixelCount), - G: uint8(sumG / pixelCount), - B: uint8(sumB / pixelCount), + R: uint8(sumR / pixelCount), //nolint:gosec // average of uint8 values fits in uint8 + G: uint8(sumG / pixelCount), //nolint:gosec // average of uint8 values fits in uint8 + B: uint8(sumB / pixelCount), //nolint:gosec // average of uint8 values fits in uint8 A: 255, } } @@ -131,26 +131,18 @@ func appendInt(buf []byte, n int) []byte { } // Handle numbers up to 255 (max RGB value) - if n >= 100 { - buf = append(buf, byte('0'+n/100)) + switch { + case n >= 100: + buf = append(buf, byte('0'+n/100)) //nolint:gosec // n/100 is 1 or 2 for values 0-255 n %= 100 buf = append(buf, byte('0'+n/10)) buf = append(buf, byte('0'+n%10)) - } else if n >= 10 { + case n >= 10: buf = append(buf, byte('0'+n/10)) buf = append(buf, byte('0'+n%10)) - } else { - buf = append(buf, byte('0'+n)) + default: + buf = append(buf, byte('0'+n)) //nolint:gosec // n is 0-9 here } return buf } - -// repeat creates a string by repeating s n times -func repeat(s string, n int) string { - result := "" - for i := 0; i < n; i++ { - result += s - } - return result -} diff --git a/internal/ui/progress.go b/internal/ui/progress.go index 820082c..be95364 100644 --- a/internal/ui/progress.go +++ b/internal/ui/progress.go @@ -20,9 +20,6 @@ var ( fireRed = cli.FireRed fireCrimson = cli.FireCrimson warmGray = cli.WarmGray - - // UI-specific colours - emberGlow = lipgloss.Color("#8B0000") // Dark ember red ) // Phase represents the current processing phase @@ -345,22 +342,23 @@ func (m *Model) renderProgress() string { } func (m *Model) renderAnalysisProgress(s *strings.Builder) { - if m.analysisProgress.TotalFrames > 0 { + switch { + case m.analysisProgress.TotalFrames > 0: // We have frame count, show progress bar percent := float64(m.analysisProgress.Frame) / float64(m.analysisProgress.TotalFrames) progressBar := m.progressBar.ViewAs(percent) s.WriteString("Progress: ") s.WriteString(progressBar) - s.WriteString(fmt.Sprintf(" %d%%", int(percent*100))) + fmt.Fprintf(s, " %d%%", int(percent*100)) s.WriteString("\n\n") - } else if m.analysisProgress.Frame > 0 { + case m.analysisProgress.Frame > 0: // No total, show frame count with elapsed time s.WriteString(lipgloss.NewStyle().Faint(true).Render("Analysing...")) - s.WriteString(fmt.Sprintf(" %d frames │ Elapsed: %s\n\n", + fmt.Fprintf(s, " %d frames │ Elapsed: %s\n\n", m.analysisProgress.Frame, - formatDuration(m.analysisProgress.Duration))) - } else { + formatDuration(m.analysisProgress.Duration)) + default: s.WriteString(lipgloss.NewStyle().Faint(true).Render("Starting analysis...\n\n")) } } @@ -378,7 +376,7 @@ func (m *Model) renderRenderingProgress(s *strings.Builder) { progressBar := m.progressBar.ViewAs(percent) s.WriteString("Progress: ") s.WriteString(progressBar) - s.WriteString(fmt.Sprintf(" %d%%", int(percent*100))) + fmt.Fprintf(s, " %d%%", int(percent*100)) s.WriteString("\n\n") // Timing information @@ -515,24 +513,24 @@ func (m *Model) renderComplete() string { dimLabel := lipgloss.NewStyle().Faint(true) // Output summary - s.WriteString(fmt.Sprintf("%s%s\n", dimLabel.Render("Output: "), m.complete.OutputFile)) + fmt.Fprintf(&s, "%s%s\n", dimLabel.Render("Output: "), m.complete.OutputFile) if m.complete.EncoderName != "" { - s.WriteString(fmt.Sprintf("%s%s\n", dimLabel.Render("Encoder: "), m.complete.EncoderName)) + fmt.Fprintf(&s, "%s%s\n", dimLabel.Render("Encoder: "), m.complete.EncoderName) } videoDuration := time.Duration(m.complete.TotalFrames) * time.Second / 30 - s.WriteString(fmt.Sprintf("%s%d frames, %.2f fps average\n", + fmt.Fprintf(&s, "%s%d frames, %.2f fps average\n", dimLabel.Render("Video: "), m.complete.TotalFrames, - float64(m.complete.TotalFrames)/videoDuration.Seconds())) + float64(m.complete.TotalFrames)/videoDuration.Seconds()) if m.complete.SamplesProcessed > 0 { - s.WriteString(fmt.Sprintf("%s%d samples processed\n", dimLabel.Render("Audio: "), m.complete.SamplesProcessed)) + fmt.Fprintf(&s, "%s%d samples processed\n", dimLabel.Render("Audio: "), m.complete.SamplesProcessed) } - s.WriteString(fmt.Sprintf("%s%.1fs video in %.1fs\n", + fmt.Fprintf(&s, "%s%.1fs video in %.1fs\n", dimLabel.Render("Duration: "), videoDuration.Seconds(), - m.complete.TotalTime.Seconds())) - s.WriteString(fmt.Sprintf("%s%s\n\n", dimLabel.Render("Size: "), formatBytes(m.complete.FileSize))) + m.complete.TotalTime.Seconds()) + fmt.Fprintf(&s, "%s%s\n\n", dimLabel.Render("Size: "), formatBytes(m.complete.FileSize)) // Audio Profile section headerStyle := lipgloss.NewStyle().Bold(true).Foreground(fireOrange) @@ -544,12 +542,12 @@ func (m *Model) renderComplete() string { s.WriteString("\n") if m.audioProfile != nil { - s.WriteString(fmt.Sprintf(" %s%s\n", labelStyle.Render(fmt.Sprintf("%-18s", "Duration:")), valueStyle.Render(fmt.Sprintf("%.1fs", m.audioProfile.Duration.Seconds())))) - s.WriteString(fmt.Sprintf(" %s%s\n", labelStyle.Render(fmt.Sprintf("%-18s", "Peak Level:")), valueStyle.Render(fmt.Sprintf("%.1f dB", m.audioProfile.PeakLevel)))) - s.WriteString(fmt.Sprintf(" %s%s\n", labelStyle.Render(fmt.Sprintf("%-18s", "RMS Level:")), valueStyle.Render(fmt.Sprintf("%.1f dB", m.audioProfile.RMSLevel)))) - s.WriteString(fmt.Sprintf(" %s%s\n", labelStyle.Render(fmt.Sprintf("%-18s", "Dynamic Range:")), valueStyle.Render(fmt.Sprintf("%.1f dB", m.audioProfile.DynamicRange)))) - s.WriteString(fmt.Sprintf(" %s%s\n", labelStyle.Render(fmt.Sprintf("%-18s", "Optimal Scale:")), valueStyle.Render(fmt.Sprintf("%.3f", m.audioProfile.OptimalScale)))) - s.WriteString(fmt.Sprintf(" %s%s\n", labelStyle.Render(fmt.Sprintf("%-18s", "Analysis Time:")), highlightValueStyle.Render(formatDuration(m.audioProfile.AnalysisTime)))) + fmt.Fprintf(&s, " %s%s\n", labelStyle.Render(fmt.Sprintf("%-18s", "Duration:")), valueStyle.Render(fmt.Sprintf("%.1fs", m.audioProfile.Duration.Seconds()))) + fmt.Fprintf(&s, " %s%s\n", labelStyle.Render(fmt.Sprintf("%-18s", "Peak Level:")), valueStyle.Render(fmt.Sprintf("%.1f dB", m.audioProfile.PeakLevel))) + fmt.Fprintf(&s, " %s%s\n", labelStyle.Render(fmt.Sprintf("%-18s", "RMS Level:")), valueStyle.Render(fmt.Sprintf("%.1f dB", m.audioProfile.RMSLevel))) + fmt.Fprintf(&s, " %s%s\n", labelStyle.Render(fmt.Sprintf("%-18s", "Dynamic Range:")), valueStyle.Render(fmt.Sprintf("%.1f dB", m.audioProfile.DynamicRange))) + fmt.Fprintf(&s, " %s%s\n", labelStyle.Render(fmt.Sprintf("%-18s", "Optimal Scale:")), valueStyle.Render(fmt.Sprintf("%.3f", m.audioProfile.OptimalScale))) + fmt.Fprintf(&s, " %s%s\n", labelStyle.Render(fmt.Sprintf("%-18s", "Analysis Time:")), highlightValueStyle.Render(formatDuration(m.audioProfile.AnalysisTime))) } s.WriteString("\n") @@ -564,31 +562,31 @@ func (m *Model) renderComplete() string { } if m.complete.ThumbnailTime > 0 { - s.WriteString(fmt.Sprintf(" %s%s (~%2d%%) %s\n", + fmt.Fprintf(&s, " %s%s (~%2d%%) %s\n", labelStyle.Render(fmt.Sprintf("%-18s", "Thumbnail:")), valueStyle.Render(fmt.Sprintf("~%-6s", formatDuration(m.complete.ThumbnailTime))), int(float64(m.complete.ThumbnailTime.Milliseconds())*100/float64(totalMs)), - m.summaryBar.ViewAs(float64(m.complete.ThumbnailTime.Milliseconds())/float64(totalMs)))) + m.summaryBar.ViewAs(float64(m.complete.ThumbnailTime.Milliseconds())/float64(totalMs))) } - s.WriteString(fmt.Sprintf(" %s%s (~%2d%%) %s\n", + fmt.Fprintf(&s, " %s%s (~%2d%%) %s\n", labelStyle.Render(fmt.Sprintf("%-18s", "Visualisation:")), valueStyle.Render(fmt.Sprintf("~%-6s", formatDuration(m.complete.VisTime))), int(float64(m.complete.VisTime.Milliseconds())*100/float64(totalMs)), - m.summaryBar.ViewAs(float64(m.complete.VisTime.Milliseconds())/float64(totalMs)))) + m.summaryBar.ViewAs(float64(m.complete.VisTime.Milliseconds())/float64(totalMs))) - s.WriteString(fmt.Sprintf(" %s%s (~%2d%%) %s\n", + fmt.Fprintf(&s, " %s%s (~%2d%%) %s\n", labelStyle.Render(fmt.Sprintf("%-18s", "Video encoding:")), valueStyle.Render(fmt.Sprintf("~%-6s", formatDuration(m.complete.EncodeTime))), int(float64(m.complete.EncodeTime.Milliseconds())*100/float64(totalMs)), - m.summaryBar.ViewAs(float64(m.complete.EncodeTime.Milliseconds())/float64(totalMs)))) + m.summaryBar.ViewAs(float64(m.complete.EncodeTime.Milliseconds())/float64(totalMs))) if m.complete.AudioTime > 0 { - s.WriteString(fmt.Sprintf(" %s%s (~%2d%%) %s\n", + fmt.Fprintf(&s, " %s%s (~%2d%%) %s\n", labelStyle.Render(fmt.Sprintf("%-18s", "Audio encoding:")), valueStyle.Render(fmt.Sprintf("~%-6s", formatDuration(m.complete.AudioTime))), int(float64(m.complete.AudioTime.Milliseconds())*100/float64(totalMs)), - m.summaryBar.ViewAs(float64(m.complete.AudioTime.Milliseconds())/float64(totalMs)))) + m.summaryBar.ViewAs(float64(m.complete.AudioTime.Milliseconds())/float64(totalMs))) } // Calculate unaccounted time including finalisation (Pass 2 only) @@ -607,14 +605,14 @@ func (m *Model) renderComplete() string { strings.Contains(m.complete.EncoderName, "videotoolbox") { otherLabel = "GPU pipeline:" } - s.WriteString(fmt.Sprintf(" %s%s (~%2d%%) %s\n", + fmt.Fprintf(&s, " %s%s (~%2d%%) %s\n", labelStyle.Render(fmt.Sprintf("%-18s", otherLabel)), valueStyle.Render(fmt.Sprintf("~%-6s", formatDuration(otherTime))), int(float64(otherTime.Milliseconds())*100/float64(totalMs)), - m.summaryBar.ViewAs(float64(otherTime.Milliseconds())/float64(totalMs)))) + m.summaryBar.ViewAs(float64(otherTime.Milliseconds())/float64(totalMs))) } - s.WriteString(fmt.Sprintf(" %s%s", labelStyle.Render(fmt.Sprintf("%-18s", "Total time:")), highlightValueStyle.Render(formatDuration(m.complete.TotalTime)))) + fmt.Fprintf(&s, " %s%s", labelStyle.Render(fmt.Sprintf("%-18s", "Total time:")), highlightValueStyle.Render(formatDuration(m.complete.TotalTime))) return lipgloss.NewStyle(). BorderStyle(lipgloss.RoundedBorder()). @@ -755,17 +753,10 @@ func renderSpectrum(barHeights []float64, width int) string { } styledBlock := lipgloss.NewStyle(). - Foreground(fireColors[colorIdx]). + Foreground(fireColors[colorIdx]). //nolint:gosec // bounds checked above Render(string(blocks[blockIdx])) result.WriteString(styledBlock) } return result.String() } - -func min(a, b int) int { - if a < b { - return a - } - return b -} diff --git a/justfile b/justfile index 1f59357..71f386c 100644 --- a/justfile +++ b/justfile @@ -241,6 +241,14 @@ test-encoder: build ./jivefire --episode="01" --title "Linux Matters: wav (mono)" testdata/LMP0.wav testdata/LMP0-wav.mp4 ./jivefire --no-preview --episode="02" --title "Linux Matters: wav (stereo)" testdata/LMP0-stereo.wav testdata/LMP0-wav-stereo.mp4 +# Run linters +lint: + @go vet ./... + @gocyclo -top 20 -avg -ignore '_test\.go$' . + @ineffassign ./... + @golangci-lint run + @actionlint + # Run tests test: _check-submodule go test ./...