Full Code of asciinema/asciinema for AI

develop 202d5c576168 cached
70 files
371.0 KB
98.8k tokens
507 symbols
1 requests
Download .txt
Showing preview only (390K chars total). Download the full file or copy to clipboard to get everything.
Repository: asciinema/asciinema
Branch: develop
Commit: 202d5c576168
Files: 70
Total size: 371.0 KB

Directory structure:
gitextract_57n0_umc/

├── .cargo/
│   └── config.toml
├── .gitattributes
├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug-report.yml
│   │   └── config.yml
│   └── workflows/
│       ├── ci.yml
│       └── release.yml
├── .gitignore
├── CHANGELOG.md
├── CONTRIBUTING.md
├── Cargo.toml
├── Dockerfile
├── LICENSE
├── README.md
├── assets/
│   ├── asciinema-player.css
│   └── index.html
├── build.rs
├── default.nix
├── flake.nix
├── shell.nix
├── src/
│   ├── alis.rs
│   ├── api.rs
│   ├── asciicast/
│   │   ├── util.rs
│   │   ├── v1.rs
│   │   ├── v2.rs
│   │   └── v3.rs
│   ├── asciicast.rs
│   ├── cli.rs
│   ├── cmd/
│   │   ├── auth.rs
│   │   ├── cat.rs
│   │   ├── convert.rs
│   │   ├── mod.rs
│   │   ├── play.rs
│   │   ├── session.rs
│   │   └── upload.rs
│   ├── config.rs
│   ├── encoder/
│   │   ├── asciicast.rs
│   │   ├── mod.rs
│   │   ├── raw.rs
│   │   └── txt.rs
│   ├── fd.rs
│   ├── file_writer.rs
│   ├── forwarder.rs
│   ├── hash.rs
│   ├── html.rs
│   ├── leb128.rs
│   ├── locale.rs
│   ├── main.rs
│   ├── notifier.rs
│   ├── player.rs
│   ├── pty.rs
│   ├── server.rs
│   ├── session.rs
│   ├── status.rs
│   ├── stream.rs
│   ├── tty/
│   │   ├── default.rs
│   │   ├── inspect.rs
│   │   └── macos.rs
│   ├── tty.rs
│   └── util.rs
└── tests/
    ├── casts/
    │   ├── demo.cast
    │   ├── demo.json
    │   ├── full-v1.json
    │   ├── full-v2.cast
    │   ├── full-v3.cast
    │   ├── minimal-v1.json
    │   ├── minimal-v2.cast
    │   ├── minimal-v3.cast
    │   ├── nulls-v1.json
    │   └── nulls-v2.cast
    └── integration.sh

================================================
FILE CONTENTS
================================================

================================================
FILE: .cargo/config.toml
================================================
[env]
RUST_TEST_THREADS = "1"


================================================
FILE: .gitattributes
================================================
assets/asciinema-player.* linguist-vendored


================================================
FILE: .github/ISSUE_TEMPLATE/bug-report.yml
================================================
name: Bug Report
description: Report a bug to help improve asciinema CLI
body:
  - type: markdown
    attributes:
      value: |
        **This is a bug tracker for asciinema CLI (the recorder).**
        
        - If your issue is with the JavaScript player or server, please open an issue in the related repository
        - If you're experiencing issues with asciinema.org, contact admin@asciinema.org
        - For feature requests, questions, and discussions, use the [forum](https://discourse.asciinema.org) or [GitHub discussions](https://github.com/orgs/asciinema/discussions)
        
        Thanks for taking the time to report a bug! Please fill out the sections below.

  - type: checkboxes
    id: checks
    attributes:
      label: Pre-submission checks
      description: Please confirm the following before submitting your bug report
      options:
        - label: I have searched existing issues and this bug has not been reported yet
          required: true
        - label: This is a bug report for asciinema CLI (not player or server)
          required: true

  - type: textarea
    id: bug-description
    attributes:
      label: Bug Description
      description: A clear and concise description of what the bug is.
      placeholder: Describe the bug...
    validations:
      required: true

  - type: textarea
    id: reproduction-steps
    attributes:
      label: Steps to Reproduce
      description: Provide detailed steps to reproduce the behavior
      placeholder: |
        1. Run command `asciinema ...`
        2. Do action '...'
        3. Observe error
    validations:
      required: true

  - type: textarea
    id: expected-behavior
    attributes:
      label: Expected Behavior
      description: A clear and concise description of what you expected to happen.
      placeholder: What should have happened instead?
    validations:
      required: true

  - type: input
    id: os-version
    attributes:
      label: Operating System
      description: Which OS and version are you using?
      placeholder: e.g., Ubuntu 24.04, macOS 14.0, Fedora 39
    validations:
      required: true

  - type: input
    id: cli-version
    attributes:
      label: asciinema CLI Version
      description: What version of asciinema CLI are you using? Run `asciinema --version` to check.
      placeholder: e.g., 2.4.0
    validations:
      required: true

  - type: dropdown
    id: installation-method
    attributes:
      label: Installation Method
      description: How did you install asciinema CLI?
      options:
        - Package manager (apt, yum, brew, etc.)
        - pip/pipx
        - Built from source
        - Downloaded binary
        - Other
    validations:
      required: true

  - type: textarea
    id: terminal-info
    attributes:
      label: Terminal Information
      description: What terminal emulator and shell are you using?
      placeholder: |
        Terminal: e.g., GNOME Terminal, iTerm2, Ghostty
        Shell: e.g., bash 5.1, zsh 5.8, fish 3.6

  - type: textarea
    id: additional-context
    attributes:
      label: Additional Context
      description: Add any other context, screenshots, or relevant information about the problem here.


================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: false
contact_links:
  - name: Forum
    url: https://discourse.asciinema.org/
    about: Ideas, feature requests, help requests, questions and general discussions should be posted here.
  - name: GitHub discussions
    url: https://github.com/orgs/asciinema/discussions
    about: Ideas, feature requests, help requests, questions and general discussions should be posted here.


================================================
FILE: .github/workflows/ci.yml
================================================
name: CI

on:
  push:
    branches: ["develop"]
  pull_request:
    branches: ["develop"]

env:
  CARGO_TERM_COLOR: always

jobs:
  build:
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [ubuntu-latest, macos-latest]
        rust: [default, msrv]

    steps:
      - uses: actions/checkout@v5

      - name: Install Nix
        uses: nixbuild/nix-quick-install-action@v34

      - name: Setup Nix cache
        uses: nix-community/cache-nix-action@v6
        with:
          primary-key: nix-${{ runner.os }}-${{ matrix.rust }}-${{ hashFiles('**/*.nix', '**/flake.lock') }}
          restore-prefixes-first-match: nix-${{ runner.os }}-${{ matrix.rust }}-

      - name: Build
        run: nix develop .#${{ matrix.rust }} --command cargo build --verbose

      - name: Run cargo tests
        run: nix develop .#${{ matrix.rust }} --command cargo test --verbose

      - name: Run integration tests
        run: nix develop .#${{ matrix.rust }} --command tests/integration.sh

      - name: Check formatting
        run: nix develop .#${{ matrix.rust }} --command cargo fmt --check

      - name: Lint with clippy
        run: nix develop .#${{ matrix.rust }} --command cargo clippy


================================================
FILE: .github/workflows/release.yml
================================================
name: Release

permissions:
  contents: write

on:
  push:
    tags:
      - v[0-9]+.*

jobs:
  create-release:
    name: Create GH release draft
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v5

      - name: Create the release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: gh release create ${{ github.ref_name }} --draft --verify-tag --title ${{ github.ref_name }}

  upload-binary:
    needs: create-release
    name: ${{ matrix.target }}
    runs-on: ${{ matrix.os }}

    strategy:
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
            use-cross: false

          - os: ubuntu-latest
            target: x86_64-unknown-linux-musl
            use-cross: false

          - os: ubuntu-latest
            target: aarch64-unknown-linux-gnu
            use-cross: true

          - os: macos-latest
            target: x86_64-apple-darwin
            use-cross: false

          - os: macos-latest
            target: aarch64-apple-darwin
            use-cross: false

    env:
      CARGO: cargo

    steps:
      - uses: actions/checkout@v5

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}

      - name: Install cross
        if: matrix.use-cross
        uses: taiki-e/install-action@v2
        with:
          tool: cross

      - name: Overwrite build command env variable
        if: matrix.use-cross
        shell: bash
        run: echo "CARGO=cross" >> $GITHUB_ENV

      - name: Install build deps
        shell: bash
        run: |
          if [[ ${{ matrix.target }} == x86_64-unknown-linux-musl ]]; then
              sudo apt-get update
              sudo apt-get install -y musl-tools
          fi

      - name: Build release binary
        run: ${{ env.CARGO }} build --release --locked --target ${{ matrix.target }}

      - name: Upload the binary to the release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          mv target/${{ matrix.target }}/release/asciinema target/release/asciinema-${{ matrix.target }}
          gh release upload ${{ github.ref_name }} target/release/asciinema-${{ matrix.target }}


================================================
FILE: .gitignore
================================================
target/
.envrc
.direnv
/result


================================================
FILE: CHANGELOG.md
================================================
# asciinema changelog

## 3.2.0 (2026-03-01)

* Improved querying for terminal theme and version
* Added support for playback from stdin (thanks @fopina!)
* Improved implementation of ALiS protocol
* Switched from full jitter to equal jitter when timing stream reconnection attempts
* Added `--description`, `--visibility`, `--audio-url` options for `stream` and `session` commands (thanks @hh!)
* Added `--title`, `--description`, `--visibility`, `--audio-url` options for `upload` command
* Fixed key bindings parsing (regression from 2.x) (#720)
* Upgraded the embedded player to the latest version

## 3.1.0 (2026-01-14)

* Implemented caching and compression for static assets served by the built-in
  HTTP server in the local streaming mode (`asciinema stream -l`)
* Enabled Nerd Font symbols in the embedded player when streaming locally
* Upgraded the embedded player to the latest version
* Upgraded the virtual terminal (avt) to the latest version

## 3.0.1 (2025-10-24)

* Fixed reading of asciicasts v1 and v2 having null env values in header
* Fixed the license identifier in cargo package
* Fixed Dockerfile
* Upgraded embedded player to the latest version
* Enabled Link-Time Optimization (LTO) and codegen-units=1 for release build - smaller binary size
* Cleaned up nix flake

## 3.0.0 (2025-09-15)

This is a complete rewrite of asciinema in Rust, upgrading the recording file
format, introducing terminal live streaming, and bringing numerous improvements
across the board.

### New features

* New `stream` command for terminal live streaming, providing local mode
  (built-in HTTP server) and remote mode (relaying via asciinema server, more
  about it [here](https://docs.asciinema.org/manual/server/streaming/))
* New `session` command for simultaneous recording and streaming
* New `convert` command for format conversion between asciicast versions or
  exporting to plain text log / raw output
* New [asciicast v3 file
  format](https://docs.asciinema.org/manual/asciicast/v3/) as the new default
  output format
* Terminal theme capture - terminal colors are now automatically captured and
  saved in recordings
* New output format - plain text log - use `.txt` extension for the output
  filename or select explicitly with `--output-format txt`
* `rec`: New `--return` option for propagating session exit status
* `rec`: Session exit status is now saved as "x" (exit) event in asciicast v3
  recordings
* `rec`: Parent directories are automatically created when recording to
  non-existing paths
* `rec`: Terminal version (XTVERSION OSC query) is now saved in asciicast
  header as `term.version`
* `rec`: New `--headless` option for forcing headless mode
* `rec`: New `--log-file` option for enabling logging, e.g. for troubleshooting
  I/O errors
* `play`: New `--resize` option for enabling terminal auto-resize during playback (terminal support varies)
* New `--server-url` option for setting custom server URL (for self-hosted
  servers), as an alternative to config file and `ASCIINEMA_SERVER_URL`
  environment variable
* New system-wide configuration file `/etc/asciinema/config.toml` for setting
  defaults for all users
* Command name prefix matching - you can use `asciinema r` instead of
  `asciinema rec`, `asciinema u` instead of `asciinema upload`, etc.
* tmux status bar is now used for notifications when tmux session is detected
  and no other desktop notification mechanism is available

### Improvements

* Prompt for setting up default asciinema server URL on first use, unless one
  is configured upfront
* Comprehensive `--help` messages (vs concise `-h`), with examples for each
  subcommand
* Complete set of man pages and shell auto-completion files can be generated
  during build (see README.md)
* `rec`: Fixed saving of custom record command (`--command`) value in asciicast
  header
* `rec`: `--append` option can now be used with `--format raw`
* `upload`: Recording file is validated for correctness/formatting before upload
* Better error message when non-UTF-8 locale is detected


### Breaking changes

* `rec`: Filename argument is now required, use explicit `upload` command for
  publishing a local recording
* `rec`: Default output format is now asciicast v3 instead of v2 - asciinema
  server and player support it already, but be aware of this if you're using
  custom tooling - use `--output-format asciicast-v2` for backward compatibility
* `rec`: `--stdin` option has been renamed to `--capture-input` / `-I` for
  clarity
* `rec`: `--env` option has been renamed to `--capture-env`, short `-e` variant
  has been removed
* `rec`: `--cols` and `--rows` options have been replaced with single
  `--window-size COLSxROWS` option
* `rec`: `--raw` option has been removed, superceded by `--output-format raw`
* `rec`: `--yes` / `-y` option has been removed since there's no upload
  confirmation anymore
* `rec`: Using both `--append` and `--overwrite` options together now produces
  an immediate error instead of silently ignoring one option
* `cat`: This command now concatenates multiple recordings instead of dumping
  raw output - use `convert --output-format raw` for 2.x behavior
* `play`: `--out-fmt` and `--stream` options have been removed
* User configuration file changed format from "ini-style" to TOML, and moved
  from `~/.config/asciinema/config` to `~/.config/asciinema/config.toml` - check
  [configuration docs](https://docs.asciinema.org/manual/cli/configuration/) for
  details
* Removed built-in support for desktop notifications via terminal-notifier in
  favor of AppleScript on macOS

### Other changes

* Install ID location changed from `XDG_CONFIG_HOME/asciinema/install-id`
  (`$HOME/.config/asciinema`) to `XDG_STATE_HOME/asciinema/install-id`
  (`$HOME/.local/state/asciinema`) - for backward compatibility the previous
  location is still used if the file already exists there
* `ASCIINEMA_REC` environment variable, which was set to `1` for sessions
  started with `asciinema rec`, has been superceded by `ASCIINEMA_SESSION`, which
  is set to a unique session ID by `rec`, `stream` and `session` commands - the
  original `ASCIINEMA_REC=1` is still set by `rec` command for backward
  compatibility
* `ASCIINEMA_API_URL` environment variable has been superceded by
  `ASCIINEMA_SERVER_URL` for setting custom server URL - the original
  `ASCIINEMA_API_URL` still works but is deprecated

## 2.4.0 (2023-10-23)

* When recording without file arg we now ask whether to save, upload or discard the recording (#576)
* Added capture of terminal resize events (#565)
* Fixed blocking write error when PTY master is not ready (#569) (thanks @Low-power!)
* Fixed "broken pipe" errors when piping certain commands during recording (#369) (thanks @Low-power!)
* Fixed crash during playback of cast files with trailing blank line (#577)

## 2.3.0 (2023-07-05)

* Added official support for Python 3.11
* Dropped official support for Python 3.6
* Implemented markers in `rec` and `play -m` commands
* Added `--loop` option for looped playback in `play` command
* Added `--stream` and `--out-fmt` option for customizing output of `play` command
* Improved terminal charset detection (thanks @djds)
* Extended `cat` command to support multiple files (thanks @Low-power)
* Improved upload error messages
* Fixed direct playback from URL
* Made raw output start with terminal size sequence (`\e[8;H;Wt`)
* Prevented recording to stdout when it's a TTY
* Added target file permission checks to avoid ugly errors
* Removed named pipe re-opening, which was causing hangs in certain scenarios
* Improved PTY/TTY data reading - it goes in bigger chunks now (256 kb)
* Fixed deadlock in PTY writes (thanks @Low-power)
* Improved input forwarding from stdin
* Ignored OSC responses in recorded stdin stream

## 2.2.0 (2022-05-07)

* Added official support for Python 3.8, 3.9, 3.10
* Dropped official support for Python 3.5
* Added `--cols` / `--rows` options for overriding size of pseudo-terminal reported to recorded program
* Improved behaviour of `--append` when output file doesn't exist
* Keyboard input is now explicitly read from a TTY device in addition to stdin (when stdin != TTY)
* Recorded program output is now explicitly written to a TTY device instead of stdout
* Dash char (`-`) can now be passed as output filename to write asciicast to stdout
* Diagnostic messages are now printed to stderr (without colors when stderr != TTY)
* Improved robustness of writing asciicast to named pipes
* Lots of codebase modernizations (many thanks to Davis @djds Schirmer!)
* Many other internal refactorings

## 2.1.0 (2021-10-02)

* Ability to pause/resume terminal capture with `C-\` key shortcut
* Desktop notifications - only for the above pause feature at the moment
* Removed dependency on tput/ncurses (thanks @arp242 / Martin Tournoij!)
* ASCIINEMA_REC env var is back (thanks @landonb / Landon Bouma!)
* Terminal answerbacks (CSI 6 n) in `asciinema cat` are now hidden (thanks @djpohly / Devin J. Pohly!)
* Codeset detection works on HP-UX now (thanks @michael-o / Michael Osipov!)
* Attempt at recording to existing file suggests use of `--overwrite` option now
* Upload for users with very long `$USER` is fixed
* Added official support for Python 3.8 and 3.9
* Dropped official support for EOL-ed Python 3.4 and 3.5

## 2.0.2 (2019-01-12)

* Official support for Python 3.7
* Recording is now possible on US-ASCII locale (thanks Jean-Philippe @jpouellet Ouellet!)
* Improved Android support (thanks Fredrik @fornwall Fornwall!)
* Possibility of programatic recording with `asciinema.record_asciicast` function
* Uses new JSON response format added recently to asciinema-server
* Tweaked message about how to stop recording (thanks Bachynin @vanyakosmos Ivan!)
* Added proper description and other metadata to Python package (thanks @Crestwave!)

## 2.0.1 (2018-04-04)

* Fixed example in asciicast v2 format doc (thanks Josh "@anowlcalledjosh" Holland!)
* Replaced deprecated `encodestring` (since Python 3.1) with `encodebytes` (thanks @delirious-lettuce!)
* Fixed location of config dir (you can `mv ~/.asciinema ~/.config/asciinema`)
* Internal refactorings

## 2.0 (2018-02-10)

This major release brings many new features, improvements and bugfixes. The most
notable ones:

* new [asciicast v2 file format](doc/asciicast-v2.md)
* recording and playback of arbitrarily long session with minimal memory usage
* ability to live-stream via UNIX pipe: `asciinema rec unix.pipe` + `asciinema play unix.pipe` in second terminal tab/window
* optional stdin recording (`asciinema rec --stdin`)
* appending to existing recording (`asciinema rec --append <filename>`)
* raw recording mode, storing only stdout bytes (`asciinema rec --raw <filename>`)
* environment variable white-listing (`asciinema rec --env="VAR1,VAR2..."`)
* toggling pause in `asciinema play` by <kbd>Space</kbd>
* stepping through a recording one frame at a time with <kbd>.</kbd> (when playback paused)
* new `asciinema cat <filename>` command to dump full output of the recording
* playback from new IPFS URL scheme: `dweb:/ipfs/` (replaces `fs:/`)
* lots of other bugfixes and improvements
* dropped official support for Python 3.3 (although it still works on 3.3)

## 1.4.0 (2017-04-11)

* Dropped distutils fallback in setup.py - setuptools required now (thanks Jakub "@jakubjedelsky" Jedelsky!)
* Dropped official support for Python 3.2 (although it still works on 3.2)
* New `--speed` option for `asciinema play` (thanks Bastiaan "@bastiaanb" Bakker!)
* Ability to set API token via `ASCIINEMA_API_TOKEN` env variable (thanks Samantha "@samdmarshall" Marshall!)
* Improved shutdown on more signals: CHLD, HUP, TERM, QUIT (thanks Richard "@typerlc"!)
* Fixed stdin handling during playback via `asciinema play`

## 1.3.0 (2016-07-13)

This release brings back the original Python implementation of asciinema. It's
based on 0.9.8 codebase and adds all features and bug fixes that have been
implemented in asciinema's Go version between 0.9.8 and 1.2.0.

Other notable changes:

* Zero dependencies! (other than Python 3)
* Fixed crash when resizing terminal window during recording (#167)
* Fixed upload from IPv6 hosts (#94)
* Improved UTF-8 charset detection (#160)
* `-q/--quiet` option can be saved in config file now
* Final "logout" (produced by csh) is now removed from recorded stdout
* `rec` command now tries to write to target path before starting recording

## 1.2.0 (2016-02-22)

* Added playback from stdin: `cat demo.json | asciinema play -`
* Added playback from IPFS: `asciinema play ipfs:/ipfs/QmcdXYJp6e4zNuimuGeWPwNMHQdxuqWmKx7NhZofQ1nw2V`
* Added playback from asciicast page URL: `asciinema play https://asciinema.org/a/22124`
* `-q/--quiet` option added to `rec` command
* Fixed handling of partial UTF-8 sequences in recorded stdout
* Final "exit" is now removed from recorded stdout
* Longer operations like uploading/downloading show "spinner"

## 1.1.1 (2015-06-21)

* Fixed putting terminal in raw mode (fixes ctrl-o in nano)

## 1.1.0 (2015-05-25)

* `--max-wait` option is now also available for `play` command
* Added support for compilation on FreeBSD
* Improved locale/charset detection
* Improved upload error messages
* New config file location (with backwards compatibility)

## 1.0.0 (2015-03-12)

* `--max-wait` and `--yes` options can be saved in config file
* Support for displaying warning messages returned from API
* Also, see changes for 1.0.0 release candidates below

## 1.0.0.rc2 (2015-03-08)

* All dependencies are vendored now in Godeps dir
* Help message includes all commands with their possible options
* `-y` and `-t` options have longer alternatives: `--yes`, `--title`
* `--max-wait` option has shorter alternative: `-w`
* Import paths changed to `github.com/asciinema/asciinema` due to repository
  renaming
* `-y` also suppresess "please resize terminal" prompt

## 1.0.0.rc1 (2015-03-02)

* New [asciicast file format](doc/asciicast-v1.md)
* `rec` command can now record to file
* New commands: `play <filename>` and `upload <filename>`
* UTF-8 native locale is now required
* Added handling of status 413 and 422 by printing user friendly message

## 0.9.9 (2014-12-17)

* Rewritten in Go
* License changed to GPLv3
* `--max-wait` option added to `rec` command
* Recorded process has `ASCIINEMA_REC` env variable set (useful for "rec"
  indicator in shell's `$PROMPT/$RPROMPT`)
* No more terminal resetting (via `reset` command) before and after recording
* Informative messages are coloured to be distinguishable from normal output
* Improved error messages

## 0.9.8 (2014-02-09)

* Rename user_token to api_token
* Improvements to test suite
* Send User-Agent including client version number, python version and platform
* Handle 503 status as server maintenance
* Handle 404 response as a request for client upgrade

## 0.9.7 (2013-10-07)

* Depend on requests==1.1.0, not 2.0

## 0.9.6 (2013-10-06)

* Remove install script
* Introduce proper python package: https://pypi.python.org/pypi/asciinema
* Make the code compatible with both python 2 and 3
* Use requests lib instead of urrlib(2)

## 0.9.5 (2013-10-04)

* Fixed measurement of total recording time
* Improvements to install script
* Introduction of Homebrew formula

## 0.9.4 (2013-10-03)

* Use python2.7 in shebang

## 0.9.3 (2013-10-03)

* Re-enable resetting of a terminal before and after recording
* Add Arch Linux source package

## 0.9.2 (2013-10-02)

* Use os.uname over running the uname command
* Add basic integration tests
* Make PtyRecorder test stable again
* Move install script out of bin dir

## 0.9.1 (2013-10-01)

* Split monolithic script into separate classes/files
* Remove upload queue
* Use python2 in generated binary's shebang
* Delay config file creation until user_token is requested
* Introduce command classes for handling cli commands
* Split the recorder into classes with well defined responsibilities
* Drop curl dependency, use urllib(2) for http requests

## 0.9.0 (2013-09-24)

* Project rename from "ascii.io" to "asciinema"

## ... limbo? ...

## 0.1 (2012-03-11)

* Initial release


================================================
FILE: CONTRIBUTING.md
================================================
# Contributing to asciinema

First, if you're opening a GitHub issue make sure it goes to the correct
repository:

- [asciinema/asciinema](https://github.com/asciinema/asciinema/issues) - command-line recorder
- [asciinema/asciinema-server](https://github.com/asciinema/asciinema-server/issues) - public website hosting recordings
- [asciinema/asciinema-player](https://github.com/asciinema/asciinema-player/issues) - player

## Reporting bugs

Open an issue in GitHub issue tracker.

Tell us what's the problem and include steps to reproduce it (reliably).
Including your OS/browser/terminal name and version in the report would be
great.

## Submitting patches with bug fixes

If you found a bug and made a patch for it:

1. Make sure all tests pass. If you add new functionality, add new tests.
1. Send us a pull request, including a description of the fix (referencing an
   existing issue if there's one).

## Requesting new features

We welcome all ideas.

If you believe most asciinema users would benefit from implementing your idea
then feel free to open a GitHub issue. However, as this is an open-source
project maintained by a small team of volunteers we simply can't implement all
of them due to limited resources. Please keep that in mind.

## Proposing features/changes (pull requests)

If you want to propose code change, either introducing a new feature or
improving an existing one, please first discuss this with asciinema team. You
can simply open a separate issue for a discussion or join #asciinema IRC
channel on Libera.Chat.

## Reporting security issues

If you found a security issue in asciinema please contact us at
admin@asciinema.org. For the benefit of all asciinema users please **do
not** publish details of the vulnerability in a GitHub issue.


================================================
FILE: Cargo.toml
================================================
[package]
name = "asciinema"
version = "3.2.0"
edition = "2021"
authors = ["Marcin Kulik <m@ku1ik.com>"]
homepage = "https://asciinema.org"
repository = "https://github.com/asciinema/asciinema"
description = "Terminal session recorder, streamer, and player"
license = "GPL-3.0-or-later"

# MSRV
rust-version = "1.82.0"

[dependencies]
anyhow = "1.0"
nix = { version = "0.30", features = ["fs", "term", "process", "signal", "poll"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
clap = { version = "4.0", features = ["derive", "wrap_help"] }
signal-hook = { version = "0.3", default-features = false }
uuid = { version = "1.6", features = ["v4"] }
reqwest = { version = "0.12", default-features = false, features = ["blocking", "rustls-tls-native-roots", "multipart", "gzip", "json", "stream"] }
rustyline = { version = "17.0", default-features = false }
config = { version = "0.15", default-features = false, features = ["toml"] }
which = "8.0"
tempfile = "3.23"
avt = "0.17"
axum = { version = "0.8", default-features = false, features = ["http1", "ws"] }
tokio = { version = "1.40", features = ["rt-multi-thread", "net", "sync", "time", "fs", "process"] }
futures-util = { version = "0.3", default-features = false, features = ["sink"] }
tokio-stream = { version = "0.1", default-features = false, features = ["sync", "time"] }
rust-embed = "8.8"
tower-http = { version = "0.6", features = ["trace", "compression-gzip"] }
tracing = { version = "0.1", default-features = false }
tracing-subscriber = { version = "0.3.20", default-features = false, features = ["fmt", "env-filter"] }
rgb = { version = "0.8", default-features = false }
url = "2.5"
tokio-tungstenite = { version = "0.28", default-features = false, features = ["connect", "rustls-tls-native-roots"] }
rustls = { version = "0.23", default-features = false, features = ["ring"] }
tokio-util = { version = "0.7", features = ["rt"] }
rand = "0.9"
async-trait = "0.1"
signal-hook-tokio = { version = "0.3", features = ["futures-v0_3"] }
bytes = "1.11"

[build-dependencies]
clap = { version = "4.0", features = ["derive", "wrap_help"] }
clap_complete = "4.0"
clap_mangen = "0.2"
url = "2.5"

[profile.release]
strip = true
lto = true
codegen-units = 1

[profile.integration-test]
inherits = "release"
opt-level = 0
lto = false
codegen-units = 256
strip = "none"
incremental = true
debug-assertions = false
overflow-checks = false

[features]
macos-tty = []


================================================
FILE: Dockerfile
================================================
ARG RUST_VERSION=1.90.0
FROM rust:${RUST_VERSION}-slim-trixie AS builder
WORKDIR /app

RUN --mount=type=bind,source=src,target=src \
    --mount=type=bind,source=assets,target=assets \
    --mount=type=bind,source=build.rs,target=build.rs \
    --mount=type=bind,source=Cargo.toml,target=Cargo.toml \
    --mount=type=bind,source=Cargo.lock,target=Cargo.lock \
    --mount=type=cache,target=/app/target/ \
    --mount=type=cache,target=/usr/local/cargo/registry/ \
    <<EOF
set -e
cargo build --locked --release
cp ./target/release/asciinema /usr/local/bin/
EOF

FROM debian:trixie-slim AS run
COPY --from=builder /usr/local/bin/asciinema /usr/local/bin
ENTRYPOINT ["/usr/local/bin/asciinema"]


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.


================================================
FILE: README.md
================================================
# asciinema

[![Build Status](https://github.com/asciinema/asciinema/actions/workflows/ci.yml/badge.svg)](https://github.com/asciinema/asciinema/actions/workflows/asciinema.yml)
[![license](http://img.shields.io/badge/license-GNU-blue.svg)](https://raw.githubusercontent.com/asciinema/asciinema/master/LICENSE)

__asciinema__ (aka asciinema CLI or asciinema recorder) is a command-line tool
for recording and live streaming terminal sessions.

Unlike typical _screen_ recording software, which records visual output of a
screen into a heavyweight video files (`.mp4`, `.mov`), asciinema CLI runs
_inside a terminal_, capturing terminal session output into a lightweight
recording files in the
[asciicast](https://docs.asciinema.org/manual/asciicast/v3/) format (`.cast`),
or streaming it live to viewers in real-time.

The recordings can be replayed in a terminal, embedded on a web page with the
[asciinema player](https://docs.asciinema.org/manual/player/), or published to
an [asciinema server](https://docs.asciinema.org/manual/server/), such as
[asciinema.org](https://asciinema.org), for further sharing. Live streams allow
viewers to watch terminal sessions as they happen.

asciinema runs on GNU/Linux, macOS and FreeBSD.

<a href="https://asciinema.org/a/756853?autoplay=1"><img src="https://asciinema.org/a/756853.svg" alt="asciinema CLI demo" width="100%" /></a>

Notable features:

- recording and replaying of sessions inside a terminal,
- local and remote [live
  streaming](https://docs.asciinema.org/manual/cli/quick-start/#stream-a-terminal-session)
  of terminal sessions to multiple viewers in real-time,
- [lightweight recording
  format](https://docs.asciinema.org/manual/asciicast/v3/), which is highly
  compressible (down to 15% of the original size e.g. with `zstd` or `gzip`),
- integration with [asciinema
  server](https://docs.asciinema.org/manual/server/), e.g.
  [asciinema.org](https://asciinema.org), for easy recording hosting and live
  streaming.

To record a session run this command in your shell:

```sh
asciinema rec demo.cast
```

To stream a session via built-in HTTP server run:

```sh
asciinema stream -l
```

To stream a session via a relay (asciinema server) run:

```sh
asciinema stream -r
```

Check out the [Getting started
guide](https://docs.asciinema.org/getting-started/) for installation and usage
overview.

## Building

Building asciinema from source requires the [Rust](https://www.rust-lang.org/)
compiler (1.82 or later), and the [Cargo package
manager](https://doc.rust-lang.org/cargo/). If they are not available via your
system package manager then use [rustup](https://rustup.rs/).

To download the source code, build the asciinema binary, and install it in
`$HOME/.cargo/bin` in one go run:

```sh
cargo install --locked --git https://github.com/asciinema/asciinema
```

Then, ensure `$HOME/.cargo/bin` is in your shell's `$PATH`.

Alternatively, you can manually download the source code and build the asciinema
binary with:

```sh
git clone https://github.com/asciinema/asciinema
cd asciinema
cargo build --release
```

This produces the binary at `target/release/asciinema`. You can just copy the
binary to a directory in your `$PATH`.

To generate man pages and shell completion files, set `ASCIINEMA_GEN_DIR` to the
path where these artifacts should be stored. For example:

```sh
ASCIINEMA_GEN_DIR=/foo cargo build --release
```

The above command will build the binary and place the man pages in `/foo/man/`,
and the shell completion files in the `/foo/completion/` directory.

> [!NOTE]
> Windows is currently not supported. See [#467](https://github.com/orgs/asciinema/discussions/278).
> You can try [PowerSession](https://github.com/Watfaq/PowerSession-rs) instead.

## Development

All development happens on `develop` branch. This branch contains the current
generation (3.x) of the asciinema CLI, written in Rust.

The previous generation (2.x), written in Python, can be found in the `python`
branch.

If you wish to propose non-trivial code changes, please first reach out to the
team via [forum](https://discourse.asciinema.org/),
[Matrix](https://matrix.to/#/#asciinema:matrix.org) or
[IRC](https://web.libera.chat/#asciinema).

## Donations

Sustainability of asciinema development relies on donations and sponsorships.

If you like the project then consider becoming a
[supporter](https://docs.asciinema.org/donations/#individuals) or a [corporate
sponsor](https://docs.asciinema.org/donations/#corporate-sponsorship).

asciinema is sponsored by:

- [Brightbox](https://www.brightbox.com/)

## Consulting

If you're interested in integration or customization of asciinema to suit your
needs, check [asciinema consulting
services](https://docs.asciinema.org/consulting/).

## License

© 2011 Marcin Kulik.

All code is licensed under the GPL, v3 or later. See [LICENSE](./LICENSE) file
for details.


================================================
FILE: assets/asciinema-player.css
================================================
.ap-default-term-ff {
  --term-font-family: "Cascadia Code", "Source Code Pro", Menlo, Consolas, "DejaVu Sans Mono", monospace, "Symbols Nerd Font";
}
div.ap-wrapper {
  outline: none;
  height: 100%;
  display: flex;
  justify-content: center;
}
div.ap-wrapper .title-bar {
  display: none;
  top: -78px;
  transition: top 0.15s linear;
  position: absolute;
  left: 0;
  right: 0;
  box-sizing: content-box;
  font-size: 20px;
  line-height: 1em;
  padding: 15px;
  font-family: sans-serif;
  color: white;
  background-color: rgba(0, 0, 0, 0.8);
}
div.ap-wrapper .title-bar img {
  vertical-align: middle;
  height: 48px;
  margin-right: 16px;
}
div.ap-wrapper .title-bar a {
  color: white;
  text-decoration: underline;
}
div.ap-wrapper .title-bar a:hover {
  text-decoration: none;
}
div.ap-wrapper:fullscreen {
  background-color: #000;
  width: 100%;
  align-items: center;
}
div.ap-wrapper:fullscreen .title-bar {
  display: initial;
}
div.ap-wrapper:fullscreen.hud .title-bar {
  top: 0;
}
div.ap-wrapper div.ap-player {
  text-align: left;
  display: inline-block;
  padding: 0px;
  position: relative;
  box-sizing: content-box;
  overflow: hidden;
  max-width: 100%;
  border-radius: 4px;
  font-size: 15px;
  background-color: var(--term-color-background);
}
.ap-player {
  --term-color-foreground: #ffffff;
  --term-color-background: #000000;
  --term-color-0: var(--term-color-foreground);
  --term-color-1: var(--term-color-foreground);
  --term-color-2: var(--term-color-foreground);
  --term-color-3: var(--term-color-foreground);
  --term-color-4: var(--term-color-foreground);
  --term-color-5: var(--term-color-foreground);
  --term-color-6: var(--term-color-foreground);
  --term-color-7: var(--term-color-foreground);
  --term-color-8: var(--term-color-0);
  --term-color-9: var(--term-color-1);
  --term-color-10: var(--term-color-2);
  --term-color-11: var(--term-color-3);
  --term-color-12: var(--term-color-4);
  --term-color-13: var(--term-color-5);
  --term-color-14: var(--term-color-6);
  --term-color-15: var(--term-color-7);
}
div.ap-term {
  position: relative;
  font-family: var(--term-font-family);
  border-width: 0.75em;
  border-radius: 0;
  border-style: solid;
  border-color: var(--term-color-background);
  box-sizing: content-box;
}
div.ap-term canvas {
  position: absolute;
  inset: 0;
  display: block;
  width: 100%;
  height: 100%;
}
div.ap-term svg.ap-term-symbols {
  position: absolute;
  inset: 0;
  display: block;
  width: 100%;
  height: 100%;
  overflow: hidden;
  pointer-events: none;
}
div.ap-term svg.ap-term-symbols use {
  color: var(--term-color-foreground);
}
div.ap-term svg.ap-term-symbols:not(.ap-blink) .ap-blink {
  opacity: 0;
}
div.ap-term pre.ap-term-text {
  position: absolute;
  inset: 0;
  box-sizing: content-box;
  overflow: hidden;
  padding: 0;
  margin: 0px;
  display: block;
  white-space: pre;
  word-wrap: normal;
  word-break: normal;
  cursor: text;
  color: var(--term-color-foreground);
  outline: none;
  line-height: var(--term-line-height);
  font-family: inherit;
  font-size: inherit;
  font-variant-ligatures: none;
  border: 0;
  border-radius: 0;
  background-color: transparent !important;
}
pre.ap-term-text .ap-line {
  display: block;
  width: 100%;
  height: var(--term-line-height);
  position: absolute;
  top: calc(100% * var(--row) / var(--term-rows));
  letter-spacing: normal;
  overflow: hidden;
}
pre.ap-term-text .ap-line span {
  position: absolute;
  left: calc(100% * var(--offset) / var(--term-cols));
  padding: 0;
  display: inline-block;
  height: 100%;
}
pre.ap-term-text:not(.ap-blink) .ap-line .ap-blink {
  color: transparent;
  border-color: transparent;
}
pre.ap-term-text .ap-bold {
  font-weight: bold;
}
pre.ap-term-text .ap-faint {
  opacity: 0.5;
}
pre.ap-term-text .ap-underline {
  text-decoration: underline;
}
pre.ap-term-text .ap-italic {
  font-style: italic;
}
pre.ap-term-text .ap-strike {
  text-decoration: line-through;
}
.ap-line span {
  color: var(--term-color-foreground);
}
div.ap-player div.ap-control-bar {
  width: 100%;
  height: 32px;
  display: flex;
  justify-content: space-between;
  align-items: stretch;
  color: var(--term-color-foreground);
  box-sizing: content-box;
  line-height: 1;
  position: absolute;
  bottom: 0;
  left: 0;
  opacity: 0;
  transition: opacity 0.15s linear;
  user-select: none;
  border-top: 2px solid color-mix(in oklab, var(--term-color-background) 80%, var(--term-color-foreground));
  z-index: 30;
}
div.ap-player div.ap-control-bar * {
  box-sizing: inherit;
}
div.ap-control-bar svg.ap-icon path {
  fill: var(--term-color-foreground);
}
div.ap-control-bar span.ap-button {
  display: flex;
  flex: 0 0 auto;
  cursor: pointer;
}
div.ap-control-bar span.ap-playback-button {
  width: 12px;
  height: 12px;
  padding: 10px;
  margin: 0 0 0 2px;
}
div.ap-control-bar span.ap-playback-button svg {
  height: 12px;
  width: 12px;
}
div.ap-control-bar span.ap-timer {
  display: flex;
  flex: 0 0 auto;
  min-width: 50px;
  margin: 0 10px;
  height: 100%;
  text-align: center;
  font-size: 13px;
  line-height: 100%;
  cursor: default;
}
div.ap-control-bar span.ap-timer span {
  font-family: var(--term-font-family);
  font-size: inherit;
  font-weight: 600;
  margin: auto;
}
div.ap-control-bar span.ap-timer .ap-time-remaining {
  display: none;
}
div.ap-control-bar span.ap-timer:hover .ap-time-elapsed {
  display: none;
}
div.ap-control-bar span.ap-timer:hover .ap-time-remaining {
  display: flex;
}
div.ap-control-bar .ap-progressbar {
  display: block;
  flex: 1 1 auto;
  height: 100%;
  padding: 0 10px;
}
div.ap-control-bar .ap-progressbar .ap-bar {
  display: block;
  position: relative;
  cursor: default;
  height: 100%;
  font-size: 0;
}
div.ap-control-bar .ap-progressbar .ap-bar .ap-gutter {
  display: block;
  position: absolute;
  top: 15px;
  left: 0;
  right: 0;
  height: 3px;
}
div.ap-control-bar .ap-progressbar .ap-bar .ap-gutter-empty {
  background-color: color-mix(in oklab, var(--term-color-foreground) 20%, var(--term-color-background));
}
div.ap-control-bar .ap-progressbar .ap-bar .ap-gutter-full {
  width: 100%;
  transform-origin: left center;
  background-color: var(--term-color-foreground);
  border-radius: 3px;
}
div.ap-control-bar.ap-seekable .ap-progressbar .ap-bar {
  cursor: pointer;
}
div.ap-control-bar .ap-fullscreen-button {
  width: 14px;
  height: 14px;
  padding: 9px;
  margin: 0 2px 0 4px;
}
div.ap-control-bar .ap-fullscreen-button svg {
  width: 14px;
  height: 14px;
}
div.ap-control-bar .ap-fullscreen-button svg.ap-icon-fullscreen-on {
  display: inline;
}
div.ap-control-bar .ap-fullscreen-button svg.ap-icon-fullscreen-off {
  display: none;
}
div.ap-control-bar .ap-fullscreen-button .ap-tooltip {
  right: 5px;
  left: initial;
  transform: none;
}
div.ap-control-bar .ap-kbd-button {
  height: 14px;
  padding: 9px;
  margin: 0 0 0 4px;
}
div.ap-control-bar .ap-kbd-button svg {
  width: 26px;
  height: 14px;
}
div.ap-control-bar .ap-kbd-button .ap-tooltip {
  right: 5px;
  left: initial;
  transform: none;
}
div.ap-control-bar .ap-speaker-button {
  width: 19px;
  padding: 6px 9px;
  margin: 0 0 0 4px;
  position: relative;
}
div.ap-control-bar .ap-speaker-button svg {
  width: 19px;
}
div.ap-control-bar .ap-speaker-button .ap-tooltip {
  left: -50%;
  transform: none;
}
div.ap-wrapper.ap-hud .ap-control-bar {
  opacity: 1;
}
div.ap-wrapper:fullscreen .ap-fullscreen-button svg.ap-icon-fullscreen-on {
  display: none;
}
div.ap-wrapper:fullscreen .ap-fullscreen-button svg.ap-icon-fullscreen-off {
  display: inline;
}
span.ap-progressbar span.ap-marker-container {
  display: block;
  top: 0;
  bottom: 0;
  width: 21px;
  position: absolute;
  margin-left: -10px;
}
span.ap-marker-container span.ap-marker {
  display: block;
  top: 13px;
  bottom: 12px;
  left: 7px;
  right: 7px;
  background-color: color-mix(in oklab, var(--term-color-foreground) 33%, var(--term-color-background));
  position: absolute;
  transition: top 0.1s, bottom 0.1s, left 0.1s, right 0.1s, background-color 0.1s;
  border-radius: 50%;
}
span.ap-marker-container span.ap-marker.ap-marker-past {
  background-color: var(--term-color-foreground);
}
span.ap-marker-container span.ap-marker:hover,
span.ap-marker-container:hover span.ap-marker {
  background-color: var(--term-color-foreground);
  top: 11px;
  bottom: 10px;
  left: 5px;
  right: 5px;
}
.ap-tooltip-container span.ap-tooltip {
  visibility: hidden;
  background-color: var(--term-color-foreground);
  color: var(--term-color-background);
  font-family: var(--term-font-family);
  font-weight: bold;
  text-align: center;
  padding: 0 0.5em;
  border-radius: 4px;
  position: absolute;
  z-index: 1;
  white-space: nowrap;
  /* Prevents the text from wrapping and makes sure the tooltip width adapts to the text length */
  font-size: 13px;
  line-height: 2em;
  bottom: 100%;
  left: 50%;
  transform: translateX(-50%);
}
.ap-tooltip-container:hover span.ap-tooltip {
  visibility: visible;
}
.ap-player .ap-overlay {
  z-index: 10;
  background-repeat: no-repeat;
  background-position: center;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}
.ap-player .ap-overlay-start {
  cursor: pointer;
}
.ap-player .ap-overlay-start .ap-play-button {
  font-size: 0px;
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  text-align: center;
  color: white;
  height: 80px;
  max-height: 66%;
  margin: auto;
}
.ap-player .ap-overlay-start .ap-play-button div {
  height: 100%;
}
.ap-player .ap-overlay-start .ap-play-button div span {
  height: 100%;
  display: block;
}
.ap-player .ap-overlay-start .ap-play-button div span svg {
  height: 100%;
  display: inline-block;
}
.ap-player .ap-overlay-start .ap-play-button svg {
  filter: drop-shadow(0px 0px 5px rgba(0, 0, 0, 0.4));
}
.ap-player .ap-overlay-loading .ap-loader {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: inline-block;
  position: relative;
  border: 10px solid;
  border-color: rgba(255, 255, 255, 0.3) rgba(255, 255, 255, 0.5) rgba(255, 255, 255, 0.7) #ffffff;
  border-color: color-mix(in srgb, var(--term-color-foreground) 30%, var(--term-color-background)) color-mix(in srgb, var(--term-color-foreground) 50%, var(--term-color-background)) color-mix(in srgb, var(--term-color-foreground) 70%, var(--term-color-background)) color-mix(in srgb, var(--term-color-foreground) 100%, var(--term-color-background));
  box-sizing: border-box;
  animation: ap-loader-rotation 1s linear infinite;
}
.ap-player .ap-overlay-info {
  background-color: var(--term-color-background);
}
.ap-player .ap-overlay-info span {
  font-family: var(--term-font-family);
  font-size: 2em;
  font-weight: bold;
  color: var(--term-color-background);
  background-color: var(--term-color-foreground);
  padding: 0.5em 0.75em;
  text-transform: uppercase;
}
.ap-player .ap-overlay-help {
  background-color: rgba(0, 0, 0, 0.8);
  container-type: inline-size;
}
.ap-player .ap-overlay-help > div {
  font-family: var(--term-font-family);
  max-width: 85%;
  max-height: 85%;
  font-size: 18px;
  color: var(--term-color-foreground);
  box-sizing: border-box;
  margin-bottom: 32px;
}
.ap-player .ap-overlay-help > div div {
  padding: calc(min(4cqw, 40px));
  font-size: calc(min(1.9cqw, 18px));
  background-color: var(--term-color-background);
  border: 1px solid color-mix(in oklab, var(--term-color-background) 90%, var(--term-color-foreground));
  border-radius: 6px;
}
.ap-player .ap-overlay-help > div div p {
  font-weight: bold;
  margin: 0 0 2em 0;
}
.ap-player .ap-overlay-help > div div ul {
  list-style: none;
  padding: 0;
}
.ap-player .ap-overlay-help > div div ul li {
  margin: 0 0 0.75em 0;
}
.ap-player .ap-overlay-help > div div kbd {
  color: var(--term-color-background);
  background-color: var(--term-color-foreground);
  padding: 0.2em 0.5em;
  border-radius: 0.2em;
  font-family: inherit;
  font-size: 0.85em;
  border: none;
  margin: 0;
}
.ap-player .ap-overlay-error span {
  font-size: 8em;
}
.ap-player .slide-enter-active {
  transition: opacity 0.2s;
}
.ap-player .slide-enter-active.ap-was-playing {
  transition: top 0.2s ease-out, opacity 0.2s;
}
.ap-player .slide-exit-active {
  transition: top 0.2s ease-in, opacity 0.2s;
}
.ap-player .slide-enter {
  top: -50%;
  opacity: 0;
}
.ap-player .slide-enter-to {
  top: 0%;
}
.ap-player .slide-enter,
.ap-player .slide-enter-to,
.ap-player .slide-exit,
.ap-player .slide-exit-to {
  bottom: auto;
  height: 100%;
}
.ap-player .slide-exit {
  top: 0%;
}
.ap-player .slide-exit-to {
  top: -50%;
  opacity: 0;
}
@keyframes ap-loader-rotation {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
.asciinema-player-theme-asciinema {
  --term-color-foreground: #cccccc;
  --term-color-background: #121314;
  --term-color-0: #000000;
  --term-color-1: #dd3c69;
  --term-color-2: #4ebf22;
  --term-color-3: #ddaf3c;
  --term-color-4: #26b0d7;
  --term-color-5: #b954e1;
  --term-color-6: #54e1b9;
  --term-color-7: #d9d9d9;
  --term-color-8: #4d4d4d;
  --term-color-9: #dd3c69;
  --term-color-10: #4ebf22;
  --term-color-11: #ddaf3c;
  --term-color-12: #26b0d7;
  --term-color-13: #b954e1;
  --term-color-14: #54e1b9;
  --term-color-15: #ffffff;
}
/*
  Based on Dracula: https://draculatheme.com
 */
.asciinema-player-theme-dracula {
  --term-color-foreground: #f8f8f2;
  --term-color-background: #282a36;
  --term-color-0: #21222c;
  --term-color-1: #ff5555;
  --term-color-2: #50fa7b;
  --term-color-3: #f1fa8c;
  --term-color-4: #bd93f9;
  --term-color-5: #ff79c6;
  --term-color-6: #8be9fd;
  --term-color-7: #f8f8f2;
  --term-color-8: #6272a4;
  --term-color-9: #ff6e6e;
  --term-color-10: #69ff94;
  --term-color-11: #ffffa5;
  --term-color-12: #d6acff;
  --term-color-13: #ff92df;
  --term-color-14: #a4ffff;
  --term-color-15: #ffffff;
}
/* Based on Monokai from base16 collection - https://github.com/chriskempson/base16 */
.asciinema-player-theme-monokai {
  --term-color-foreground: #f8f8f2;
  --term-color-background: #272822;
  --term-color-0: #272822;
  --term-color-1: #f92672;
  --term-color-2: #a6e22e;
  --term-color-3: #f4bf75;
  --term-color-4: #66d9ef;
  --term-color-5: #ae81ff;
  --term-color-6: #a1efe4;
  --term-color-7: #f8f8f2;
  --term-color-8: #75715e;
  --term-color-15: #f9f8f5;
}
/*
  Based on Nord: https://github.com/arcticicestudio/nord
  Via: https://github.com/neilotoole/asciinema-theme-nord
 */
.asciinema-player-theme-nord {
  --term-color-foreground: #eceff4;
  --term-color-background: #2e3440;
  --term-color-0: #3b4252;
  --term-color-1: #bf616a;
  --term-color-2: #a3be8c;
  --term-color-3: #ebcb8b;
  --term-color-4: #81a1c1;
  --term-color-5: #b48ead;
  --term-color-6: #88c0d0;
  --term-color-7: #eceff4;
}
.asciinema-player-theme-seti {
  --term-color-foreground: #cacecd;
  --term-color-background: #111213;
  --term-color-0: #323232;
  --term-color-1: #c22832;
  --term-color-2: #8ec43d;
  --term-color-3: #e0c64f;
  --term-color-4: #43a5d5;
  --term-color-5: #8b57b5;
  --term-color-6: #8ec43d;
  --term-color-7: #eeeeee;
  --term-color-15: #ffffff;
}
/*
  Based on Solarized Dark: https://ethanschoonover.com/solarized/
 */
.asciinema-player-theme-solarized-dark {
  --term-color-foreground: #839496;
  --term-color-background: #002b36;
  --term-color-0: #073642;
  --term-color-1: #dc322f;
  --term-color-2: #859900;
  --term-color-3: #b58900;
  --term-color-4: #268bd2;
  --term-color-5: #d33682;
  --term-color-6: #2aa198;
  --term-color-7: #eee8d5;
  --term-color-8: #002b36;
  --term-color-9: #cb4b16;
  --term-color-10: #586e75;
  --term-color-11: #657b83;
  --term-color-12: #839496;
  --term-color-13: #6c71c4;
  --term-color-14: #93a1a1;
  --term-color-15: #fdf6e3;
}
/*
  Based on Solarized Light: https://ethanschoonover.com/solarized/
 */
.asciinema-player-theme-solarized-light {
  --term-color-foreground: #657b83;
  --term-color-background: #fdf6e3;
  --term-color-0: #073642;
  --term-color-1: #dc322f;
  --term-color-2: #859900;
  --term-color-3: #b58900;
  --term-color-4: #268bd2;
  --term-color-5: #d33682;
  --term-color-6: #2aa198;
  --term-color-7: #eee8d5;
  --term-color-8: #002b36;
  --term-color-9: #cb4b16;
  --term-color-10: #586e75;
  --term-color-11: #657c83;
  --term-color-12: #839496;
  --term-color-13: #6c71c4;
  --term-color-14: #93a1a1;
  --term-color-15: #fdf6e3;
}
.asciinema-player-theme-solarized-light .ap-overlay-start .ap-play-button svg .ap-play-btn-fill {
  fill: var(--term-color-1);
}
.asciinema-player-theme-solarized-light .ap-overlay-start .ap-play-button svg .ap-play-btn-stroke {
  stroke: var(--term-color-1);
}
/*
  Based on Tango: https://en.wikipedia.org/wiki/Tango_Desktop_Project
 */
.asciinema-player-theme-tango {
  --term-color-foreground: #cccccc;
  --term-color-background: #121314;
  --term-color-0: #000000;
  --term-color-1: #cc0000;
  --term-color-2: #4e9a06;
  --term-color-3: #c4a000;
  --term-color-4: #3465a4;
  --term-color-5: #75507b;
  --term-color-6: #06989a;
  --term-color-7: #d3d7cf;
  --term-color-8: #555753;
  --term-color-9: #ef2929;
  --term-color-10: #8ae234;
  --term-color-11: #fce94f;
  --term-color-12: #729fcf;
  --term-color-13: #ad7fa8;
  --term-color-14: #34e2e2;
  --term-color-15: #eeeeec;
}
/*
  Based on gruvbox: https://github.com/morhetz/gruvbox
 */
.asciinema-player-theme-gruvbox-dark {
  --term-color-foreground: #fbf1c7;
  --term-color-background: #282828;
  --term-color-0: #282828;
  --term-color-1: #cc241d;
  --term-color-2: #98971a;
  --term-color-3: #d79921;
  --term-color-4: #458588;
  --term-color-5: #b16286;
  --term-color-6: #689d6a;
  --term-color-7: #a89984;
  --term-color-8: #7c6f65;
  --term-color-9: #fb4934;
  --term-color-10: #b8bb26;
  --term-color-11: #fabd2f;
  --term-color-12: #83a598;
  --term-color-13: #d3869b;
  --term-color-14: #8ec07c;
  --term-color-15: #fbf1c7;
}


================================================
FILE: assets/index.html
================================================
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="asciinema-player.css">
  <style>
    @font-face {
      font-family: "Symbols Nerd Font";
      src: local(SymbolsNerdFont-Regular),
           url("/SymbolsNerdFont-Regular.woff2") format("woff2");
    }

    :root {
      --term-color-background: black;
    }

    html, body {
      height: 100%;
      margin: 0;
      overflow: hidden;
    }

    html {
      padding: 0;
    }

    body {
      box-sizing: border-box;
      padding: 40px;
      background-color: color-mix(in oklab, var(--term-color-background) 90%, black);
      transition: background-color 0.2s;
    }

    div.ap-wrapper:fullscreen {
      background-color: inherit;
    }

    .ap-player {
      margin: auto 0px;
      opacity: 0;
      box-shadow: color-mix(in oklab, var(--term-color-background) 50%, black) 0px 0px 60px 5px;
    }
  </style>
</head>
<body>
  <script src="asciinema-player.min.js"></script>

  <script>
    const loc = window.location;
    const params = new URLSearchParams(loc.hash.replace('#', '?'));

    let bufferTime = params.get('bufferTime');

    if (bufferTime !== null) {
      bufferTime = parseFloat(bufferTime);
    };

    const src = {
      driver: 'websocket',
      url: loc.protocol.replace("http", "ws") + '//' + loc.host + '/ws',
      bufferTime
    };

    const fit = params.get('fit');
    const terminalLineHeight = params.get('terminalLineHeight');

    const opts = {
      logger: console,
      fit: fit === null ? 'both' : fit,
      theme: params.get('theme'),
      autoPlay: params.get('autoPlay') !== 'false',
      terminalFontFamily: params.get('terminalFontFamily'),
      terminalLineHeight: terminalLineHeight === null ? undefined : parseFloat(terminalLineHeight)
    };

    console.debug('initializing the player', { src, opts });

    window.player = AsciinemaPlayer.create(src, document.body, opts);

    window.player.addEventListener('metadata', () => {
      const el = window.player.el.getElementsByClassName('ap-player')[0];
      const style = window.getComputedStyle(el);
      const color = style.getPropertyValue("--term-color-background");
      document.documentElement.style.setProperty('--term-color-background', color);
      el.style.opacity = 1;
    });
  </script>
</body>
</html>


================================================
FILE: build.rs
================================================
use clap::CommandFactory;
use clap::ValueEnum;
use std::env;
use std::fs::create_dir_all;
use std::path::Path;
use std::path::PathBuf;

mod cli {
    include!("src/cli.rs");
}

const ENV_KEY: &str = "ASCIINEMA_GEN_DIR";

fn main() -> std::io::Result<()> {
    if let Some(dir) = env::var_os(ENV_KEY).or(env::var_os("OUT_DIR")) {
        let mut cmd = cli::Cli::command();
        let base_dir = PathBuf::from(dir);

        let man_dir = Path::join(&base_dir, "man");
        create_dir_all(&man_dir)?;
        clap_mangen::generate_to(cmd.clone(), &man_dir)?;

        let completion_dir = Path::join(&base_dir, "completion");
        create_dir_all(&completion_dir)?;

        for shell in clap_complete::Shell::value_variants() {
            clap_complete::generate_to(*shell, &mut cmd, "asciinema", &completion_dir)?;
        }
    }

    println!("cargo:rustc-env=TARGET={}", env::var("TARGET").unwrap());
    println!("cargo:rerun-if-env-changed={ENV_KEY}");

    Ok(())
}


================================================
FILE: default.nix
================================================
{
  lib,
  stdenv,
  rust,
  makeRustPlatform,
  version,
  libiconv,
  python3,
}:
(makeRustPlatform {
  cargo = rust;
  rustc = rust;
}).buildRustPackage
  {
    pname = "asciinema";
    inherit version;

    src = builtins.path {
      path = ./.;
      name = "asciinema";
    };

    dontUseCargoParallelTests = true;
    cargoLock.lockFile = ./Cargo.lock;
    nativeBuildInputs = [ rust ];

    buildInputs = lib.optional stdenv.isDarwin [
      libiconv
    ];

    nativeCheckInputs = [ python3 ];
  }


================================================
FILE: flake.nix
================================================
{
  description = "Terminal session recorder";

  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
    rust-overlay.url = "github:oxalica/rust-overlay";
    flake-utils.url = "github:numtide/flake-utils";
  };

  outputs =
    {
      self,
      nixpkgs,
      rust-overlay,
      flake-utils,
    }:
    flake-utils.lib.eachDefaultSystem (
      system:
      let
        pkgs = import nixpkgs {
          inherit system;
          overlays = [ (import rust-overlay) ];
        };

        packageToml = (builtins.fromTOML (builtins.readFile ./Cargo.toml)).package;
        msrv = packageToml.rust-version;
      in
      {
        packages.default = pkgs.callPackage ./default.nix {
          version = packageToml.version;
          rust = pkgs.rust-bin.stable.latest.minimal;
        };

        devShells = pkgs.callPackages ./shell.nix {
          package = self.packages.${system}.default;

          rust = {
            default = pkgs.rust-bin.stable.latest.minimal;
            msrv = pkgs.rust-bin.stable.${msrv}.minimal;
          };
        };

        formatter = pkgs.nixfmt-tree;
      }
    );
}


================================================
FILE: shell.nix
================================================
{
  package,
  shellcheck,
  mkShell,
  rust,
}:
let
  mkDevShell =
    rust:
    mkShell {
      inputsFrom = [
        (package.override {
          rust = rust.override {
            extensions = [
              "rust-src"
              "rust-analyzer"
              "clippy"
            ];
          };
        })
      ];

      packages = [ shellcheck ];

      env.RUST_BACKTRACE = 1;
    };
in
{
  default = mkDevShell rust.default;
  msrv = mkDevShell rust.msrv;
}


================================================
FILE: src/alis.rs
================================================
// This module implements ALiS (asciinema live stream) protocol, which is an application level
// protocol built on top of WebSocket binary messages, used by asciinema CLI, asciinema player and
// asciinema server.

// See more at: https://docs.asciinema.org/manual/server/streaming/

use std::future;
use std::time::Duration;

use futures_util::{stream, Stream, StreamExt};
use tokio_stream::wrappers::errors::BroadcastStreamRecvError;

use crate::leb128;
use crate::stream::Event;

static MAGIC_STRING: &str = "ALiS\x01";

#[derive(Default)]
struct EventSerializer(Duration);

pub fn stream<S: Stream<Item = Result<Event, BroadcastStreamRecvError>>>(
    stream: S,
) -> impl Stream<Item = Result<Vec<u8>, BroadcastStreamRecvError>> {
    let header = stream::once(future::ready(Ok(MAGIC_STRING.into())));
    let mut serializer = EventSerializer::default();
    let events = stream.map(move |event| event.map(|event| serializer.serialize_event(event)));

    header.chain(events)
}

impl EventSerializer {
    fn serialize_event(&mut self, event: Event) -> Vec<u8> {
        use Event::*;

        match event {
            Init(last_id, time, size, theme, init) => {
                let last_id_bytes = leb128::encode(last_id);
                let time_bytes = leb128::encode(time.as_micros() as u64);
                let cols_bytes = leb128::encode(size.0);
                let rows_bytes = leb128::encode(size.1);
                let init_len = init.len() as u32;
                let init_len_bytes = leb128::encode(init_len);

                let mut msg = vec![0x01];
                msg.extend_from_slice(&last_id_bytes);
                msg.extend_from_slice(&time_bytes);
                msg.extend_from_slice(&cols_bytes);
                msg.extend_from_slice(&rows_bytes);

                match theme {
                    Some(theme) => {
                        msg.push(16);
                        msg.push(theme.fg.r);
                        msg.push(theme.fg.g);
                        msg.push(theme.fg.b);
                        msg.push(theme.bg.r);
                        msg.push(theme.bg.g);
                        msg.push(theme.bg.b);

                        for color in &theme.palette {
                            msg.push(color.r);
                            msg.push(color.g);
                            msg.push(color.b);
                        }
                    }

                    None => {
                        msg.push(0);
                    }
                }

                msg.extend_from_slice(&init_len_bytes);
                msg.extend_from_slice(init.as_bytes());

                self.0 = time;

                msg
            }

            Output(id, time, text) => {
                let id_bytes = leb128::encode(id);
                let time_bytes = leb128::encode(self.rel_time(time));
                let text_len = text.len() as u32;
                let text_len_bytes = leb128::encode(text_len);

                let mut msg = vec![b'o'];
                msg.extend_from_slice(&id_bytes);
                msg.extend_from_slice(&time_bytes);
                msg.extend_from_slice(&text_len_bytes);
                msg.extend_from_slice(text.as_bytes());

                msg
            }

            Input(id, time, text) => {
                let id_bytes = leb128::encode(id);
                let time_bytes = leb128::encode(self.rel_time(time));
                let text_len = text.len() as u32;
                let text_len_bytes = leb128::encode(text_len);

                let mut msg = vec![b'i'];
                msg.extend_from_slice(&id_bytes);
                msg.extend_from_slice(&time_bytes);
                msg.extend_from_slice(&text_len_bytes);
                msg.extend_from_slice(text.as_bytes());

                msg
            }

            Resize(id, time, size) => {
                let id_bytes = leb128::encode(id);
                let time_bytes = leb128::encode(self.rel_time(time));
                let cols_bytes = leb128::encode(size.0);
                let rows_bytes = leb128::encode(size.1);

                let mut msg = vec![b'r'];
                msg.extend_from_slice(&id_bytes);
                msg.extend_from_slice(&time_bytes);
                msg.extend_from_slice(&cols_bytes);
                msg.extend_from_slice(&rows_bytes);

                msg
            }

            Marker(id, time, text) => {
                let id_bytes = leb128::encode(id);
                let time_bytes = leb128::encode(self.rel_time(time));
                let text_len = text.len() as u32;
                let text_len_bytes = leb128::encode(text_len);

                let mut msg = vec![b'm'];
                msg.extend_from_slice(&id_bytes);
                msg.extend_from_slice(&time_bytes);
                msg.extend_from_slice(&text_len_bytes);
                msg.extend_from_slice(text.as_bytes());

                msg
            }

            Exit(id, time, status) => {
                let id_bytes = leb128::encode(id);
                let time_bytes = leb128::encode(self.rel_time(time));
                let status_bytes = leb128::encode(status.max(0) as u64);

                let mut msg = vec![b'x'];
                msg.extend_from_slice(&id_bytes);
                msg.extend_from_slice(&time_bytes);
                msg.extend_from_slice(&status_bytes);

                msg
            }

            Eot(id, time) => {
                let id_bytes = leb128::encode(id);
                let time_bytes = leb128::encode(self.rel_time(time));

                let mut msg = vec![0x04];
                msg.extend_from_slice(&id_bytes);
                msg.extend_from_slice(&time_bytes);

                msg
            }
        }
    }

    fn rel_time(&mut self, time: Duration) -> u64 {
        let time = time.max(self.0);
        let rel_time = time - self.0;
        self.0 = time;

        rel_time.as_micros() as u64
    }
}

#[cfg(test)]
mod tests {
    use rgb::RGB8;

    use super::*;
    use crate::tty::{TtySize, TtyTheme};

    #[test]
    fn test_serialize_init_with_theme_and_seed() {
        let mut serializer = EventSerializer(Duration::from_millis(0));

        let theme = TtyTheme {
            fg: rgb(255, 255, 255),
            bg: rgb(0, 0, 0),
            palette: vec![
                rgb(0, 0, 0),       // Black
                rgb(128, 0, 0),     // Dark Red
                rgb(0, 128, 0),     // Dark Green
                rgb(128, 128, 0),   // Dark Yellow
                rgb(0, 0, 128),     // Dark Blue
                rgb(128, 0, 128),   // Dark Magenta
                rgb(0, 128, 128),   // Dark Cyan
                rgb(192, 192, 192), // Light Gray
                rgb(128, 128, 128), // Dark Gray
                rgb(255, 0, 0),     // Bright Red
                rgb(0, 255, 0),     // Bright Green
                rgb(255, 255, 0),   // Bright Yellow
                rgb(0, 0, 255),     // Bright Blue
                rgb(255, 0, 255),   // Bright Magenta
                rgb(0, 255, 255),   // Bright Cyan
                rgb(255, 255, 255), // White
            ],
        };

        let event = Event::Init(
            42.into(),
            Duration::from_micros(1000),
            TtySize(180, 24),
            Some(theme),
            "terminal seed".to_string(),
        );

        let bytes = serializer.serialize_event(event);

        let mut expected = vec![
            0x01, // Init event type
            0x2A, // id (42) in LEB128
            0xE8, 0x07, // time (1000) in LEB128
            0xB4, 0x01, // cols (180) in LEB128
            0x18, // rows (24) in LEB128
            16,   // theme - 16 colors
            255, 255, 255, // foreground RGB
            0, 0, 0, // background RGB
        ];

        // Add palette colors (16 colors * 3 bytes each)
        expected.extend_from_slice(&[
            0, 0, 0, // Black
            128, 0, 0, // Dark Red
            0, 128, 0, // Dark Green
            128, 128, 0, // Dark Yellow
            0, 0, 128, // Dark Blue
            128, 0, 128, // Dark Magenta
            0, 128, 128, // Dark Cyan
            192, 192, 192, // Light Gray
            128, 128, 128, // Dark Gray
            255, 0, 0, // Bright Red
            0, 255, 0, // Bright Green
            255, 255, 0, // Bright Yellow
            0, 0, 255, // Bright Blue
            255, 0, 255, // Bright Magenta
            0, 255, 255, // Bright Cyan
            255, 255, 255, // White
        ]);

        expected.push(0x0D); // init string length (13)
        expected.extend_from_slice(b"terminal seed"); // init string

        assert_eq!(bytes, expected);
        assert_eq!(serializer.0.as_micros(), 1000);
    }

    #[test]
    fn test_serialize_init_without_theme_nor_seed() {
        let mut serializer = EventSerializer::default();

        let event = Event::Init(
            1.into(),
            Duration::from_micros(500),
            TtySize(120, 130),
            None,
            "".to_string(),
        );

        let bytes = serializer.serialize_event(event);

        let expected = vec![
            0x01, // Init event type
            0x01, // id (1) in LEB128
            0xF4, 0x03, // relative time (500) in LEB128
            0x78, // cols (120) in LEB128
            0x82, 0x01, // rows (130) in LEB128
            0x00, // no theme flag
            0x00, // init string length (0) in LEB128
        ];

        assert_eq!(bytes, expected);
        assert_eq!(serializer.0.as_micros(), 500);
    }

    #[test]
    fn test_serialize_output() {
        let mut serializer = EventSerializer(Duration::from_micros(1000));
        let event = Event::Output(
            5.into(),
            Duration::from_micros(1200),
            "Hello 世界 🌍".to_string(),
        );
        let bytes = serializer.serialize_event(event);

        let mut expected = vec![
            b'o', // Output event type
            0x05, // id (5) in LEB128
            0xC8, 0x01, // relative time (200) in LEB128
            0x11, // text length in bytes
        ];

        expected.extend_from_slice("Hello 世界 🌍".as_bytes()); // text bytes

        assert_eq!(bytes, expected);
        assert_eq!(serializer.0.as_micros(), 1200); // Time updated to 1200
    }

    #[test]
    fn test_serialize_input() {
        let mut serializer = EventSerializer(Duration::from_micros(500));
        let event = Event::Input(1000000.into(), Duration::from_micros(750), "x".to_string());
        let bytes = serializer.serialize_event(event);

        let expected = vec![
            b'i', // Input event type
            0xC0, 0x84, 0x3D, // id (1000000) in LEB128
            0xFA, 0x01, // relative time (250) in LEB128
            0x01, // text length (1) in LEB128
            b'x', // text
        ];

        assert_eq!(bytes, expected);
        assert_eq!(serializer.0.as_micros(), 750);
    }

    #[test]
    fn test_serialize_resize() {
        let mut serializer = EventSerializer(Duration::from_micros(2000));
        let event = Event::Resize(15.into(), Duration::from_micros(2100), TtySize(180, 50));
        let bytes = serializer.serialize_event(event);

        let expected = vec![
            b'r', // Resize event type
            0x0F, // id (15) in LEB128
            0x64, // relative time (100) in LEB128
            0xB4, 0x01, // cols (180) in LEB128
            0x32, // rows (50) in LEB128
        ];

        assert_eq!(bytes, expected);
        assert_eq!(serializer.0.as_micros(), 2100);
    }

    #[test]
    fn test_serialize_marker_with_label() {
        let mut serializer = EventSerializer(Duration::from_micros(3000));
        let event = Event::Marker(
            20.into(),
            Duration::from_micros(3500),
            "checkpoint".to_string(),
        );
        let bytes = serializer.serialize_event(event);

        let expected = vec![
            b'm', // Marker event type
            0x14, // id (20) in LEB128
            0xF4, 0x03, // relative time (500) in LEB128
            0x0A, // label length (10) in LEB128
        ];
        let mut expected = expected;
        expected.extend_from_slice(b"checkpoint"); // label bytes

        assert_eq!(bytes, expected);
        assert_eq!(serializer.0.as_micros(), 3500);
    }

    #[test]
    fn test_serialize_marker_without_label() {
        let mut serializer = EventSerializer(Duration::from_micros(3000));
        let event = Event::Marker(2.into(), Duration::from_micros(3300), "".to_string());
        let bytes = serializer.serialize_event(event);

        let expected = vec![
            b'm', // Marker event type
            0x02, // id (2) in LEB128
            0xAC, 0x02, // relative time (300) in LEB128
            0x00, // label length (0)
        ];

        assert_eq!(bytes, expected);
    }

    #[test]
    fn test_serialize_exit_positive_status() {
        let mut serializer = EventSerializer(Duration::from_micros(4000));
        let event = Event::Exit(25.into(), Duration::from_micros(4200), 0);
        let bytes = serializer.serialize_event(event);

        let expected = vec![
            b'x', // Exit event type
            0x19, // id (25) in LEB128
            0xC8, 0x01, // relative time (200) in LEB128
            0x00, // status (0) in LEB128
        ];

        assert_eq!(bytes, expected);
        assert_eq!(serializer.0.as_micros(), 4200);
    }

    #[test]
    fn test_serialize_exit_negative_status() {
        let mut serializer = EventSerializer(Duration::from_micros(5000));
        let event = Event::Exit(30.into(), Duration::from_micros(5300), -1);
        let bytes = serializer.serialize_event(event);

        let expected = vec![
            b'x', // Exit event type
            0x1E, // id (30) in LEB128
            0xAC, 0x02, // relative time (300) in LEB128
            0x00, // status (clamped to 0) in LEB128
        ];

        assert_eq!(bytes, expected);
        assert_eq!(serializer.0.as_micros(), 5300);
    }

    #[test]
    fn test_serialize_eot() {
        let mut serializer = EventSerializer(Duration::from_micros(5000));
        let event = Event::Eot(30.into(), Duration::from_micros(5300));
        let bytes = serializer.serialize_event(event);

        let expected = vec![
            0x04, // EOT event type
            0x1E, // id (30) in LEB128
            0xAC, 0x02, // relative time (300) in LEB128
        ];

        assert_eq!(bytes, expected);
        assert_eq!(serializer.0.as_micros(), 5300);
    }

    #[test]
    fn test_subsequent_event_lower_time() {
        let mut serializer = EventSerializer(Duration::from_micros(1000));

        // First event at time 1000
        let event1 = Event::Output(1.into(), Duration::from_micros(1000), "first".to_string());
        let bytes1 = serializer.serialize_event(event1);

        // Verify first event uses time 0 (1000 - 1000)
        assert_eq!(bytes1[2], 0x00); // relative time should be 0
        assert_eq!(serializer.0.as_micros(), 1000);

        // Second event with lower timestamp (wraparound risk case)
        let event2 = Event::Output(2.into(), Duration::from_micros(500), "second".to_string());
        let bytes2 = serializer.serialize_event(event2);

        assert_eq!(bytes2[2], 0x00); // relative time should be 0
        assert_eq!(serializer.0.as_micros(), 1000); // Time should remain 1000 (not decrease)
    }

    fn rgb(r: u8, g: u8, b: u8) -> RGB8 {
        RGB8::new(r, g, b)
    }
}


================================================
FILE: src/api.rs
================================================
use std::collections::HashMap;
use std::env;
use std::fmt::Debug;

use anyhow::{bail, Context, Result};
use reqwest::{header, Response};
use reqwest::{multipart::Form, Client, RequestBuilder};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use url::Url;

use crate::config::Config;

#[derive(Debug, Deserialize)]
pub struct RecordingResponse {
    pub url: String,
    pub message: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct StreamResponse {
    pub id: u64,
    pub ws_producer_url: String,
    pub url: String,
}

#[derive(Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Visibility {
    Public,
    Unlisted,
    Private,
}

#[derive(Default, Serialize)]
pub struct RecordingChangeset {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<Option<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<Option<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub visibility: Option<Visibility>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub audio_url: Option<Option<String>>,
}

#[derive(Default, Serialize)]
pub struct StreamChangeset {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub live: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<Option<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<Option<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub visibility: Option<Visibility>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub audio_url: Option<Option<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub term_type: Option<Option<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub term_version: Option<Option<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shell: Option<Option<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub env: Option<Option<HashMap<String, String>>>,
}

#[derive(Debug, Deserialize)]
struct ErrorResponse {
    message: String,
}

pub fn get_auth_url(config: &mut Config) -> Result<Url> {
    let mut url = config.get_server_url()?;
    url.set_path(&format!("connect/{}", config.get_install_id()?));

    Ok(url)
}

pub async fn create_recording(
    path: &str,
    changeset: RecordingChangeset,
    config: &mut Config,
) -> Result<RecordingResponse> {
    let server_url = &config.get_server_url()?;
    let install_id = config.get_install_id()?;

    let response = create_recording_request(server_url, install_id, path, changeset)
        .await?
        .send()
        .await?;

    if response.status().as_u16() == 413 {
        match response.json::<ErrorResponse>().await {
            Ok(json) => {
                bail!("{}", json.message);
            }

            Err(_) => {
                bail!("The recording exceeds the server-configured size limit");
            }
        }
    } else {
        response.error_for_status_ref()?;
    }

    Ok(response.json::<RecordingResponse>().await?)
}

async fn create_recording_request(
    server_url: &Url,
    install_id: String,
    path: &str,
    changeset: RecordingChangeset,
) -> Result<RequestBuilder> {
    let client = Client::new();
    let mut url = server_url.clone();
    url.set_path("api/v1/recordings");
    let form = Form::new().file("file", path).await?;
    let form = add_recording_changeset_fields(form, changeset);
    let builder = client.post(url).multipart(form);

    Ok(add_headers(builder, &install_id))
}

fn add_recording_changeset_fields(mut form: Form, changeset: RecordingChangeset) -> Form {
    if let Some(Some(title)) = changeset.title {
        form = form.text("title", title);
    }

    if let Some(Some(description)) = changeset.description {
        form = form.text("description", description);
    }

    if let Some(visibility) = changeset.visibility {
        let visibility = match visibility {
            Visibility::Public => "public",
            Visibility::Unlisted => "unlisted",
            Visibility::Private => "private",
        };

        form = form.text("visibility", visibility);
    }

    if let Some(Some(audio_url)) = changeset.audio_url {
        form = form.text("audio_url", audio_url);
    }

    form
}

pub async fn list_user_streams(prefix: &str, config: &mut Config) -> Result<Vec<StreamResponse>> {
    let server_url = config.get_server_url()?;
    let install_id = config.get_install_id()?;

    let response = list_user_streams_request(&server_url, prefix, &install_id)
        .send()
        .await
        .context("cannot obtain stream producer endpoint - is the server down?")?;

    parse_stream_response(response, &server_url).await
}

fn list_user_streams_request(server_url: &Url, prefix: &str, install_id: &str) -> RequestBuilder {
    let client = Client::new();
    let mut url = server_url.clone();
    url.set_path("api/v1/user/streams");
    url.set_query(Some(&format!("prefix={prefix}&limit=10")));

    add_headers(client.get(url), install_id)
}

pub async fn create_stream(
    changeset: StreamChangeset,
    config: &mut Config,
) -> Result<StreamResponse> {
    let server_url = config.get_server_url()?;
    let install_id = config.get_install_id()?;

    let response = create_stream_request(&server_url, &install_id, changeset)
        .send()
        .await
        .context("cannot obtain stream producer endpoint - is the server down?")?;

    parse_stream_response(response, &server_url).await
}

fn create_stream_request(
    server_url: &Url,
    install_id: &str,
    changeset: StreamChangeset,
) -> RequestBuilder {
    let client = Client::new();
    let mut url = server_url.clone();
    url.set_path("api/v1/streams");
    let builder = client.post(url);
    let builder = add_headers(builder, install_id);

    builder.json(&changeset)
}

pub async fn update_stream(
    stream_id: u64,
    changeset: StreamChangeset,
    config: &mut Config,
) -> Result<StreamResponse> {
    let server_url = config.get_server_url()?;
    let install_id = config.get_install_id()?;

    let response = update_stream_request(&server_url, &install_id, stream_id, changeset)
        .send()
        .await
        .context("cannot obtain stream producer endpoint - is the server down?")?;

    parse_stream_response(response, &server_url).await
}

fn update_stream_request(
    server_url: &Url,
    install_id: &str,
    stream_id: u64,
    changeset: StreamChangeset,
) -> RequestBuilder {
    let client = Client::new();
    let mut url = server_url.clone();
    url.set_path(&format!("api/v1/streams/{stream_id}"));
    let builder = client.patch(url);
    let builder = add_headers(builder, install_id);

    builder.json(&changeset)
}

async fn parse_stream_response<T: DeserializeOwned>(
    response: Response,
    server_url: &Url,
) -> Result<T> {
    let server_hostname = server_url.host().unwrap();

    match response.status().as_u16() {
        401 => bail!(
            "this CLI hasn't been authenticated with {server_hostname} - run `asciinema auth` first"
        ),

        404 => match response.json::<ErrorResponse>().await {
            Ok(json) => bail!("{}", json.message),
            Err(_) => bail!("{server_hostname} doesn't support streaming"),
        },

        422 => match response.json::<ErrorResponse>().await {
            Ok(json) => bail!("{}", json.message),
            Err(_) => bail!("{server_hostname} doesn't support streaming"),
        },

        _ => {
            response.error_for_status_ref()?;
        }
    }

    response.json::<T>().await.map_err(|e| e.into())
}

fn add_headers(builder: RequestBuilder, install_id: &str) -> RequestBuilder {
    builder
        .basic_auth(get_username(), Some(install_id))
        .header(header::USER_AGENT, build_user_agent())
        .header(header::ACCEPT, "application/json")
}

fn get_username() -> String {
    env::var("USER").unwrap_or("".to_owned())
}

pub fn build_user_agent() -> String {
    let ua = concat!(
        "asciinema/",
        env!("CARGO_PKG_VERSION"),
        " target/",
        env!("TARGET")
    );

    ua.to_owned()
}


================================================
FILE: src/asciicast/util.rs
================================================
use std::time::Duration;

use anyhow::Result;
use serde::{Deserialize, Deserializer};

pub fn deserialize_time<'de, D>(deserializer: D) -> Result<Duration, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de::Error;

    let value: serde_json::Value = Deserialize::deserialize(deserializer)?;

    let number = value
        .as_f64()
        .map(|v| v.to_string())
        .ok_or(Error::custom("expected number"))?;

    let parts: Vec<&str> = number.split('.').collect();

    match parts.as_slice() {
        [left, right] => {
            let secs: u64 = left.parse().map_err(Error::custom)?;
            let right = right.trim();

            let micros: u64 = format!("{:0<6}", &right[..(6.min(right.len()))])
                .parse()
                .map_err(Error::custom)?;

            Ok(Duration::from_micros(secs * 1_000_000 + micros))
        }

        [number] => {
            let secs: u64 = number.parse().map_err(Error::custom)?;

            Ok(Duration::from_micros(secs * 1_000_000))
        }

        _ => Err(Error::custom(format!("invalid time format: {value}"))),
    }
}


================================================
FILE: src/asciicast/v1.rs
================================================
use std::collections::HashMap;
use std::time::Duration;

use anyhow::{bail, Result};
use serde::Deserialize;

use super::{Asciicast, Event, Header, Version};
use crate::asciicast::util::deserialize_time;

#[derive(Debug, Deserialize)]
struct V1 {
    version: u8,
    width: u16,
    height: u16,
    command: Option<String>,
    title: Option<String>,
    env: Option<HashMap<String, Option<String>>>,
    stdout: Vec<V1OutputEvent>,
}

#[derive(Debug, Deserialize)]
struct V1OutputEvent {
    #[serde(deserialize_with = "deserialize_time")]
    time: Duration,
    data: String,
}

pub fn load(json: String) -> Result<Asciicast<'static>> {
    let asciicast: V1 = serde_json::from_str(&json)?;

    if asciicast.version != 1 {
        bail!("unsupported asciicast version")
    }

    let term_type = asciicast
        .env
        .as_ref()
        .map(|env| env.get("TERM"))
        .unwrap_or_default()
        .cloned()
        .unwrap_or_default();

    let env = asciicast.env.map(|env| {
        env.into_iter()
            .filter_map(|(k, v)| v.map(|v| (k, v)))
            .collect()
    });

    let header = Header {
        term_cols: asciicast.width,
        term_rows: asciicast.height,
        term_type,
        term_version: None,
        term_theme: None,
        timestamp: None,
        idle_time_limit: None,
        command: asciicast.command.clone(),
        title: asciicast.title.clone(),
        env,
    };

    let events = Box::new(asciicast.stdout.into_iter().scan(
        Duration::from_micros(0),
        |prev_time, event| {
            let time = *prev_time + event.time;
            *prev_time = time;

            Some(Ok(Event::output(time, event.data)))
        },
    ));

    Ok(Asciicast {
        version: Version::One,
        header,
        events,
    })
}


================================================
FILE: src/asciicast/v2.rs
================================================
use std::collections::HashMap;
use std::fmt;
use std::io;
use std::time::Duration;

use anyhow::{anyhow, bail, Context, Result};
use serde::{Deserialize, Deserializer, Serialize};

use super::{util, Asciicast, Event, EventData, Header, Version};
use crate::tty::TtyTheme;

#[derive(Deserialize)]
struct V2Header {
    version: u8,
    width: u16,
    height: u16,
    timestamp: Option<u64>,
    idle_time_limit: Option<f64>,
    command: Option<String>,
    title: Option<String>,
    env: Option<HashMap<String, Option<String>>>,
    theme: Option<V2Theme>,
}

#[derive(Deserialize, Serialize, Clone)]
struct V2Theme {
    #[serde(deserialize_with = "deserialize_color")]
    fg: RGB8,
    #[serde(deserialize_with = "deserialize_color")]
    bg: RGB8,
    #[serde(deserialize_with = "deserialize_palette")]
    palette: V2Palette,
}

#[derive(Clone)]
struct RGB8(rgb::RGB8);

#[derive(Clone)]
struct V2Palette(Vec<RGB8>);

#[derive(Debug, Deserialize)]
struct V2Event {
    #[serde(deserialize_with = "util::deserialize_time")]
    time: Duration,
    #[serde(deserialize_with = "deserialize_code")]
    code: V2EventCode,
    data: String,
}

#[derive(PartialEq, Debug)]
enum V2EventCode {
    Output,
    Input,
    Resize,
    Marker,
    Other(char),
}

pub struct Parser(V2Header);

pub fn open(header_line: &str) -> Result<Parser> {
    let header = serde_json::from_str::<V2Header>(header_line)?;

    if header.version != 2 {
        bail!("not an asciicast v2 file")
    }

    Ok(Parser(header))
}

impl Parser {
    pub fn parse<'a, I: Iterator<Item = io::Result<String>> + Send + 'a>(
        self,
        lines: I,
    ) -> Asciicast<'a> {
        let term_type = self
            .0
            .env
            .as_ref()
            .map(|env| env.get("TERM").cloned())
            .unwrap_or_default()
            .unwrap_or_default();

        let term_theme = self.0.theme.as_ref().map(|t| t.into());

        let env = self.0.env.map(|env| {
            env.into_iter()
                .filter_map(|(k, v)| v.map(|v| (k, v)))
                .collect()
        });

        let header = Header {
            term_cols: self.0.width,
            term_rows: self.0.height,
            term_type,
            term_version: None,
            term_theme,
            timestamp: self.0.timestamp,
            idle_time_limit: self.0.idle_time_limit,
            command: self.0.command.clone(),
            title: self.0.title.clone(),
            env,
        };

        let events = Box::new(lines.filter_map(parse_line));

        Asciicast {
            version: Version::Two,
            header,
            events,
        }
    }
}

fn parse_line(line: io::Result<String>) -> Option<Result<Event>> {
    match line {
        Ok(line) => {
            if line.is_empty() {
                None
            } else {
                Some(parse_event(line))
            }
        }

        Err(e) => Some(Err(e.into())),
    }
}

fn parse_event(line: String) -> Result<Event> {
    let event = serde_json::from_str::<V2Event>(&line).context("asciicast v2 parse error")?;

    let data = match event.code {
        V2EventCode::Output => EventData::Output(event.data),
        V2EventCode::Input => EventData::Input(event.data),

        V2EventCode::Resize => match event.data.split_once('x') {
            Some((cols, rows)) => {
                let cols: u16 = cols
                    .parse()
                    .map_err(|e| anyhow!("invalid cols value in resize event: {e}"))?;

                let rows: u16 = rows
                    .parse()
                    .map_err(|e| anyhow!("invalid rows value in resize event: {e}"))?;

                EventData::Resize(cols, rows)
            }

            None => {
                bail!("invalid size value in resize event");
            }
        },

        V2EventCode::Marker => EventData::Marker(event.data),
        V2EventCode::Other(c) => EventData::Other(c, event.data),
    };

    Ok(Event {
        time: event.time,
        data,
    })
}

fn deserialize_code<'de, D>(deserializer: D) -> Result<V2EventCode, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de::Error;
    use V2EventCode::*;

    let value: &str = Deserialize::deserialize(deserializer)?;

    match value {
        "o" => Ok(Output),
        "i" => Ok(Input),
        "r" => Ok(Resize),
        "m" => Ok(Marker),
        "" => Err(Error::custom("missing event code")),
        s => Ok(Other(s.chars().next().unwrap())),
    }
}

pub struct V2Encoder {
    time_offset: Duration,
}

impl V2Encoder {
    pub fn new(time_offset: Duration) -> Self {
        Self { time_offset }
    }

    pub fn header(&mut self, header: &Header) -> Vec<u8> {
        let header: V2Header = header.into();
        let mut data = serde_json::to_string(&header).unwrap().into_bytes();
        data.push(b'\n');

        data
    }

    pub fn event(&mut self, event: &Event) -> Vec<u8> {
        let mut data = self.serialize_event(event).into_bytes();
        data.push(b'\n');

        data
    }

    fn serialize_event(&self, event: &Event) -> String {
        use EventData::*;

        let (code, data) = match &event.data {
            Output(data) => ('o', self.to_json_string(data)),
            Input(data) => ('i', self.to_json_string(data)),
            Resize(cols, rows) => ('r', self.to_json_string(&format!("{cols}x{rows}"))),
            Marker(data) => ('m', self.to_json_string(data)),
            Exit(data) => ('x', self.to_json_string(&data.to_string())),
            Other(code, data) => (*code, self.to_json_string(data)),
        };

        format!(
            "[{}, {}, {}]",
            format_time(event.time + self.time_offset),
            self.to_json_string(&code.to_string()),
            data,
        )
    }

    fn to_json_string(&self, s: &str) -> String {
        serde_json::to_string(s).unwrap()
    }
}

fn format_time(time: Duration) -> String {
    let time = time.as_micros();
    let mut formatted_time = format!("{}.{:0>6}", time / 1_000_000, time % 1_000_000);
    let dot_idx = formatted_time.find('.').unwrap();

    for idx in (dot_idx + 2..=formatted_time.len() - 1).rev() {
        if formatted_time.as_bytes()[idx] != b'0' {
            break;
        }

        formatted_time.truncate(idx);
    }

    formatted_time
}

impl serde::Serialize for V2Header {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeMap;

        let mut len = 4;

        if self.timestamp.is_some() {
            len += 1;
        }

        if self.idle_time_limit.is_some() {
            len += 1;
        }

        if self.command.is_some() {
            len += 1;
        }

        if self.title.is_some() {
            len += 1;
        }

        if self.env.as_ref().is_some_and(|env| !env.is_empty()) {
            len += 1;
        }

        if self.theme.is_some() {
            len += 1;
        }

        let mut map = serializer.serialize_map(Some(len))?;
        map.serialize_entry("version", &2)?;
        map.serialize_entry("width", &self.width)?;
        map.serialize_entry("height", &self.height)?;

        if let Some(timestamp) = self.timestamp {
            map.serialize_entry("timestamp", &timestamp)?;
        }

        if let Some(limit) = self.idle_time_limit {
            map.serialize_entry("idle_time_limit", &limit)?;
        }

        if let Some(command) = &self.command {
            map.serialize_entry("command", &command)?;
        }

        if let Some(title) = &self.title {
            map.serialize_entry("title", &title)?;
        }

        if let Some(env) = &self.env {
            if !env.is_empty() {
                map.serialize_entry("env", &env)?;
            }
        }

        if let Some(theme) = &self.theme {
            map.serialize_entry("theme", &theme)?;
        }

        map.end()
    }
}

fn deserialize_color<'de, D>(deserializer: D) -> Result<RGB8, D::Error>
where
    D: Deserializer<'de>,
{
    let value: &str = Deserialize::deserialize(deserializer)?;
    parse_hex_color(value).ok_or(serde::de::Error::custom("invalid hex triplet"))
}

fn parse_hex_color(rgb: &str) -> Option<RGB8> {
    if rgb.len() != 7 {
        return None;
    }

    let r = u8::from_str_radix(&rgb[1..3], 16).ok()?;
    let g = u8::from_str_radix(&rgb[3..5], 16).ok()?;
    let b = u8::from_str_radix(&rgb[5..7], 16).ok()?;

    Some(RGB8(rgb::RGB8::new(r, g, b)))
}

fn deserialize_palette<'de, D>(deserializer: D) -> Result<V2Palette, D::Error>
where
    D: Deserializer<'de>,
{
    let value: &str = Deserialize::deserialize(deserializer)?;
    let mut colors: Vec<RGB8> = value.split(':').filter_map(parse_hex_color).collect();
    let len = colors.len();

    if len == 8 {
        colors.extend_from_within(..);
    } else if len != 16 {
        return Err(serde::de::Error::custom("expected 8 or 16 hex triplets"));
    }

    Ok(V2Palette(colors))
}

impl serde::Serialize for RGB8 {
    fn serialize<S>(&self, serializer: S) -> std::prelude::v1::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

impl fmt::Display for RGB8 {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> fmt::Result {
        write!(f, "#{:0>2x}{:0>2x}{:0>2x}", self.0.r, self.0.g, self.0.b)
    }
}

impl serde::Serialize for V2Palette {
    fn serialize<S>(&self, serializer: S) -> std::prelude::v1::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let palette = self
            .0
            .iter()
            .map(|c| c.to_string())
            .collect::<Vec<_>>()
            .join(":");

        serializer.serialize_str(&palette)
    }
}

impl From<&Header> for V2Header {
    fn from(header: &Header) -> Self {
        let env = header
            .env
            .clone()
            .map(|env| env.into_iter().map(|(k, v)| (k, Some(v))).collect());

        V2Header {
            version: 2,
            width: header.term_cols,
            height: header.term_rows,
            timestamp: header.timestamp,
            idle_time_limit: header.idle_time_limit,
            command: header.command.clone(),
            title: header.title.clone(),
            env,
            theme: header.term_theme.as_ref().map(|t| t.into()),
        }
    }
}

impl From<&TtyTheme> for V2Theme {
    fn from(tty_theme: &TtyTheme) -> Self {
        let palette = tty_theme.palette.iter().copied().map(RGB8).collect();

        V2Theme {
            fg: RGB8(tty_theme.fg),
            bg: RGB8(tty_theme.bg),
            palette: V2Palette(palette),
        }
    }
}

impl From<&V2Theme> for TtyTheme {
    fn from(tty_theme: &V2Theme) -> Self {
        let palette = tty_theme.palette.0.iter().map(|c| c.0).collect();

        TtyTheme {
            fg: tty_theme.fg.0,
            bg: tty_theme.bg.0,
            palette,
        }
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    #[test]
    fn format_time() {
        assert_eq!(super::format_time(Duration::from_micros(0)), "0.0");
        assert_eq!(
            super::format_time(Duration::from_micros(1000001)),
            "1.000001"
        );
        assert_eq!(super::format_time(Duration::from_micros(12300000)), "12.3");
        assert_eq!(
            super::format_time(Duration::from_micros(12000003)),
            "12.000003"
        );
    }
}


================================================
FILE: src/asciicast/v3.rs
================================================
use std::collections::HashMap;
use std::fmt;
use std::io;
use std::time::Duration;

use anyhow::{anyhow, bail, Context, Result};
use serde::{Deserialize, Deserializer, Serialize};

use super::{util, Asciicast, Event, EventData, Header, Version};
use crate::tty::TtyTheme;
use crate::util::Quantizer;

#[derive(Deserialize)]
struct V3Header {
    version: u8,
    term: V3Term,
    timestamp: Option<u64>,
    idle_time_limit: Option<f64>,
    command: Option<String>,
    title: Option<String>,
    env: Option<HashMap<String, String>>,
}

#[derive(Deserialize)]
struct V3Term {
    cols: u16,
    rows: u16,
    #[serde(rename = "type")]
    type_: Option<String>,
    version: Option<String>,
    theme: Option<V3Theme>,
}

#[derive(Deserialize, Serialize, Clone)]
struct V3Theme {
    #[serde(deserialize_with = "deserialize_color")]
    fg: RGB8,
    #[serde(deserialize_with = "deserialize_color")]
    bg: RGB8,
    #[serde(deserialize_with = "deserialize_palette")]
    palette: V3Palette,
}

#[derive(Clone)]
struct RGB8(rgb::RGB8);

#[derive(Clone)]
struct V3Palette(Vec<RGB8>);

#[derive(Debug, Deserialize)]
struct V3Event {
    #[serde(deserialize_with = "util::deserialize_time")]
    time: Duration,
    #[serde(deserialize_with = "deserialize_code")]
    code: V3EventCode,
    data: String,
}

#[derive(PartialEq, Debug)]
enum V3EventCode {
    Output,
    Input,
    Resize,
    Marker,
    Exit,
    Other(char),
}

pub struct Parser {
    header: V3Header,
    prev_time: Duration,
}

pub fn open(header_line: &str) -> Result<Parser> {
    let header = serde_json::from_str::<V3Header>(header_line)?;

    if header.version != 3 {
        bail!("not an asciicast v3 file")
    }

    Ok(Parser {
        header,
        prev_time: Duration::from_micros(0),
    })
}

impl Parser {
    pub fn parse<'a, I: Iterator<Item = io::Result<String>> + Send + 'a>(
        mut self,
        lines: I,
    ) -> Asciicast<'a> {
        let term_theme = self.header.term.theme.as_ref().map(|t| t.into());

        let header = Header {
            term_cols: self.header.term.cols,
            term_rows: self.header.term.rows,
            term_type: self.header.term.type_.clone(),
            term_version: self.header.term.version.clone(),
            term_theme,
            timestamp: self.header.timestamp,
            idle_time_limit: self.header.idle_time_limit,
            command: self.header.command.clone(),
            title: self.header.title.clone(),
            env: self.header.env.clone(),
        };

        let events = Box::new(lines.filter_map(move |line| self.parse_line(line)));

        Asciicast {
            version: Version::Three,
            header,
            events,
        }
    }

    fn parse_line(&mut self, line: io::Result<String>) -> Option<Result<Event>> {
        match line {
            Ok(line) => {
                if line.is_empty() || line.starts_with('#') {
                    None
                } else {
                    Some(self.parse_event(line))
                }
            }

            Err(e) => Some(Err(e.into())),
        }
    }

    fn parse_event(&mut self, line: String) -> Result<Event> {
        let event = serde_json::from_str::<V3Event>(&line).context("asciicast v3 parse error")?;

        let data = match event.code {
            V3EventCode::Output => EventData::Output(event.data),
            V3EventCode::Input => EventData::Input(event.data),

            V3EventCode::Resize => match event.data.split_once('x') {
                Some((cols, rows)) => {
                    let cols: u16 = cols
                        .parse()
                        .map_err(|e| anyhow!("invalid cols value in resize event: {e}"))?;

                    let rows: u16 = rows
                        .parse()
                        .map_err(|e| anyhow!("invalid rows value in resize event: {e}"))?;

                    EventData::Resize(cols, rows)
                }

                None => {
                    bail!("invalid size value in resize event");
                }
            },

            V3EventCode::Marker => EventData::Marker(event.data),
            V3EventCode::Exit => EventData::Exit(event.data.parse()?),
            V3EventCode::Other(c) => EventData::Other(c, event.data),
        };

        let time = self.prev_time + event.time;
        self.prev_time = time;

        Ok(Event { time, data })
    }
}

fn deserialize_code<'de, D>(deserializer: D) -> Result<V3EventCode, D::Error>
where
    D: Deserializer<'de>,
{
    use serde::de::Error;
    use V3EventCode::*;

    let value: &str = Deserialize::deserialize(deserializer)?;

    match value {
        "o" => Ok(Output),
        "i" => Ok(Input),
        "r" => Ok(Resize),
        "m" => Ok(Marker),
        "x" => Ok(Exit),
        "" => Err(Error::custom("missing event code")),
        s => Ok(Other(s.chars().next().unwrap())),
    }
}

pub struct V3Encoder {
    prev_time: Duration,
    time_quantizer: Quantizer,
}

impl V3Encoder {
    pub fn new() -> Self {
        Self {
            prev_time: Duration::from_micros(0),
            time_quantizer: Quantizer::new(1_000_000),
        }
    }

    pub fn header(&mut self, header: &Header) -> Vec<u8> {
        let header: V3Header = header.into();
        let mut data = serde_json::to_string(&header).unwrap().into_bytes();
        data.push(b'\n');

        data
    }

    pub fn event(&mut self, event: &Event) -> Vec<u8> {
        let mut data = self.serialize_event(event).into_bytes();
        data.push(b'\n');

        data
    }

    fn serialize_event(&mut self, event: &Event) -> String {
        use EventData::*;

        let (code, data) = match &event.data {
            Output(data) => ('o', self.to_json_string(data)),
            Input(data) => ('i', self.to_json_string(data)),
            Resize(cols, rows) => ('r', self.to_json_string(&format!("{cols}x{rows}"))),
            Marker(data) => ('m', self.to_json_string(data)),
            Exit(data) => ('x', self.to_json_string(&data.to_string())),
            Other(code, data) => (*code, self.to_json_string(data)),
        };

        let dt = event.time - self.prev_time;
        self.prev_time = event.time;
        let dt = Duration::from_nanos(self.time_quantizer.next(dt.as_nanos()) as u64);

        format!(
            "[{}, {}, {}]",
            format_duration(dt),
            self.to_json_string(&code.to_string()),
            data,
        )
    }

    fn to_json_string(&self, s: &str) -> String {
        serde_json::to_string(s).unwrap()
    }
}

fn format_duration(duration: Duration) -> String {
    let time_ms = duration.as_millis();
    let secs = time_ms / 1_000;
    let millis = time_ms % 1_000;

    format!("{}.{}", secs, format!("{:03}", millis))
}

impl serde::Serialize for V3Header {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeMap;

        let mut len = 2;

        if self.timestamp.is_some() {
            len += 1;
        }

        if self.idle_time_limit.is_some() {
            len += 1;
        }

        if self.command.is_some() {
            len += 1;
        }

        if self.title.is_some() {
            len += 1;
        }

        if self.env.as_ref().is_some_and(|env| !env.is_empty()) {
            len += 1;
        }

        let mut map = serializer.serialize_map(Some(len))?;
        map.serialize_entry("version", &3)?;
        map.serialize_entry("term", &self.term)?;

        if let Some(timestamp) = self.timestamp {
            map.serialize_entry("timestamp", &timestamp)?;
        }

        if let Some(limit) = self.idle_time_limit {
            map.serialize_entry("idle_time_limit", &limit)?;
        }

        if let Some(command) = &self.command {
            map.serialize_entry("command", &command)?;
        }

        if let Some(title) = &self.title {
            map.serialize_entry("title", &title)?;
        }

        if let Some(env) = &self.env {
            if !env.is_empty() {
                map.serialize_entry("env", &env)?;
            }
        }
        map.end()
    }
}

impl serde::Serialize for V3Term {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeMap;

        let mut len = 2;

        if self.type_.is_some() {
            len += 1;
        }

        if self.version.is_some() {
            len += 1;
        }

        if self.theme.is_some() {
            len += 1;
        }

        let mut map = serializer.serialize_map(Some(len))?;
        map.serialize_entry("cols", &self.cols)?;
        map.serialize_entry("rows", &self.rows)?;

        if let Some(type_) = &self.type_ {
            map.serialize_entry("type", &type_)?;
        }

        if let Some(version) = &self.version {
            map.serialize_entry("version", &version)?;
        }

        if let Some(theme) = &self.theme {
            map.serialize_entry("theme", &theme)?;
        }

        map.end()
    }
}

fn deserialize_color<'de, D>(deserializer: D) -> Result<RGB8, D::Error>
where
    D: Deserializer<'de>,
{
    let value: &str = Deserialize::deserialize(deserializer)?;
    parse_hex_color(value).ok_or(serde::de::Error::custom("invalid hex triplet"))
}

fn parse_hex_color(rgb: &str) -> Option<RGB8> {
    if rgb.len() != 7 {
        return None;
    }

    let r = u8::from_str_radix(&rgb[1..3], 16).ok()?;
    let g = u8::from_str_radix(&rgb[3..5], 16).ok()?;
    let b = u8::from_str_radix(&rgb[5..7], 16).ok()?;

    Some(RGB8(rgb::RGB8::new(r, g, b)))
}

fn deserialize_palette<'de, D>(deserializer: D) -> Result<V3Palette, D::Error>
where
    D: Deserializer<'de>,
{
    let value: &str = Deserialize::deserialize(deserializer)?;
    let mut colors: Vec<RGB8> = value.split(':').filter_map(parse_hex_color).collect();
    let len = colors.len();

    if len == 8 {
        colors.extend_from_within(..);
    } else if len != 16 {
        return Err(serde::de::Error::custom("expected 8 or 16 hex triplets"));
    }

    Ok(V3Palette(colors))
}

impl serde::Serialize for RGB8 {
    fn serialize<S>(&self, serializer: S) -> std::prelude::v1::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

impl fmt::Display for RGB8 {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> fmt::Result {
        write!(f, "#{:0>2x}{:0>2x}{:0>2x}", self.0.r, self.0.g, self.0.b)
    }
}

impl serde::Serialize for V3Palette {
    fn serialize<S>(&self, serializer: S) -> std::prelude::v1::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let palette = self
            .0
            .iter()
            .map(|c| c.to_string())
            .collect::<Vec<_>>()
            .join(":");

        serializer.serialize_str(&palette)
    }
}

impl From<&Header> for V3Header {
    fn from(header: &Header) -> Self {
        V3Header {
            version: 3,
            term: V3Term {
                cols: header.term_cols,
                rows: header.term_rows,
                type_: header.term_type.clone(),
                version: header.term_version.clone(),
                theme: header.term_theme.as_ref().map(|t| t.into()),
            },
            timestamp: header.timestamp,
            idle_time_limit: header.idle_time_limit,
            command: header.command.clone(),
            title: header.title.clone(),
            env: header.env.clone(),
        }
    }
}

impl From<&TtyTheme> for V3Theme {
    fn from(tty_theme: &TtyTheme) -> Self {
        let palette = tty_theme.palette.iter().copied().map(RGB8).collect();

        V3Theme {
            fg: RGB8(tty_theme.fg),
            bg: RGB8(tty_theme.bg),
            palette: V3Palette(palette),
        }
    }
}

impl From<&V3Theme> for TtyTheme {
    fn from(tty_theme: &V3Theme) -> Self {
        let palette = tty_theme.palette.0.iter().map(|c| c.0).collect();

        TtyTheme {
            fg: tty_theme.fg.0,
            bg: tty_theme.bg.0,
            palette,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::format_duration;
    use std::time::Duration;

    #[test]
    fn format_time() {
        assert_eq!(format_duration(Duration::from_millis(0)), "0.000");
        assert_eq!(format_duration(Duration::from_millis(666)), "0.666");
        assert_eq!(format_duration(Duration::from_millis(1000)), "1.000");
        assert_eq!(format_duration(Duration::from_millis(12345)), "12.345");
    }
}


================================================
FILE: src/asciicast.rs
================================================
mod util;
mod v1;
mod v2;
mod v3;

use std::collections::HashMap;
use std::fmt::Display;
use std::fs;
use std::io::{self, BufRead};
use std::path::Path;
use std::time::Duration;

use anyhow::{anyhow, Result};

use crate::tty::TtyTheme;
pub use v2::V2Encoder;
pub use v3::V3Encoder;

pub struct Asciicast<'a> {
    pub version: Version,
    pub header: Header,
    pub events: Box<dyn Iterator<Item = Result<Event>> + Send + 'a>,
}

#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Version {
    One,
    Two,
    Three,
}

pub struct Header {
    pub term_cols: u16,
    pub term_rows: u16,
    pub term_type: Option<String>,
    pub term_version: Option<String>,
    pub term_theme: Option<TtyTheme>,
    pub timestamp: Option<u64>,
    pub idle_time_limit: Option<f64>,
    pub command: Option<String>,
    pub title: Option<String>,
    pub env: Option<HashMap<String, String>>,
}

pub struct Event {
    pub time: Duration,
    pub data: EventData,
}

pub enum EventData {
    Output(String),
    Input(String),
    Resize(u16, u16),
    Marker(String),
    Exit(i32),
    Other(char, String),
}

pub trait Encoder {
    fn header(&mut self, header: &Header) -> Vec<u8>;
    fn event(&mut self, event: &Event) -> Vec<u8>;
}

impl PartialEq<u8> for Version {
    fn eq(&self, other: &u8) -> bool {
        matches!(
            (self, other),
            (Version::One, 1) | (Version::Two, 2) | (Version::Three, 3)
        )
    }
}

impl Display for Version {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Version::One => write!(f, "1"),
            Version::Two => write!(f, "2"),
            Version::Three => write!(f, "3"),
        }
    }
}

impl Default for Header {
    fn default() -> Self {
        Self {
            term_cols: 80,
            term_rows: 24,
            term_type: None,
            term_version: None,
            term_theme: None,
            timestamp: None,
            idle_time_limit: None,
            command: None,
            title: None,
            env: None,
        }
    }
}

impl Encoder for V2Encoder {
    fn header(&mut self, header: &Header) -> Vec<u8> {
        self.header(header)
    }

    fn event(&mut self, event: &Event) -> Vec<u8> {
        self.event(event)
    }
}

impl Encoder for V3Encoder {
    fn header(&mut self, header: &Header) -> Vec<u8> {
        self.header(header)
    }

    fn event(&mut self, event: &Event) -> Vec<u8> {
        self.event(event)
    }
}

pub fn open_from_path<S: AsRef<Path>>(path: S) -> Result<Asciicast<'static>> {
    fs::File::open(&path)
        .map(io::BufReader::new)
        .map_err(|e| anyhow!(e))
        .and_then(open)
        .map_err(|e| anyhow!("can't open {}: {}", path.as_ref().to_string_lossy(), e))
}

pub fn open<'a, R: BufRead + Send + 'a>(reader: R) -> Result<Asciicast<'a>> {
    let mut lines = reader.lines();
    let first_line = lines.next().ok_or(anyhow!("empty file"))??;

    if let Ok(parser) = v3::open(&first_line) {
        Ok(parser.parse(lines))
    } else if let Ok(parser) = v2::open(&first_line) {
        Ok(parser.parse(lines))
    } else {
        let json = std::iter::once(Ok(first_line))
            .chain(lines)
            .collect::<io::Result<String>>()?;

        v1::load(json).map_err(|_| anyhow!("not a v1, v2, v3 asciicast file"))
    }
}

pub fn get_duration<S: AsRef<Path>>(path: S) -> Result<Duration> {
    let Asciicast { events, .. } = open_from_path(path)?;
    let time = events
        .last()
        .map_or(Ok(Duration::from_micros(0)), |e| e.map(|e| e.time))?;

    Ok(time)
}

impl Event {
    pub fn output(time: Duration, text: String) -> Self {
        Event {
            time,
            data: EventData::Output(text),
        }
    }

    pub fn input(time: Duration, text: String) -> Self {
        Event {
            time,
            data: EventData::Input(text),
        }
    }

    pub fn resize(time: Duration, size: (u16, u16)) -> Self {
        Event {
            time,
            data: EventData::Resize(size.0, size.1),
        }
    }

    pub fn marker(time: Duration, label: String) -> Self {
        Event {
            time,
            data: EventData::Marker(label),
        }
    }

    pub fn exit(time: Duration, status: i32) -> Self {
        Event {
            time,
            data: EventData::Exit(status),
        }
    }
}

pub fn limit_idle_time(
    events: impl Iterator<Item = Result<Event>> + Send,
    limit: f64,
) -> impl Iterator<Item = Result<Event>> + Send {
    let limit = Duration::from_micros((limit * 1_000_000.0) as u64);
    let mut prev_time = Duration::from_micros(0);
    let mut offset = Duration::from_micros(0);

    events.map(move |event| {
        event.map(|event| {
            let delay = event.time - prev_time;

            if delay > limit {
                offset += delay - limit;
            }

            prev_time = event.time;
            let time = event.time - offset;

            Event { time, ..event }
        })
    })
}

pub fn accelerate(
    events: impl Iterator<Item = Result<Event>> + Send,
    speed: f64,
) -> impl Iterator<Item = Result<Event>> + Send {
    events.map(move |event| {
        event.map(|event| {
            let time = event.time.div_f64(speed);

            Event { time, ..event }
        })
    })
}

pub fn encoder(version: Version) -> Option<Box<dyn Encoder>> {
    match version {
        Version::One => None,
        Version::Two => Some(Box::new(V2Encoder::new(Duration::from_micros(0)))),
        Version::Three => Some(Box::new(V3Encoder::new())),
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;
    use std::time::Duration;

    use anyhow::Result;
    use rgb::RGB8;

    use super::{Asciicast, Event, EventData, Header, V2Encoder};
    use crate::tty::TtyTheme;

    #[test]
    fn open_v1_minimal() {
        let Asciicast {
            version,
            header,
            events,
        } = super::open_from_path("tests/casts/minimal-v1.json").unwrap();

        let events = events.collect::<Result<Vec<Event>>>().unwrap();

        assert_eq!(version, 1);
        assert_eq!((header.term_cols, header.term_rows), (100, 50));
        assert!(header.term_theme.is_none());

        assert_eq!(events[0].time, Duration::from_micros(1230000));
        assert!(matches!(events[0].data, EventData::Output(ref s) if s == "hello"));
    }

    #[test]
    fn open_v1_full() {
        let Asciicast {
            version,
            header,
            events,
        } = super::open_from_path("tests/casts/full-v1.json").unwrap();
        let events = events.collect::<Result<Vec<Event>>>().unwrap();

        assert_eq!(version, 1);
        assert_eq!((header.term_cols, header.term_rows), (100, 50));

        let mut expected_env = HashMap::new();
        expected_env.insert("SHELL".to_owned(), "/bin/bash".to_owned());
        expected_env.insert("TERM".to_owned(), "xterm-256color".to_owned());
        assert_eq!(header.env.unwrap(), expected_env);

        assert_eq!(events[0].time, Duration::from_micros(1));
        assert!(matches!(events[0].data, EventData::Output(ref s) if s == "ż"));

        assert_eq!(events[1].time, Duration::from_micros(10000001));
        assert!(matches!(events[1].data, EventData::Output(ref s) if s == "ółć"));

        assert_eq!(events[2].time, Duration::from_micros(10500001));
        assert!(matches!(events[2].data, EventData::Output(ref s) if s == "\r\n"));
    }

    #[test]
    fn open_v1_with_nulls_in_header() {
        let Asciicast {
            version, header, ..
        } = super::open_from_path("tests/casts/nulls-v1.json").unwrap();
        assert_eq!(version, 1);

        let mut expected_env = HashMap::new();
        expected_env.insert("SHELL".to_owned(), "/bin/bash".to_owned());
        assert_eq!(header.env.unwrap(), expected_env);
    }

    #[test]
    fn open_v2_minimal() {
        let Asciicast {
            version,
            header,
            events,
        } = super::open_from_path("tests/casts/minimal-v2.cast").unwrap();

        let events = events.collect::<Result<Vec<Event>>>().unwrap();

        assert_eq!(version, 2);
        assert_eq!((header.term_cols, header.term_rows), (100, 50));
        assert!(header.term_theme.is_none());

        assert_eq!(events[0].time, Duration::from_micros(1230000));
        assert!(matches!(events[0].data, EventData::Output(ref s) if s == "hello"));
    }

    #[test]
    fn open_v2_full() {
        let Asciicast {
            version,
            header,
            events,
        } = super::open_from_path("tests/casts/full-v2.cast").unwrap();
        let events = events.take(5).collect::<Result<Vec<Event>>>().unwrap();
        let theme = header.term_theme.unwrap();

        assert_eq!(version, 2);
        assert_eq!((header.term_cols, header.term_rows), (100, 50));
        assert_eq!(header.timestamp, Some(1509091818));
        assert_eq!(theme.fg, RGB8::new(0, 0, 0));
        assert_eq!(theme.bg, RGB8::new(0xff, 0xff, 0xff));
        assert_eq!(theme.palette[0], RGB8::new(0x24, 0x1f, 0x31));

        let mut expected_env = HashMap::new();
        expected_env.insert("SHELL".to_owned(), "/bin/bash".to_owned());
        expected_env.insert("TERM".to_owned(), "xterm-256color".to_owned());
        assert_eq!(header.env.unwrap(), expected_env);

        assert_eq!(events[0].time, Duration::from_micros(1));
        assert!(matches!(events[0].data, EventData::Output(ref s) if s == "ż"));

        assert_eq!(events[1].time, Duration::from_micros(1_000_000));
        assert!(matches!(events[1].data, EventData::Output(ref s) if s == "ółć"));

        assert_eq!(events[2].time, Duration::from_micros(2_300_000));
        assert!(matches!(events[2].data, EventData::Input(ref s) if s == "\n"));

        assert_eq!(events[3].time, Duration::from_micros(5_600_001));

        assert!(
            matches!(events[3].data, EventData::Resize(ref cols, ref rows) if *cols == 80 && *rows == 40)
        );

        assert_eq!(events[4].time, Duration::from_micros(10_500_000));
        assert!(matches!(events[4].data, EventData::Output(ref s) if s == "\r\n"));
    }

    #[test]
    fn open_v2_with_nulls_in_header() {
        let Asciicast {
            version, header, ..
        } = super::open_from_path("tests/casts/nulls-v2.cast").unwrap();
        assert_eq!(version, 2);

        let mut expected_env = HashMap::new();
        expected_env.insert("SHELL".to_owned(), "/bin/bash".to_owned());
        assert_eq!(header.env.unwrap(), expected_env);
    }

    #[test]
    fn open_v3_minimal() {
        let Asciicast {
            version,
            header,
            events,
        } = super::open_from_path("tests/casts/minimal-v3.cast").unwrap();

        let events = events.collect::<Result<Vec<Event>>>().unwrap();

        assert_eq!(version, 3);
        assert_eq!((header.term_cols, header.term_rows), (100, 50));
        assert!(header.term_theme.is_none());

        assert_eq!(events[0].time, Duration::from_micros(1230000));
        assert!(matches!(events[0].data, EventData::Output(ref s) if s == "hello"));
    }

    #[test]
    fn open_v3_full() {
        let Asciicast {
            version,
            header,
            events,
        } = super::open_from_path("tests/casts/full-v3.cast").unwrap();
        let events = events.take(5).collect::<Result<Vec<Event>>>().unwrap();
        let theme = header.term_theme.unwrap();

        assert_eq!(version, 3);
        assert_eq!((header.term_cols, header.term_rows), (100, 50));
        assert_eq!(header.timestamp, Some(1509091818));
        assert_eq!(theme.fg, RGB8::new(0, 0, 0));
        assert_eq!(theme.bg, RGB8::new(0xff, 0xff, 0xff));
        assert_eq!(theme.palette[0], RGB8::new(0x24, 0x1f, 0x31));

        assert_eq!(events[0].time, Duration::from_micros(1));
        assert!(matches!(events[0].data, EventData::Output(ref s) if s == "ż"));

        assert_eq!(events[1].time, Duration::from_micros(1_000_001));
        assert!(matches!(events[1].data, EventData::Output(ref s) if s == "ółć"));

        assert_eq!(events[2].time, Duration::from_micros(1_300_001));
        assert!(matches!(events[2].data, EventData::Input(ref s) if s == "\n"));

        assert_eq!(events[3].time, Duration::from_micros(2_900_002));

        assert!(
            matches!(events[3].data, EventData::Resize(ref cols, ref rows) if *cols == 80 && *rows == 40)
        );

        assert_eq!(events[4].time, Duration::from_micros(13_400_002));
        assert!(matches!(events[4].data, EventData::Output(ref s) if s == "\r\n"));
    }

    #[test]
    fn encoder() {
        let mut data = Vec::new();
        let header = Header::default();
        let mut enc = V2Encoder::new(Duration::from_micros(0));
        data.extend(enc.header(&header));
        data.extend(enc.event(&Event::output(
            Duration::from_micros(1000000),
            "hello\r\n".to_owned(),
        )));

        let mut enc = V2Encoder::new(Duration::from_micros(1000001));
        data.extend(enc.event(&Event::output(
            Duration::from_micros(1000001),
            "world".to_owned(),
        )));
        data.extend(enc.event(&Event::input(
            Duration::from_micros(2000002),
            " ".to_owned(),
        )));
        data.extend(enc.event(&Event::resize(Duration::from_micros(3000003), (100, 40))));
        data.extend(enc.event(&Event::output(
            Duration::from_micros(4000004),
            "żółć".to_owned(),
        )));

        let lines = parse(data);

        assert_eq!(lines[0]["version"], 2);
        assert_eq!(lines[0]["width"], 80);
        assert_eq!(lines[0]["height"], 24);
        assert!(lines[0]["timestamp"].is_null());
        assert_eq!(lines[1][0], 1.000000);
        assert_eq!(lines[1][1], "o");
        assert_eq!(lines[1][2], "hello\r\n");
        assert_eq!(lines[2][0], 2.000002);
        assert_eq!(lines[2][1], "o");
        assert_eq!(lines[2][2], "world");
        assert_eq!(lines[3][0], 3.000003);
        assert_eq!(lines[3][1], "i");
        assert_eq!(lines[3][2], " ");
        assert_eq!(lines[4][0], 4.000004);
        assert_eq!(lines[4][1], "r");
        assert_eq!(lines[4][2], "100x40");
        assert_eq!(lines[5][0], 5.000005);
        assert_eq!(lines[5][1], "o");
        assert_eq!(lines[5][2], "żółć");
    }

    #[test]
    fn header_encoding() {
        let mut enc = V2Encoder::new(Duration::from_micros(0));
        let mut env = HashMap::new();
        env.insert("SHELL".to_owned(), "/usr/bin/fish".to_owned());
        env.insert("TERM".to_owned(), "xterm256-color".to_owned());

        let tty_theme = TtyTheme {
            fg: RGB8::new(0, 1, 2),
            bg: RGB8::new(0, 100, 200),
            palette: vec![
                RGB8::new(0, 0, 0),
                RGB8::new(10, 11, 12),
                RGB8::new(20, 21, 22),
                RGB8::new(30, 31, 32),
                RGB8::new(40, 41, 42),
                RGB8::new(50, 51, 52),
                RGB8::new(60, 61, 62),
                RGB8::new(70, 71, 72),
                RGB8::new(80, 81, 82),
                RGB8::new(90, 91, 92),
                RGB8::new(100, 101, 102),
                RGB8::new(110, 111, 112),
                RGB8::new(120, 121, 122),
                RGB8::new(130, 131, 132),
                RGB8::new(140, 141, 142),
                RGB8::new(150, 151, 152),
            ],
        };

        let header = Header {
            timestamp: Some(1704719152),
            idle_time_limit: Some(1.5),
            command: Some("/bin/bash".to_owned()),
            title: Some("Demo".to_owned()),
            env: Some(env),
            term_theme: Some(tty_theme),
            ..Default::default()
        };

        let data = enc.header(&header);
        let lines = parse(data);

        assert_eq!(lines[0]["version"], 2);
        assert_eq!(lines[0]["width"], 80);
        assert_eq!(lines[0]["height"], 24);
        assert_eq!(lines[0]["timestamp"], 1704719152);
        assert_eq!(lines[0]["idle_time_limit"], 1.5);
        assert_eq!(lines[0]["command"], "/bin/bash");
        assert_eq!(lines[0]["title"], "Demo");
        assert_eq!(lines[0]["env"].as_object().unwrap().len(), 2);
        assert_eq!(lines[0]["env"]["SHELL"], "/usr/bin/fish");
        assert_eq!(lines[0]["env"]["TERM"], "xterm256-color");
        assert_eq!(lines[0]["theme"]["fg"], "#000102");
        assert_eq!(lines[0]["theme"]["bg"], "#0064c8");
        assert_eq!(lines[0]["theme"]["palette"], "#000000:#0a0b0c:#141516:#1e1f20:#28292a:#323334:#3c3d3e:#464748:#505152:#5a5b5c:#646566:#6e6f70:#78797a:#828384:#8c8d8e:#969798");
    }

    fn parse(json: Vec<u8>) -> Vec<serde_json::Value> {
        String::from_utf8(json)
            .unwrap()
            .split('\n')
            .filter(|s| !s.is_empty())
            .map(serde_json::from_str::<serde_json::Value>)
            .collect::<serde_json::Result<Vec<_>>>()
            .unwrap()
    }

    #[test]
    fn accelerate() {
        let events = [(0u64, "foo"), (20, "bar"), (50, "baz")].map(|(time, output)| {
            Ok(Event::output(
                Duration::from_micros(time),
                output.to_owned(),
            ))
        });

        let output = output(super::accelerate(events.into_iter(), 2.0));

        assert_eq!(output[0], (Duration::from_micros(0), "foo".to_owned()));
        assert_eq!(output[1], (Duration::from_micros(10), "bar".to_owned()));
        assert_eq!(output[2], (Duration::from_micros(25), "baz".to_owned()));
    }

    #[test]
    fn limit_idle_time() {
        let events = [
            (0, "foo"),
            (1_000_000, "bar"),
            (3_500_000, "baz"),
            (4_000_000, "qux"),
            (7_500_000, "quux"),
        ]
        .map(|(time, output)| {
            Ok(Event::output(
                Duration::from_micros(time),
                output.to_owned(),
            ))
        });

        let events = output(super::limit_idle_time(events.into_iter(), 2.0));

        assert_eq!(events[0], (Duration::from_micros(0), "foo".to_owned()));
        assert_eq!(
            events[1],
            (Duration::from_micros(1_000_000), "bar".to_owned())
        );
        assert_eq!(
            events[2],
            (Duration::from_micros(3_000_000), "baz".to_owned())
        );
        assert_eq!(
            events[3],
            (Duration::from_micros(3_500_000), "qux".to_owned())
        );
        assert_eq!(
            events[4],
            (Duration::from_micros(5_500_000), "quux".to_owned())
        );
    }

    fn output(events: impl Iterator<Item = Result<Event>>) -> Vec<(Duration, String)> {
        events
            .filter_map(|r| {
                if let Ok(Event {
                    time,
                    data: EventData::Output(data),
                }) = r
                {
                    Some((time, data))
                } else {
                    None
                }
            })
            .collect::<Vec<_>>()
    }
}


================================================
FILE: src/cli.rs
================================================
use std::net::SocketAddr;
use std::num::ParseIntError;
use std::path::PathBuf;

use clap::{ArgGroup, Args, Parser, Subcommand, ValueEnum};

pub const DEFAULT_LISTEN_ADDR: &str = "127.0.0.1:0";

#[derive(Debug, Parser)]
#[clap(author, version, about)]
#[command(name = "asciinema", max_term_width = 100, infer_subcommands = true)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Commands,

    /// Suppress diagnostic messages and progress indicators. Only error messages will be displayed.
    #[clap(
        short,
        long,
        global = true,
        display_order = 101,
        help = "Quiet mode - suppress diagnostic messages",
        long_help
    )]
    pub quiet: bool,
}

#[derive(Debug, Subcommand)]
pub enum Commands {
    /// Record a terminal session to a file.
    ///
    /// Captures all terminal output and optionally keyboard input, saving it for later playback. Supports various output formats, idle time limiting, and session customization options.
    ///
    /// Press <ctrl+d> or type 'exit' to end the recording session.
    /// Press <ctrl+\> to pause/resume capture of the session.
    ///
    /// During the session, the ASCIINEMA_SESSION environment variable is set to a unique session ID.
    #[clap(
        visible_alias = "rec",
        about = "Record a terminal session",
        long_about,
        after_help = "\x1b[1;4mExamples\x1b[0m:

  asciinema rec demo.cast
      Records a shell session to a file

  asciinema rec --command \"python script.py\" demo.cast
      Records execution of a Python script

  asciinema rec --idle-time-limit 2 demo.cast
      Records with idle time capped at 2 seconds

  asciinema rec --capture-input --title \"API Demo\" demo.cast
      Records with keyboard input and sets a title

  asciinema rec --append demo.cast
      Continues recording to an existing file

  asciinema rec demo.txt
      Records as a plain-text log - output format inferred from the .txt extension"
    )]
    Record(Record),

    /// Stream a terminal session in real-time.
    ///
    /// Broadcasts a terminal session live via either the local HTTP server (for local/LAN viewing) or a remote asciinema server (for public sharing). Viewers can watch the session as it happens through a web interface.
    ///
    /// Press <ctrl+d> or type 'exit' to end the streaming session.
    /// Press <ctrl+\> to pause/resume capture of the session.
    ///
    /// During the session, the ASCIINEMA_SESSION environment variable is set to a unique session ID.
    #[clap(
        about = "Stream a terminal session",
        long_about,
        after_help = "\x1b[1;4mExamples\x1b[0m:

  asciinema stream --local
      Streams a shell session via the local HTTP server listening on an ephemeral port on 127.0.0.1

  asciinema stream --local 0.0.0.0:8080
      Streams via the local HTTP server listening on port 8080 on all network interfaces

  asciinema stream --remote
      Streams via an asciinema server for public viewing

  asciinema stream -l -r
      Streams both locally and remotely simultaneously

  asciinema stream -r --command \"ping asciinema.org\"
      Streams execution of the ping command

  asciinema stream -r <ID> -t \"Live coding\"
      Streams via a remote server, reusing the existing stream ID and setting the stream title"
    )]
    Stream(Stream),

    /// Record and stream a terminal session simultaneously.
    ///
    /// Combines the functionality of record and stream commands, allowing you to save a recording to a file while also broadcasting it live to viewers.
    ///
    /// Press <ctrl+d> or type 'exit' to end the session.
    /// Press <ctrl+\> to pause/resume capture of the session.
    ///
    /// During the session, the ASCIINEMA_SESSION environment variable is set to a unique session ID.
    #[clap(
        about = "Record and stream a terminal session",
        long_about,
        after_help = "\x1b[1;4mExamples\x1b[0m:

  asciinema session --output-file demo.cast --stream-local
      Records a shell session to a file and streams it via the local HTTP server listening on an ephemeral port on 127.0.0.1

  asciinema session -o demo.cast --stream-remote
      Records to a file and streams via an asciinema server for public viewing

  asciinema session --stream-local --stream-remote
      Streams both locally and remotely simultaneously, without saving to a file

  asciinema session -o demo.cast -l -r -t \"Live coding\"
      Records + streams locally + streams remotely, setting the title of the recording/stream

  asciinema session -o demo.cast --idle-time-limit 1.5
      Records to a file with idle time capped at 1.5 seconds

  asciinema session -o demo.cast -l 0.0.0.0:9000 -r <ID>
      Records + streams locally on port 9000 + streams remotely, reusing existing stream ID"
    )]
    Session(Session),

    /// Play back a recorded terminal session.
    ///
    /// Displays a previously recorded asciicast file in your terminal with various playback controls (see below). Supports local files and remote URLs.
    ///
    /// Press <ctrl+c> to interrupt the playback.
    /// Press <space> to pause/resume.
    /// Press '.' to step forward (while paused).
    /// Press ']' to skip to the next marker (while paused).
    #[clap(
        about = "Play back a terminal session",
        long_about,
        after_help = "\x1b[1;4mExamples\x1b[0m:

  asciinema play demo.cast
      Plays back a local recording file once

  asciinema play --speed 2.0 --loop demo.cast
      Plays back at double speed in a loop

  asciinema play --idle-time-limit 2 demo.cast
      Plays back with idle time capped at 2 seconds

  asciinema play https://asciinema.org/a/569727
      Plays back directly from a URL

  asciinema play --pause-on-markers demo.cast
      Plays back, pausing automatically at every marker"
    )]
    Play(Play),

    /// Upload a recording to an asciinema server.
    ///
    /// Takes a local asciicast file and uploads it to an asciinema server (either asciinema.org or a self-hosted server), returning a recording URL which can be shared publicly.
    #[clap(about = "Upload a recording to an asciinema server", long_about)]
    Upload(Upload),

    /// Authenticate with an asciinema server.
    ///
    /// Creates a user account link between your local CLI and an asciinema server account. Optional for uploading with the upload command, required for remote streaming with the stream and session commands.
    #[clap(
        about = "Authenticate this CLI with an asciinema server account",
        long_about
    )]
    Auth(Auth),

    /// Concatenate multiple recordings into one.
    ///
    /// Combines two or more asciicast files in sequence, adjusting timing so each recording plays immediately after the previous one ends. Useful for creating longer recordings from multiple shorter sessions.
    ///
    /// Note: in asciinema 2.x this command used to print raw terminal output for a given session
    /// file. If you're looking for this behavior then use `asciinema convert -f raw <FILE> -` instead.
    #[clap(
        about = "Concatenate multiple recordings",
        long_about,
        after_help = "\x1b[1;4mExamples\x1b[0m:

  asciinema cat demo1.cast demo2.cast demo3.cast > combined.cast
      Combines local recordings into one file

  asciinema cat https://asciinema.org/a/569727 part2.cast > combined.cast
      Combines a remote and a local recording into one file"
    )]
    Cat(Cat),

    /// Convert a recording to another format.
    ///
    /// Transform asciicast files between different formats (v1, v2, v3) or export to other formats like raw terminal output or plain text. Supports reading from files, URLs, or stdin and writing to files or stdout.
    #[clap(
        about = "Convert a recording to another format",
        long_about,
        after_help = "\x1b[1;4mExamples\x1b[0m:

  asciinema convert old.cast new.cast
      Converts a recording to the latest asciicast format (v3)

  asciinema convert demo.cast demo.txt
      Exports a recording as a plain-text log - output format inferred from the .txt extension

  asciinema convert --output-format raw demo.cast demo.txt
      Exports as raw terminal output

  asciinema convert -f txt demo.cast -
      Exports as plain text to stdout

  asciinema convert https://asciinema.org/a/569727 starwars.cast
      Downloads a remote recording and converts it to the latest asciicast format (v3)"
    )]
    Convert(Convert),
}

#[derive(Debug, Args)]
pub struct Record {
    /// Output file path
    pub file: String,

    /// Specify the format for the output file. The default is asciicast-v3. If the file path ends with .txt, the txt format will be selected automatically unless --output-format is explicitly specified.
    #[arg(
        short = 'f',
        long,
        value_enum,
        value_name = "FORMAT",
        help = "Output file format [default: asciicast-v3]",
        long_help
    )]
    pub output_format: Option<Format>,

    /// Specify the command to execute in the recording session. If not provided, asciinema will use your default shell from the $SHELL environment variable. This can be any command with arguments, for example: --command "python script.py" or --command "bash -l". Can also be set via the config file option session.command.
    #[arg(
        short,
        long,
        help = "Command to start in the session [default: $SHELL]",
        long_help
    )]
    pub command: Option<String>,

    /// Enable recording of keyboard input in addition to terminal output. When enabled, both what you type and what appears on the screen will be captured. Note that sensitive input like passwords will also be recorded when this option is enabled. Can also be set via the config file option session.capture_input.
    #[arg(
        long,
        short = 'I',
        alias = "stdin",
        help = "Enable input (keyboard) capture",
        long_help
    )]
    pub capture_input: bool,

    /// Specify which environment variables to capture and include in the recording metadata. This helps ensure the recording context is preserved, e.g., for auditing. Provide a comma-separated list of variable names, for example: --rec-env "USER,SHELL,TERM". If not specified, only the SHELL variable is captured by default. Can also be set via the config file option session.capture_env.
    #[arg(
        long,
        value_name = "VARS",
        help = "Comma-separated list of environment variables to capture [default: SHELL]",
        long_help
    )]
    pub capture_env: Option<String>,

    /// Append the new session to an existing recording file instead of creating a new one. This allows you to continue a previous recording session. The timing will be adjusted to maintain continuity from where the previous recording ended. Cannot be used together with --overwrite.
    #[arg(short, long, help = "Append to an existing recording file", long_help)]
    pub append: bool,

    /// Overwrite the output file if it already exists. By default, asciinema will refuse to overwrite existing files to prevent accidental data loss. Cannot be used together with --append.
    #[arg(
        long,
        conflicts_with = "append",
        help = "Overwrite the output file if it already exists",
        long_help
    )]
    pub overwrite: bool,

    /// Set a title that will be stored in the recording metadata. This title may be displayed by players and is useful for organizing and identifying recordings. For example: --title "Installing Podman on Ubuntu".
    #[arg(short, long, help = "Title of the recording", long_help)]
    pub title: Option<String>,

    /// Limit the maximum idle time recorded between terminal events to the specified number of seconds. Long pauses (such as when you step away from the terminal) will be capped at this duration in the recording, making playback more watchable. For example, --idle-time-limit 2.0 will ensure no pause longer than 2 seconds appears in the recording. Note that this option doesn't alter the original (captured) timing information and instead, embeds the idle time limit value in the metadata, which is interpreted by session players at playback time. This allows tweaking of the limit after recording. Can also be set via the config file option session.idle_time_limit.
    #[arg(
        short,
        long,
        value_name = "SECS",
        help = "Limit idle time to a given number of seconds",
        long_help
    )]
    pub idle_time_limit: Option<f64>,

    /// Record in headless mode without using the terminal for input/output. This is useful for automated or scripted recordings where you don't want asciinema to interfere with the current terminal session. The recorded command will still execute normally, but asciinema won't display its output in your terminal. Headless mode is enabled automatically when running in an environment where a terminal is not available.
    #[arg(
        long,
        help = "Headless mode - don't use the terminal for I/O",
        long_help
    )]
    pub headless: bool,

    /// Override the terminal window size used for the recording session. Specify dimensions as COLSxROWS (e.g., 80x24 for 80 columns by 24 rows). You can specify just columns (80x) or just rows (x24) to override only one dimension. This is useful for ensuring consistent recording dimensions regardless of your current terminal size.
    #[arg(long, value_name = "COLSxROWS", value_parser = parse_window_size, help = "Override session's terminal window size", long_help)]
    pub window_size: Option<(Option<u16>, Option<u16>)>,

    /// Make the asciinema command exit with the same status code as the recorded session. By default, asciinema exits with status 0 regardless of what happens in the recorded session. With this option, if the recorded command exits with a non-zero status, asciinema will also exit with the same status.
    #[arg(long, help = "Return the session's exit status", long_help)]
    pub return_: bool,

    /// Enable logging of internal events to a file at the specified path. Useful for debugging recording issues.
    #[arg(long, value_name = "PATH", help = "Log file path", long_help)]
    pub log_file: Option<PathBuf>,

    #[arg(long, hide = true)]
    pub cols: Option<u16>,

    #[arg(long, hide = true)]
    pub rows: Option<u16>,

    #[arg(long, hide = true)]
    pub raw: bool,
}

#[derive(Debug, Args)]
pub struct Play {
    /// The path to an asciicast file or HTTP(S) URL to play back. Can be a local file path, HTTP(S) URL for remote files, or '-' to read from standard input. Remote URLs allow playing recordings directly from the web without need for manual downloading. Supported formats include asciicast v1, v2, and v3.
    pub file: String,

    /// Control the playback speed as a multiplier of the original timing. Values greater than 1.0 make playback faster, while values less than 1.0 make it slower. For example, --speed 2.0 plays at double speed, while --speed 0.5 plays at half speed. The default is 1.0 (original speed). Can also be set via the config file option playback.speed.
    #[arg(short, long, help = "Set playback speed", long_help)]
    pub speed: Option<f64>,

    /// Enable continuous looping of the recording. When the recording reaches the end, it will automatically restart from the beginning. This continues indefinitely until you interrupt playback with <ctrl+c>.
    #[arg(
        short,
        long,
        name = "loop",
        help = "Loop playback continuously",
        long_help
    )]
    pub loop_: bool,

    /// Limit the maximum idle time between events during playback to the specified number of seconds. Long pauses in the original recording (such as when the user stepped away) will be shortened to this duration, making playback more watchable. This overrides any idle time limit set in the recording itself or in your config file (playback.idle_time_limit).
    #[arg(
        short,
        long,
        value_name = "SECS",
        help = "Limit idle time to a given number of seconds",
        long_help
    )]
    pub idle_time_limit: Option<f64>,

    /// Automatically pause playback when encountering marker events. Markers are special events that can be added during recording to mark important points in a session. When this option is enabled, playback will pause at each marker, allowing you to control the flow of the demonstration. Use <space> to resume, '.' to step through events, or ']' to skip to the next marker.
    #[arg(short = 'm', long, help = "Automatically pause on markers", long_help)]
    pub pause_on_markers: bool,

    /// Automatically resize the terminal window to match the original recording dimensions. This option attempts to change your terminal size to match the size used when the recording was made, ensuring the output appears exactly as it was originally recorded. Note that this feature is only supported by some terminals and may not work in all environments.
    #[arg(
        short = 'r',
        long,
        help = "Auto-resize terminal to match original size",
        long_help
    )]
    pub resize: bool,
}

#[derive(Debug, Args)]
#[clap(group(ArgGroup::new("mode").args(&["local", "remote"]).multiple(true).required(true)))]
pub struct Stream {
    /// Start the local HTTP server to stream the session in real-time. Creates a web interface accessible via browser where viewers can watch the terminal session live. Optionally specify the bind address as IP:PORT (e.g., 0.0.0.0:8080 to allow external connections). If no address is provided, it listens on an automatically assigned ephemeral port on 127.0.0.1.
    #[arg(short, long, value_name = "IP:PORT", default_missing_value = DEFAULT_LISTEN_ADDR, num_args = 0..=1, help = "Stream via the local HTTP server", long_help)]
    pub local: Option<SocketAddr>,

    /// Stream the session to a remote asciinema server for public viewing. This allows sharing your session on the web with anyone who has the stream URL. You can provide either a stream ID of an existing stream configuration in your asciinema server account, or a direct WebSocket URL (ws:// or wss://) for custom servers. Omitting the value for this option lets the asciinema server allocate a new stream ID automatically.
    #[arg(short, long, value_name = "STREAM-ID|WS-URL", default_missing_value = "", num_args = 0..=1, value_parser = validate_forward_target, help = "Stream via remote asciinema server", long_help)]
    pub remote: Option<RelayTarget>,

    /// Specify the command to execute in the streaming session. If not provided, asciinema will use your default shell from the $SHELL environment variable. This can be any command with arguments, for example: --command "python script.py" or --command "bash -l". Can also be set via the config file option session.command.
    #[arg(
        short,
        long,
        help = "Command to start in the session [default: $SHELL]",
        long_help
    )]
    pub command: Option<String>,

    /// Enable recording of keyboard input in addition to terminal output. When enabled, both what you type and what appears on the screen will be captured. Note that sensitive input like passwords will also be recorded when this option is enabled. If the server has stream recording enabled then keyboard input will be included in the recording file created on the server side. Can also be set via the config file option session.capture_input.
    #[arg(long, short = 'I', help = "Enable input (keyboard) capture", long_help)]
    pub capture_input: bool,

    /// Specify which environment variables to capture and include in the stream metadata. Provide a comma-separated list of variable names, for example: --rec-env "USER,SHELL,TERM". If not specified, only the SHELL variable is captured by default. If the server has stream recording enabled then these environment variables will be included in the recording file created on the server side. Can also be set via the config file option session.capture_env.
    #[arg(
        long,
        value_name = "VARS",
        help = "Comma-separated list of environment variables to capture [default: SHELL]",
        long_help
    )]
    pub capture_env: Option<String>,

    /// Set a descriptive title for the streaming session. This title is displayed to viewers (when doing remote streaming with --remote). For example: --title "Building a REST API". If the server has stream recording enabled then the title will be included in the recording file created on the server side.
    #[arg(short, long, help = "Title of the session", long_help)]
    pub title: Option<String>,

    /// Set a description for the session. This description is displayed on the stream page (applies only to remote streaming with --remote) and can include formatting, links, and code blocks. Useful for providing context, instructions, or documentation for viewers.
    #[arg(
        long,
        help = "Description of the session (Markdown supported)",
        long_help
    )]
    pub description: Option<String>,

    /// Set the visibility level for the stream (applies only to remote streaming with --remote). Public streams appear in listings and on your profile page. Unlisted streams are accessible via a direct URL but don't appear in listings. Private streams are only accessible to the owner.
    #[arg(long, value_enum, help = "Visibility level", long_help)]
    pub visibility: Option<Visibility>,

    /// Specify the URL of a live audio stream (e.g., Icecast MP3/OGG) to synchronize with the terminal stream (applies only to remote streaming with --remote). When set, viewers can listen to audio commentary while watching the terminal. The audio URL is stored in the stream metadata and used by the player for synchronized playback. For example: --audio-url https://icecast.example.com/live.mp3
    #[arg(
        long,
        value_name = "URL",
        help = "Audio stream URL for synchronized playback",
        long_help
    )]
    pub audio_url: Option<String>,

    /// Stream in headless mode without using the terminal for input/output. This is useful for automated or scripted streaming where you don't want asciinema to interfere with the current terminal session. The streamed command will still execute normally and be visible to viewers, but won't be displayed in your local terminal. Headless mode is enabled automatically when running in an environment where a terminal is not available.
    #[arg(
        long,
        help = "Headless mode - don't use the terminal for I/O",
        long_help
    )]
    pub headless: bool,

    /// Override the terminal window size used for the streaming session. Specify dimensions as COLSxROWS (e.g., 80x24 for 80 columns by 24 rows). You can specify just columns (80x) or just rows (x24) to override only one dimension. This is useful for ensuring consistent streaming dimensions regardless of your current terminal size.
    #[arg(long, value_name = "COLSxROWS", value_parser = parse_window_size, help = "Override session's terminal window size", long_help)]
    pub window_size: Option<(Option<u16>, Option<u16>)>,

    /// Make the asciinema command exit with the same status code as the streamed session. By default, asciinema exits with status 0 regardless of what happens in the streamed session. With this option, if the streamed command exits with a non-zero status, asciinema will also exit with that same status.
    #[arg(long, help = "Return the session's exit status", long_help)]
    pub return_: bool,

    /// Enable logging of internal events to a file at the specified path. Useful for debugging streaming issues (connection errors, disconnections, etc.).
    #[arg(long, value_name = "PATH", help = "Log file path", long_help)]
    pub log_file: Option<PathBuf>,

    /// Specify a custom asciinema server URL for streaming to self-hosted servers. Use the base server URL (e.g., https://asciinema.example.com). Can also be set via the environment variable ASCIINEMA_SERVER_URL or the config file option server.url. If no server URL is configured via this option, environment variable, or config file, you will be prompted to choose one (defaulting to asciinema.org), which will be saved as a default.
    #[arg(long, value_name = "URL", help = "asciinema server URL", long_help)]
    pub server_url: Option<String>,
}

/// Visibility level for uploads and streams
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub enum Visibility {
    Public,
    Unlisted,
    Private,
}

#[derive(Debug, Args)]
#[clap(group(ArgGroup::new("mode").args(&["output_file", "stream_local", "stream_remote"]).multiple(true).required(true)))]
pub struct Session {
    /// Save the session to a file at the specified path. Can be combined with local and remote streaming.
    #[arg(
        short,
        long,
        value_name = "PATH",
        help = "Save the session to a file",
        long_help
    )]
    pub output_file: Option<String>,

    /// Specify the format for the output file when saving is enabled with --output-file. The default is asciicast-v3. If the output file path ends with .txt, the txt format will be selected automatically unless this option is explicitly specified.
    #[arg(
        short = 'f',
        long,
        value_enum,
        value_name = "FORMAT",
        help = "Output file format [default: asciicast-v3]",
        long_help
    )]
    pub output_format: Option<Format>,

    /// Start the local HTTP server to stream the session in real-time. Creates a web interface accessible via browser where viewers can watch the terminal session live. Optionally specify the bind address as IP:PORT (e.g., 0.0.0.0:8080 to allow external connections). If no address is provided, it listends on an automatically assigned ephemeral port on 127.0.0.1. Can be combined with remote streaming and file output.
    #[arg(short = 'l', long, value_name = "IP:PORT", default_missing_value = DEFAULT_LISTEN_ADDR, num_args = 0..=1, help = "Stream via the local HTTP server", long_help)]
    pub stream_local: Option<SocketAddr>,

    /// Stream the session to a remote asciinema server for public viewing. This allows sharing your session on the web with anyone who has the stream URL. You can provide either a stream ID of an existing stream configuration in your asciinema server account, or a direct WebSocket URL (ws:// or wss://) for custom servers. Omitting the value for this option lets the asciinema server allocate a new stream ID automatically. Can be combined with local streaming and file output.
    #[arg(short = 'r', long, value_name = "STREAM-ID|WS-URL", default_missing_value = "", num_args = 0..=1, value_parser = validate_forward_target, help = "Stream via remote asciinema server", long_help)]
    pub stream_remote: Option<RelayTarget>,

    /// Specify the command to execute in the session. If not provided, asciinema will use your default shell from the $SHELL environment variable. This can be any command with arguments, for example: --command "python script.py" or --command "bash -l". Can also be set via the config file option session.command.
    #[arg(
        short,
        long,
        help = "Command to start in the session [default: $SHELL]",
        long_help
    )]
    pub command: Option<String>,

    /// Enable recording of keyboard input in addition to terminal output. When enabled, both what you type and what appears on the screen will be captured. Note that sensitive input like passwords will also be recorded when this option is enabled. If the server has stream recording enabled then keyboard input will be included in the recording file created on the server side. Can also be set via the config file option session.capture_input.
    #[arg(long, short = 'I', help = "Enable input (keyboard) capture", long_help)]
    pub capture_input: bool,

    /// Specify which environment variables to capture and include in the session metadata. Provide a comma-separated list of variable names, for example: --rec-env "USER,SHELL,TERM". If not specified, only the SHELL variable is captured by default. If the server has stream recording enabled then these environment variables will be included in the recording file created on the server side. Can also be set via the config file option session.capture_env.
    #[arg(
        long,
        value_name = "VARS",
        help = "Comma-separated list of environment variables to capture [default: SHELL]",
        long_help
    )]
    pub capture_env: Option<String>,

    /// Append the new session to an existing recording file instead of creating a new one. This allows you to continue a previous recording session. The timing will be adjusted to maintain continuity from where the previous recording ended. Cannot be used together with --overwrite. Only applies when --output-file is specified.
    #[arg(short, long, help = "Append to an existing recording file", long_help)]
    pub append: bool,

    /// Overwrite the output file if it already exists. By default, asciinema will refuse to overwrite existing files to prevent accidental data loss. Cannot be used together with --append. Only applies when --output-file is specified.
    #[arg(
        long,
        conflicts_with = "append",
        help = "Overwrite the output file if it already exists",
        long_help
    )]
    pub overwrite: bool,

    /// Set a title for the session that will be stored in the recording metadata and displayed to stream viewers (when doing remote streaming with --remote). For example: --title "Installing Podman on Ubuntu". If the server has stream recording enabled then the title will be included in the recording file created on the server side.
    #[arg(short, long, help = "Title of the session", long_help)]
    pub title: Option<String>,

    /// Set a description for the session. This description is displayed on the stream page (applies only to remote streaming with --stream-remote) and can include formatting, links, and code blocks. Useful for providing context, instructions, or documentation for viewers.
    #[arg(
        long,
        help = "Description of the session (Markdown supported)",
        long_help
    )]
    pub description: Option<String>,

    /// Set the visibility level for the stream (applies only to remote streaming with --stream-remote). Public streams appear in listings and on your profile page. Unlisted streams are accessible via a direct URL but don't appear in listings. Private streams are only accessible to the owner.
    #[arg(long, value_enum, help = "Stream visibility level", long_help)]
    pub visibility: Option<Visibility>,

    /// Specify the URL of a live audio stream (e.g., Icecast MP3/OGG) to synchronize with the terminal stream (applies only to remote streaming with --stream-remote). When set, viewers can listen to audio commentary while watching the terminal. The audio URL is stored in the stream metadata and used by the player for synchronized playback. For example: --audio-url https://icecast.example.com/live.mp3
    #[arg(
        long,
        value_name = "URL",
        help = "Audio stream URL for synchronized playback",
        long_help
    )]
    pub audio_url: Option<String>,

    /// Limit the maximum idle time recorded between terminal events to the specified number of seconds. Long pauses (such as when you step away from the terminal) will be capped at this duration in the recording, making playback more watchable. For example, --idle-time-limit 2.0 will ensure no pause longer than 2 seconds appears in the recording. Only applies when --output-file is specified. Note that this option doesn't alter the original (captured) timing information and instead, it embeds the idle time limit value in the metadata, which is interpreted by session players at playback time. This allows tweaking of the limit after recording. Can also be set via the config file option session.idle_time_limit.
    #[arg(
        short,
        long,
        value_name = "SECS",
        help = "Limit idle time to a given number of seconds",
        long_help
    )]
    pub idle_time_limit: Option<f64>,

    /// Run the session in headless mode without using the terminal for input/output. This is useful for automated or scripted sessions where you don't want asciinema to interfere with the current terminal session. The session command will still execute normally and be recorded/streamed, but won't be displayed in your local terminal. Headless mode is enabled automatically when running in an environment where a terminal is not available.
    #[arg(
        long,
        help = "Headless mode - don't use the terminal for I/O",
        long_help
    )]
    pub headless: bool,

    /// Override the terminal window size used for the session. Specify dimensions as COLSxROWS (e.g., 80x24 for 80 columns by 24 rows). You can specify just columns (80x) or just rows (x24) to override only one dimension. This is useful for ensuring consistent recording dimensions regardless of your current terminal size.
    #[arg(long, value_name = "COLSxROWS", value_parser = parse_window_size, help = "Override session's terminal window size", long_help)]
    pub window_size: Option<(Option<u16>, Option<u16>)>,

    /// Make the asciinema command exit with the same status code as the session command. By default, asciinema exits with status 0 regardless of what happens in the session. With this option, if the session command exits with a non-zero status, asciinema will also exit with that same status.
    #[arg(long, help = "Return the session's exit status", long_help)]
    pub return_: bool,

    /// Enable logging of internal events to a file at the specified path. Useful for debugging I/O issues (connection errors, disconnections, file write errors, etc.).
    #[arg(long, value_name = "PATH", help = "Log file path", long_help)]
    pub log_file: Option<PathBuf>,

    /// Specify a custom asciinema server URL for streaming to self-hosted servers. Use the base server URL (e.g., https://asciinema.example.com). Can also be set via environment variable ASCIINEMA_SERVER_URL or config file option server.url. If no server URL is configured via this option, environment variable, or config file, you will be prompted to choose one (defaulting to asciinema.org), which will be saved as a default.
    #[arg(long, value_name = "URL", help = "asciinema server URL", long_help)]
    pub server_url: Option<String>,

    #[arg(hide = true)]
    pub env: Vec<String>,
}

#[derive(Debug, Args)]
pub struct Cat {
    /// List of recording files to concatenate. Provide at least two file paths (local files or HTTP(S) URLs). The files will be combined in the order specified. All files must be in asciicast format.
    #[arg(required = true, num_args = 2.., help = "Recording files to concatenate", long_help)]
    pub file: Vec<String>,
}

#[derive(Debug, Args)]
pub struct Convert {
    /// The source recording to convert. Can be a local file path, HTTP(S) URL for remote files, or '-' to read from standard input. Remote URLs allow converting recordings directly from the web without need for manual downloading. Supported input formats include asciicast v1, v2 and v3.
    pub input: String,

    /// The output path for the convert
Download .txt
gitextract_57n0_umc/

├── .cargo/
│   └── config.toml
├── .gitattributes
├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug-report.yml
│   │   └── config.yml
│   └── workflows/
│       ├── ci.yml
│       └── release.yml
├── .gitignore
├── CHANGELOG.md
├── CONTRIBUTING.md
├── Cargo.toml
├── Dockerfile
├── LICENSE
├── README.md
├── assets/
│   ├── asciinema-player.css
│   └── index.html
├── build.rs
├── default.nix
├── flake.nix
├── shell.nix
├── src/
│   ├── alis.rs
│   ├── api.rs
│   ├── asciicast/
│   │   ├── util.rs
│   │   ├── v1.rs
│   │   ├── v2.rs
│   │   └── v3.rs
│   ├── asciicast.rs
│   ├── cli.rs
│   ├── cmd/
│   │   ├── auth.rs
│   │   ├── cat.rs
│   │   ├── convert.rs
│   │   ├── mod.rs
│   │   ├── play.rs
│   │   ├── session.rs
│   │   └── upload.rs
│   ├── config.rs
│   ├── encoder/
│   │   ├── asciicast.rs
│   │   ├── mod.rs
│   │   ├── raw.rs
│   │   └── txt.rs
│   ├── fd.rs
│   ├── file_writer.rs
│   ├── forwarder.rs
│   ├── hash.rs
│   ├── html.rs
│   ├── leb128.rs
│   ├── locale.rs
│   ├── main.rs
│   ├── notifier.rs
│   ├── player.rs
│   ├── pty.rs
│   ├── server.rs
│   ├── session.rs
│   ├── status.rs
│   ├── stream.rs
│   ├── tty/
│   │   ├── default.rs
│   │   ├── inspect.rs
│   │   └── macos.rs
│   ├── tty.rs
│   └── util.rs
└── tests/
    ├── casts/
    │   ├── demo.cast
    │   ├── demo.json
    │   ├── full-v1.json
    │   ├── full-v2.cast
    │   ├── full-v3.cast
    │   ├── minimal-v1.json
    │   ├── minimal-v2.cast
    │   ├── minimal-v3.cast
    │   ├── nulls-v1.json
    │   └── nulls-v2.cast
    └── integration.sh
Download .txt
SYMBOL INDEX (507 symbols across 40 files)

FILE: build.rs
  constant ENV_KEY (line 12) | const ENV_KEY: &str = "ASCIINEMA_GEN_DIR";
  function main (line 14) | fn main() -> std::io::Result<()> {

FILE: src/alis.rs
  type EventSerializer (line 19) | struct EventSerializer(Duration);
    method serialize_event (line 32) | fn serialize_event(&mut self, event: Event) -> Vec<u8> {
    method rel_time (line 166) | fn rel_time(&mut self, time: Duration) -> u64 {
  function stream (line 21) | pub fn stream<S: Stream<Item = Result<Event, BroadcastStreamRecvError>>>(
  function test_serialize_init_with_theme_and_seed (line 183) | fn test_serialize_init_with_theme_and_seed() {
  function test_serialize_init_without_theme_nor_seed (line 258) | fn test_serialize_init_without_theme_nor_seed() {
  function test_serialize_output (line 286) | fn test_serialize_output() {
  function test_serialize_input (line 309) | fn test_serialize_input() {
  function test_serialize_resize (line 327) | fn test_serialize_resize() {
  function test_serialize_marker_with_label (line 345) | fn test_serialize_marker_with_label() {
  function test_serialize_marker_without_label (line 368) | fn test_serialize_marker_without_label() {
  function test_serialize_exit_positive_status (line 384) | fn test_serialize_exit_positive_status() {
  function test_serialize_exit_negative_status (line 401) | fn test_serialize_exit_negative_status() {
  function test_serialize_eot (line 418) | fn test_serialize_eot() {
  function test_subsequent_event_lower_time (line 434) | fn test_subsequent_event_lower_time() {
  function rgb (line 453) | fn rgb(r: u8, g: u8, b: u8) -> RGB8 {

FILE: src/api.rs
  type RecordingResponse (line 15) | pub struct RecordingResponse {
  type StreamResponse (line 21) | pub struct StreamResponse {
  type Visibility (line 29) | pub enum Visibility {
  type RecordingChangeset (line 36) | pub struct RecordingChangeset {
  type StreamChangeset (line 48) | pub struct StreamChangeset {
  type ErrorResponse (line 70) | struct ErrorResponse {
  function get_auth_url (line 74) | pub fn get_auth_url(config: &mut Config) -> Result<Url> {
  function create_recording (line 81) | pub async fn create_recording(
  function create_recording_request (line 111) | async fn create_recording_request(
  function add_recording_changeset_fields (line 127) | fn add_recording_changeset_fields(mut form: Form, changeset: RecordingCh...
  function list_user_streams (line 153) | pub async fn list_user_streams(prefix: &str, config: &mut Config) -> Res...
  function list_user_streams_request (line 165) | fn list_user_streams_request(server_url: &Url, prefix: &str, install_id:...
  function create_stream (line 174) | pub async fn create_stream(
  function create_stream_request (line 189) | fn create_stream_request(
  function update_stream (line 203) | pub async fn update_stream(
  function update_stream_request (line 219) | fn update_stream_request(
  function parse_stream_response (line 234) | async fn parse_stream_response<T: DeserializeOwned>(
  function add_headers (line 263) | fn add_headers(builder: RequestBuilder, install_id: &str) -> RequestBuil...
  function get_username (line 270) | fn get_username() -> String {
  function build_user_agent (line 274) | pub fn build_user_agent() -> String {

FILE: src/asciicast.rs
  type Asciicast (line 19) | pub struct Asciicast<'a> {
  type Version (line 26) | pub enum Version {
    method eq (line 65) | fn eq(&self, other: &u8) -> bool {
  type Header (line 32) | pub struct Header {
  type Event (line 45) | pub struct Event {
    method output (line 155) | pub fn output(time: Duration, text: String) -> Self {
    method input (line 162) | pub fn input(time: Duration, text: String) -> Self {
    method resize (line 169) | pub fn resize(time: Duration, size: (u16, u16)) -> Self {
    method marker (line 176) | pub fn marker(time: Duration, label: String) -> Self {
    method exit (line 183) | pub fn exit(time: Duration, status: i32) -> Self {
  type EventData (line 50) | pub enum EventData {
  type Encoder (line 59) | pub trait Encoder {
    method header (line 60) | fn header(&mut self, header: &Header) -> Vec<u8>;
    method event (line 61) | fn event(&mut self, event: &Event) -> Vec<u8>;
    method header (line 101) | fn header(&mut self, header: &Header) -> Vec<u8> {
    method event (line 105) | fn event(&mut self, event: &Event) -> Vec<u8> {
    method header (line 111) | fn header(&mut self, header: &Header) -> Vec<u8> {
    method event (line 115) | fn event(&mut self, event: &Event) -> Vec<u8> {
  method fmt (line 74) | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  method default (line 84) | fn default() -> Self {
  function open_from_path (line 120) | pub fn open_from_path<S: AsRef<Path>>(path: S) -> Result<Asciicast<'stat...
  function open (line 128) | pub fn open<'a, R: BufRead + Send + 'a>(reader: R) -> Result<Asciicast<'...
  function get_duration (line 145) | pub fn get_duration<S: AsRef<Path>>(path: S) -> Result<Duration> {
  function limit_idle_time (line 191) | pub fn limit_idle_time(
  function accelerate (line 215) | pub fn accelerate(
  function encoder (line 228) | pub fn encoder(version: Version) -> Option<Box<dyn Encoder>> {
  function open_v1_minimal (line 248) | fn open_v1_minimal() {
  function open_v1_full (line 266) | fn open_v1_full() {
  function open_v1_with_nulls_in_header (line 293) | fn open_v1_with_nulls_in_header() {
  function open_v2_minimal (line 305) | fn open_v2_minimal() {
  function open_v2_full (line 323) | fn open_v2_full() {
  function open_v2_with_nulls_in_header (line 364) | fn open_v2_with_nulls_in_header() {
  function open_v3_minimal (line 376) | fn open_v3_minimal() {
  function open_v3_full (line 394) | fn open_v3_full() {
  function encoder (line 430) | fn encoder() {
  function header_encoding (line 479) | fn header_encoding() {
  function parse (line 536) | fn parse(json: Vec<u8>) -> Vec<serde_json::Value> {
  function accelerate (line 547) | fn accelerate() {
  function limit_idle_time (line 563) | fn limit_idle_time() {
  function output (line 599) | fn output(events: impl Iterator<Item = Result<Event>>) -> Vec<(Duration,...

FILE: src/asciicast/util.rs
  function deserialize_time (line 6) | pub fn deserialize_time<'de, D>(deserializer: D) -> Result<Duration, D::...

FILE: src/asciicast/v1.rs
  type V1 (line 11) | struct V1 {
  type V1OutputEvent (line 22) | struct V1OutputEvent {
  function load (line 28) | pub fn load(json: String) -> Result<Asciicast<'static>> {

FILE: src/asciicast/v2.rs
  type V2Header (line 13) | struct V2Header {
    method serialize (line 249) | fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    method from (line 385) | fn from(header: &Header) -> Self {
  type V2Theme (line 26) | struct V2Theme {
    method from (line 406) | fn from(tty_theme: &TtyTheme) -> Self {
  type RGB8 (line 36) | struct RGB8(rgb::RGB8);
    method serialize (line 354) | fn serialize<S>(&self, serializer: S) -> std::prelude::v1::Result<S::O...
    method fmt (line 363) | fn fmt(&self, f: &mut std::fmt::Formatter) -> fmt::Result {
  type V2Palette (line 39) | struct V2Palette(Vec<RGB8>);
    method serialize (line 369) | fn serialize<S>(&self, serializer: S) -> std::prelude::v1::Result<S::O...
  type V2Event (line 42) | struct V2Event {
  type V2EventCode (line 51) | enum V2EventCode {
  type Parser (line 59) | pub struct Parser(V2Header);
    method parse (line 72) | pub fn parse<'a, I: Iterator<Item = io::Result<String>> + Send + 'a>(
  function open (line 61) | pub fn open(header_line: &str) -> Result<Parser> {
  function parse_line (line 115) | fn parse_line(line: io::Result<String>) -> Option<Result<Event>> {
  function parse_event (line 129) | fn parse_event(line: String) -> Result<Event> {
  function deserialize_code (line 164) | fn deserialize_code<'de, D>(deserializer: D) -> Result<V2EventCode, D::E...
  type V2Encoder (line 183) | pub struct V2Encoder {
    method new (line 188) | pub fn new(time_offset: Duration) -> Self {
    method header (line 192) | pub fn header(&mut self, header: &Header) -> Vec<u8> {
    method event (line 200) | pub fn event(&mut self, event: &Event) -> Vec<u8> {
    method serialize_event (line 207) | fn serialize_event(&self, event: &Event) -> String {
    method to_json_string (line 227) | fn to_json_string(&self, s: &str) -> String {
  function format_time (line 232) | fn format_time(time: Duration) -> String {
  function deserialize_color (line 316) | fn deserialize_color<'de, D>(deserializer: D) -> Result<RGB8, D::Error>
  function parse_hex_color (line 324) | fn parse_hex_color(rgb: &str) -> Option<RGB8> {
  function deserialize_palette (line 336) | fn deserialize_palette<'de, D>(deserializer: D) -> Result<V2Palette, D::...
  method from (line 418) | fn from(tty_theme: &V2Theme) -> Self {
  function format_time (line 434) | fn format_time() {

FILE: src/asciicast/v3.rs
  type V3Header (line 14) | struct V3Header {
    method serialize (line 253) | fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    method from (line 420) | fn from(header: &Header) -> Self {
  type V3Term (line 25) | struct V3Term {
    method serialize (line 311) | fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  type V3Theme (line 35) | struct V3Theme {
    method from (line 440) | fn from(tty_theme: &TtyTheme) -> Self {
  type RGB8 (line 45) | struct RGB8(rgb::RGB8);
    method serialize (line 389) | fn serialize<S>(&self, serializer: S) -> std::prelude::v1::Result<S::O...
    method fmt (line 398) | fn fmt(&self, f: &mut std::fmt::Formatter) -> fmt::Result {
  type V3Palette (line 48) | struct V3Palette(Vec<RGB8>);
    method serialize (line 404) | fn serialize<S>(&self, serializer: S) -> std::prelude::v1::Result<S::O...
  type V3Event (line 51) | struct V3Event {
  type V3EventCode (line 60) | enum V3EventCode {
  type Parser (line 69) | pub struct Parser {
    method parse (line 88) | pub fn parse<'a, I: Iterator<Item = io::Result<String>> + Send + 'a>(
    method parse_line (line 116) | fn parse_line(&mut self, line: io::Result<String>) -> Option<Result<Ev...
    method parse_event (line 130) | fn parse_event(&mut self, line: String) -> Result<Event> {
  function open (line 74) | pub fn open(header_line: &str) -> Result<Parser> {
  function deserialize_code (line 167) | fn deserialize_code<'de, D>(deserializer: D) -> Result<V3EventCode, D::E...
  type V3Encoder (line 187) | pub struct V3Encoder {
    method new (line 193) | pub fn new() -> Self {
    method header (line 200) | pub fn header(&mut self, header: &Header) -> Vec<u8> {
    method event (line 208) | pub fn event(&mut self, event: &Event) -> Vec<u8> {
    method serialize_event (line 215) | fn serialize_event(&mut self, event: &Event) -> String {
    method to_json_string (line 239) | fn to_json_string(&self, s: &str) -> String {
  function format_duration (line 244) | fn format_duration(duration: Duration) -> String {
  function deserialize_color (line 351) | fn deserialize_color<'de, D>(deserializer: D) -> Result<RGB8, D::Error>
  function parse_hex_color (line 359) | fn parse_hex_color(rgb: &str) -> Option<RGB8> {
  function deserialize_palette (line 371) | fn deserialize_palette<'de, D>(deserializer: D) -> Result<V3Palette, D::...
  method from (line 452) | fn from(tty_theme: &V3Theme) -> Self {
  function format_time (line 469) | fn format_time() {

FILE: src/cli.rs
  constant DEFAULT_LISTEN_ADDR (line 7) | pub const DEFAULT_LISTEN_ADDR: &str = "127.0.0.1:0";
  type Cli (line 12) | pub struct Cli {
  type Commands (line 29) | pub enum Commands {
  type Record (line 221) | pub struct Record {
  type Play (line 322) | pub struct Play {
  type Stream (line 366) | pub struct Stream {
  type Visibility (line 449) | pub enum Visibility {
  type Session (line 457) | pub struct Session {
  type Cat (line 586) | pub struct Cat {
  type Convert (line 593) | pub struct Convert {
  type Upload (line 621) | pub struct Upload {
  type Auth (line 656) | pub struct Auth {
  type Format (line 663) | pub enum Format {
  type RelayTarget (line 676) | pub enum RelayTarget {
  function parse_window_size (line 681) | fn parse_window_size(s: &str) -> Result<(Option<u16>, Option<u16>), Stri...
  function validate_forward_target (line 706) | fn validate_forward_target(s: &str) -> Result<RelayTarget, String> {

FILE: src/cmd/auth.rs
  function run (line 8) | pub fn run(self) -> Result<()> {

FILE: src/cmd/cat.rs
  function run (line 12) | pub fn run(self) -> Result<()> {
  function open_input_files (line 53) | fn open_input_files(&self) -> Result<Vec<Asciicast<'_>>> {
  function get_encoder (line 63) | fn get_encoder(&self, version: Version) -> Result<Box<dyn Encoder>> {

FILE: src/cmd/convert.rs
  function run (line 15) | pub fn run(self) -> Result<()> {
  function get_encoder (line 25) | fn get_encoder(&self) -> Box<dyn encoder::Encoder> {
  function get_input_path (line 44) | fn get_input_path(&self) -> Result<Box<dyn AsRef<Path>>> {
  function get_output_path (line 52) | fn get_output_path(&self) -> String {
  function open_output_file (line 60) | fn open_output_file(&self, path: String) -> Result<fs::File> {
  function get_mode (line 73) | fn get_mode(&self, path: &str) -> Result<bool> {

FILE: src/cmd/play.rs
  function run (line 13) | pub fn run(self) -> anyhow::Result<()> {
  function get_path (line 49) | fn get_path(&self) -> anyhow::Result<Box<dyn AsRef<Path>>> {
  function get_key_bindings (line 58) | fn get_key_bindings(config: &config::Playback) -> anyhow::Result<KeyBind...

FILE: src/cmd/session.rs
  function run (line 34) | pub fn run(mut self) -> Result<ExitCode> {
  function do_run (line 49) | async fn do_run(&mut self) -> Result<i32> {
  function get_command (line 164) | fn get_command(&self, config: &config::Session) -> Option<String> {
  function get_session_metadata (line 168) | fn get_session_metadata(&self, config: &config::Session, term: TermInfo)...
  function get_file_writer (line 179) | async fn get_file_writer<N: Notifier + 'static>(
  function get_file_mode (line 204) | fn get_file_mode(&self, path: &Path) -> Result<(bool, bool)> {
  function get_file_format (line 226) | fn get_file_format(&self, path: &Path, append: bool) -> Result<Format> {
  function get_encoder (line 246) | fn get_encoder(
  function open_output_file (line 270) | async fn open_output_file(
  function get_listener (line 291) | async fn get_listener(&self) -> Result<Option<TcpListener>> {
  function get_relay (line 302) | async fn get_relay(
  function start_stream (line 330) | async fn start_stream(
  function init_logging (line 383) | fn init_logging(&self) -> Result<()> {
  function open_log_file (line 403) | fn open_log_file(&self, path: &PathBuf) -> Result<std::fs::File> {
  type TtyKind (line 413) | enum TtyKind {
  type TtySelection (line 418) | struct TtySelection {
    method open_raw (line 493) | async fn open_raw(&self) -> Result<Box<dyn RawTty>> {
  function probe_tty (line 424) | async fn probe_tty(
  type Relay (line 506) | struct Relay {
    method id (line 512) | fn id(&self) -> String {
  function get_key_bindings (line 517) | fn get_key_bindings(config: &config::Session) -> Result<KeyBindings> {
  function capture_env (line 535) | fn capture_env(var_names: Option<String>, config: &config::Session) -> H...
  function get_notifier (line 547) | fn get_notifier(config: &Config) -> BackgroundNotifier {
  function build_exec_command (line 557) | fn build_exec_command(command: Option<String>) -> Vec<String> {
  function build_exec_extra_env (line 565) | fn build_exec_extra_env(vars: &[String], relay_id: Option<&String>) -> H...
  function get_parent_session_relay_id (line 584) | fn get_parent_session_relay_id() -> Option<String> {

FILE: src/cmd/upload.rs
  function run (line 10) | pub fn run(self) -> Result<()> {
  function do_run (line 14) | async fn do_run(self) -> Result<()> {

FILE: src/config.rs
  constant DEFAULT_SERVER_URL (line 14) | const DEFAULT_SERVER_URL: &str = "https://asciinema.org";
  constant INSTALL_ID_FILENAME (line 15) | const INSTALL_ID_FILENAME: &str = "install-id";
  type Key (line 17) | pub type Key = Option<Vec<u8>>;
  type Config (line 21) | pub struct Config {
    method new (line 64) | pub fn new(server_url: Option<String>) -> Result<Self> {
    method get_server_url (line 90) | pub fn get_server_url(&mut self) -> Result<Url> {
    method get_install_id (line 104) | pub fn get_install_id(&self) -> Result<String> {
  type Server (line 30) | pub struct Server {
  type Session (line 36) | pub struct Session {
    method prefix_key (line 122) | pub fn prefix_key(&self) -> Result<Option<Key>> {
    method pause_key (line 126) | pub fn pause_key(&self) -> Result<Option<Key>> {
    method add_marker_key (line 130) | pub fn add_marker_key(&self) -> Result<Option<Key>> {
  type Playback (line 48) | pub struct Playback {
    method pause_key (line 136) | pub fn pause_key(&self) -> Result<Option<Key>> {
    method step_key (line 140) | pub fn step_key(&self) -> Result<Option<Key>> {
    method next_marker_key (line 144) | pub fn next_marker_key(&self) -> Result<Option<Key>> {
  type Notifications (line 58) | pub struct Notifications {
  function ask_for_server_url (line 149) | fn ask_for_server_url() -> Result<String> {
  function save_default_server_url (line 162) | fn save_default_server_url(url: &str) -> Result<()> {
  function parse_server_url (line 174) | fn parse_server_url(s: &str) -> Result<Url> {
  function read_install_id (line 184) | fn read_install_id(path: &PathBuf) -> Result<Option<String>> {
  function generate_install_id (line 198) | fn generate_install_id() -> String {
  function save_install_id (line 202) | fn save_install_id(path: &PathBuf, id: &str) -> Result<()> {
  function user_config_path (line 212) | pub fn user_config_path() -> Result<PathBuf> {
  function legacy_user_config_path (line 216) | fn legacy_user_config_path() -> Result<PathBuf> {
  function user_defaults_path (line 220) | fn user_defaults_path() -> Result<PathBuf> {
  function install_id_path (line 224) | fn install_id_path() -> Result<PathBuf> {
  function legacy_install_id_path (line 228) | fn legacy_install_id_path() -> Result<PathBuf> {
  function config_home (line 232) | fn config_home() -> Result<PathBuf> {
  function state_home (line 240) | fn state_home() -> Result<PathBuf> {
  function parse_key (line 253) | fn parse_key<S: AsRef<str>>(key: S) -> Result<Key> {
  function parse_control_key (line 289) | fn parse_control_key(c: char) -> Option<u8> {
  function check_legacy_config_file (line 305) | pub fn check_legacy_config_file() {
  function parse_key_accepts_ctrl_letters (line 334) | fn parse_key_accepts_ctrl_letters() {
  function parse_key_accepts_ctrl_punctuation (line 341) | fn parse_key_accepts_ctrl_punctuation() {
  function parse_key_rejects_invalid_ctrl_combos (line 349) | fn parse_key_rejects_invalid_ctrl_combos() {

FILE: src/encoder/asciicast.rs
  type AsciicastV2Encoder (line 5) | pub struct AsciicastV2Encoder {
    method new (line 11) | pub fn new(append: bool, time_offset: Duration) -> Self {
    method header (line 19) | fn header(&mut self, header: &Header) -> Vec<u8> {
    method event (line 29) | fn event(&mut self, event: Event) -> Vec<u8> {
    method flush (line 33) | fn flush(&mut self) -> Vec<u8> {
  type AsciicastV3Encoder (line 38) | pub struct AsciicastV3Encoder {
    method new (line 44) | pub fn new(append: bool) -> Self {
    method header (line 52) | fn header(&mut self, header: &Header) -> Vec<u8> {
    method event (line 62) | fn event(&mut self, event: Event) -> Vec<u8> {
    method flush (line 66) | fn flush(&mut self) -> Vec<u8> {

FILE: src/encoder/mod.rs
  type Encoder (line 15) | pub trait Encoder {
    method header (line 16) | fn header(&mut self, header: &Header) -> Vec<u8>;
    method event (line 17) | fn event(&mut self, event: Event) -> Vec<u8>;
    method flush (line 18) | fn flush(&mut self) -> Vec<u8>;
  type EncoderExt (line 21) | pub trait EncoderExt {
    method encode_to_file (line 22) | fn encode_to_file(&mut self, cast: crate::asciicast::Asciicast, file: ...
    method encode_to_file (line 26) | fn encode_to_file(&mut self, cast: crate::asciicast::Asciicast, file: ...

FILE: src/encoder/raw.rs
  type RawEncoder (line 3) | pub struct RawEncoder;
    method new (line 6) | pub fn new() -> Self {
    method header (line 12) | fn header(&mut self, header: &Header) -> Vec<u8> {
    method event (line 16) | fn event(&mut self, event: Event) -> Vec<u8> {
    method flush (line 24) | fn flush(&mut self) -> Vec<u8> {
  function encoder (line 38) | fn encoder() {

FILE: src/encoder/txt.rs
  type TextEncoder (line 5) | pub struct TextEncoder {
    method new (line 10) | pub fn new() -> Self {
    method header (line 16) | fn header(&mut self, header: &Header) -> Vec<u8> {
    method event (line 27) | fn event(&mut self, event: Event) -> Vec<u8> {
    method flush (line 41) | fn flush(&mut self) -> Vec<u8> {
  function text_lines_to_bytes (line 46) | fn text_lines_to_bytes<S: AsRef<str>>(lines: impl Iterator<Item = S>) ->...
  function encoder (line 64) | fn encoder() {

FILE: src/fd.rs
  type FdExt (line 6) | pub trait FdExt: AsFd {
    method set_nonblocking (line 7) | fn set_nonblocking(&self) -> io::Result<()> {

FILE: src/file_writer.rs
  type FileWriter (line 11) | pub struct FileWriter {
    method new (line 25) | pub fn new(
    method start (line 39) | pub async fn start(mut self) -> io::Result<LiveFileWriter> {
  type LiveFileWriter (line 18) | pub struct LiveFileWriter {
    method event (line 79) | async fn event(&mut self, event: session::Event) -> io::Result<()> {
    method flush (line 98) | async fn flush(&mut self) -> io::Result<()> {
  function from (line 104) | fn from(event: session::Event) -> Self {

FILE: src/forwarder.rs
  constant PING_INTERVAL (line 25) | const PING_INTERVAL: u64 = 15;
  constant PING_TIMEOUT (line 26) | const PING_TIMEOUT: u64 = 10;
  constant SEND_TIMEOUT (line 27) | const SEND_TIMEOUT: u64 = 10;
  constant RECONNECT_DELAY_BASE (line 28) | const RECONNECT_DELAY_BASE: u64 = 500;
  constant RECONNECT_DELAY_CAP (line 29) | const RECONNECT_DELAY_CAP: u64 = 10_000;
  function forward (line 31) | pub async fn forward<N: Notifier>(
  function connect_and_forward (line 138) | async fn connect_and_forward(
  function build_request (line 149) | fn build_request(url: &url::Url) -> anyhow::Result<ClientRequestBuilder> {
  function get_alis_stream (line 157) | fn get_alis_stream(
  function handle_socket (line 167) | async fn handle_socket<T>(
  function send_with_timeout (line 222) | async fn send_with_timeout(
  function handle_close_frame (line 231) | fn handle_close_frame(frame: Option<CloseFrame>) -> anyhow::Result<()> {
  function exponential_delay (line 249) | fn exponential_delay(attempt: usize) -> u64 {
  function ws_result (line 257) | fn ws_result(m: Result<Vec<u8>, BroadcastStreamRecvError>) -> anyhow::Re...
  function close_message (line 264) | fn close_message() -> Message {
  function ping_stream (line 271) | fn ping_stream() -> impl Stream<Item = Message> {
  function exponential_delay_is_within_equal_jitter_bounds (line 282) | fn exponential_delay_is_within_equal_jitter_bounds() {

FILE: src/hash.rs
  constant FNV_128_PRIME (line 4) | const FNV_128_PRIME: u128 = 309485009821345068724781371;
  constant FNV_128_OFFSET_BASIS (line 5) | const FNV_128_OFFSET_BASIS: u128 = 144066263297769815596495629667062367629;
  function fnv1a_128 (line 7) | pub fn fnv1a_128<D: AsRef<[u8]>>(data: D) -> u128 {
  function digest (line 23) | fn digest() {

FILE: src/html.rs
  function extract_asciicast_link (line 1) | pub fn extract_asciicast_link(html: &str) -> Option<String> {
  function attr (line 38) | fn attr<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
  function extract_asciicast_link_valid_html (line 69) | fn extract_asciicast_link_valid_html() {
  function extract_asciicast_link_alternate_mime_type (line 87) | fn extract_asciicast_link_alternate_mime_type() {
  function extract_asciicast_link_multiple_rel_values (line 100) | fn extract_asciicast_link_multiple_rel_values() {
  function extract_asciicast_link_case_insensitive (line 113) | fn extract_asciicast_link_case_insensitive() {
  function extract_asciicast_link_single_quotes (line 126) | fn extract_asciicast_link_single_quotes() {
  function extract_asciicast_link_mixed_quotes (line 139) | fn extract_asciicast_link_mixed_quotes() {
  function extract_asciicast_link_multiple_links (line 152) | fn extract_asciicast_link_multiple_links() {
  function extract_asciicast_link_no_head (line 168) | fn extract_asciicast_link_no_head() {
  function extract_asciicast_link_no_matching_link (line 181) | fn extract_asciicast_link_no_matching_link() {
  function extract_asciicast_link_wrong_rel (line 195) | fn extract_asciicast_link_wrong_rel() {
  function extract_asciicast_link_wrong_type (line 208) | fn extract_asciicast_link_wrong_type() {
  function extract_asciicast_link_no_href (line 221) | fn extract_asciicast_link_no_href() {
  function extract_asciicast_link_empty_href (line 234) | fn extract_asciicast_link_empty_href() {
  function extract_asciicast_link_malformed_html (line 247) | fn extract_asciicast_link_malformed_html() {
  function extract_asciicast_link_empty_html (line 260) | fn extract_asciicast_link_empty_html() {
  function extract_asciicast_link_invalid_html (line 265) | fn extract_asciicast_link_invalid_html() {
  function extract_asciicast_link_special_characters_in_href (line 271) | fn extract_asciicast_link_special_characters_in_href() {

FILE: src/leb128.rs
  function encode (line 1) | pub fn encode<N: Into<u64>>(value: N) -> Vec<u8> {
  function test_encode (line 28) | fn test_encode() {

FILE: src/locale.rs
  function check_utf8_locale (line 6) | pub fn check_utf8_locale() -> anyhow::Result<()> {
  function initialize_from_env (line 24) | pub fn initialize_from_env() {
  function get_encoding (line 30) | fn get_encoding() -> String {

FILE: src/main.rs
  function main (line 31) | fn main() -> ExitCode {

FILE: src/notifier.rs
  type Notifier (line 13) | pub trait Notifier: Send {
    method notify (line 14) | async fn notify(&mut self, message: String) -> anyhow::Result<()>;
    method notify (line 41) | async fn notify(&mut self, message: String) -> anyhow::Result<()> {
    method notify (line 58) | async fn notify(&mut self, message: String) -> anyhow::Result<()> {
    method notify (line 73) | async fn notify(&mut self, message: String) -> anyhow::Result<()> {
    method notify (line 85) | async fn notify(&mut self, text: String) -> anyhow::Result<()> {
    method notify (line 100) | async fn notify(&mut self, _text: String) -> anyhow::Result<()> {
    method notify (line 146) | async fn notify(&mut self, message: String) -> anyhow::Result<()> {
  function get_notifier (line 17) | pub fn get_notifier(custom_command: Option<String>) -> Box<dyn Notifier> {
  type TmuxNotifier (line 29) | pub struct TmuxNotifier(PathBuf);
    method get (line 32) | fn get() -> Option<Self> {
  type LibNotifyNotifier (line 48) | pub struct LibNotifyNotifier(PathBuf);
    method get (line 51) | fn get() -> Option<Self> {
  type AppleScriptNotifier (line 63) | pub struct AppleScriptNotifier(PathBuf);
    method get (line 66) | fn get() -> Option<Self> {
  type CustomNotifier (line 81) | pub struct CustomNotifier(String);
  type NullNotifier (line 96) | pub struct NullNotifier;
  function exec (line 105) | async fn exec<S: AsRef<OsStr>>(command: &mut Command, args: &[S]) -> any...
  type BackgroundNotifier (line 125) | pub struct BackgroundNotifier(mpsc::Sender<String>);
  function background (line 127) | pub fn background(mut notifier: Box<dyn Notifier>) -> BackgroundNotifier {

FILE: src/player.rs
  type KeyBindings (line 9) | pub struct KeyBindings {
  method default (line 17) | fn default() -> Self {
  function play (line 27) | pub async fn play(
  function emit_session_events (line 154) | fn emit_session_events(

FILE: src/pty.rs
  type Pty (line 19) | pub struct Pty {
    method read (line 25) | pub async fn read(&self, buffer: &mut [u8]) -> io::Result<usize> {
    method write (line 35) | pub async fn write(&self, buffer: &[u8]) -> io::Result<usize> {
    method resize (line 45) | pub fn resize(&self, winsize: Winsize) {
    method kill (line 49) | pub fn kill(&self) {
    method wait (line 54) | pub async fn wait(&self, options: Option<WaitPidFlag>) -> io::Result<W...
  method drop (line 61) | fn drop(&mut self) {
  function spawn (line 67) | pub fn spawn<S: AsRef<str>>(
  function handle_child (line 89) | fn handle_child<S: AsRef<str>>(
  function spawn (line 114) | async fn spawn<S: AsRef<str>>(command: &[S], extra_env: &HashMap<String,...
  function read_output (line 118) | async fn read_output(pty: Pty) -> Vec<String> {
  function spawn_basic (line 134) | async fn spawn_basic() {
  function spawn_no_output (line 151) | async fn spawn_no_output() {
  function spawn_quick (line 159) | async fn spawn_quick() {
  function spawn_extra_env (line 167) | async fn spawn_extra_env() {
  function spawn_echo_input (line 178) | async fn spawn_echo_input() {

FILE: src/server.rs
  type Assets (line 34) | struct Assets;
  type AssetInfo (line 36) | struct AssetInfo {
  type AssetManifest (line 43) | struct AssetManifest {
  constant DIGEST_HEX_LEN (line 50) | const DIGEST_HEX_LEN: usize = 16;
  type AppState (line 91) | struct AppState {
  function serve (line 96) | pub async fn serve(
  function static_handler (line 144) | async fn static_handler(headers: HeaderMap, uri: Uri) -> impl IntoRespon...
  function mime_from_path (line 188) | fn mime_from_path(path: &str) -> &'static str {
  function asset_response (line 204) | fn asset_response(
  function hex_encode (line 229) | fn hex_encode(bytes: &[u8]) -> String {
  function digest_path (line 233) | fn digest_path(path: &str, hash: &str) -> Option<String> {
  function rewrite_index_html (line 244) | fn rewrite_index_html(by_path: &HashMap<String, AssetInfo>) -> Bytes {
  function etag_matches (line 266) | fn etag_matches(headers: &HeaderMap, etag: &str) -> bool {
  function ws_handler (line 288) | async fn ws_handler(
  function handle_socket (line 311) | async fn handle_socket(socket: WebSocket, subscriber: Subscriber) -> any...
  function close_socket (line 329) | async fn close_socket(mut socket: WebSocket) {
  function close_message (line 334) | fn close_message(code: CloseCode, reason: &'static str) -> Message {
  function ws_result (line 341) | fn ws_result(m: Result<Vec<u8>, BroadcastStreamRecvError>) -> Result<Mes...

FILE: src/session.rs
  constant BUF_SIZE (line 22) | const BUF_SIZE: usize = 128 * 1024;
  type Event (line 25) | pub enum Event {
  type Metadata (line 34) | pub struct Metadata {
  type TermInfo (line 44) | pub struct TermInfo {
  type Session (line 51) | struct Session<N: Notifier> {
  type Output (line 66) | pub trait Output: Send {
    method event (line 67) | async fn event(&mut self, event: Event) -> io::Result<()>;
    method flush (line 68) | async fn flush(&mut self) -> io::Result<()>;
  function run (line 71) | pub async fn run<S: AsRef<str>, T: RawTty + ?Sized, N: Notifier>(
  function forward_events (line 106) | async fn forward_events(mut events_rx: mpsc::Receiver<Event>, outputs: V...
  function forward_event (line 125) | async fn forward_event(mut output: Box<dyn Output>, event: Event) -> Opt...
  function run (line 137) | async fn run<T: RawTty + ?Sized>(mut self, pty: Pty, tty: &mut T) -> any...
  function handle_output (line 237) | async fn handle_output(&mut self, data: &[u8]) {
  function handle_input (line 248) | async fn handle_input(&mut self, data: &[u8]) -> bool {
  function handle_resize (line 292) | async fn handle_resize(&mut self, tty_size: TtySize) {
  function handle_exit (line 300) | async fn handle_exit(&mut self, status: i32) {
  function elapsed_time (line 305) | fn elapsed_time(&self) -> Duration {
  function send_session_event (line 313) | async fn send_session_event(&mut self, event: Event) {
  function notify (line 320) | async fn notify<S: ToString>(&mut self, text: S) {
  type KeyBindings (line 328) | pub struct KeyBindings {
  method default (line 335) | fn default() -> Self {

FILE: src/status.rs
  function disable (line 4) | pub fn disable() {
  function do_info (line 18) | pub fn do_info(message: String) {
  function do_warn (line 24) | pub fn do_warn(message: String) {

FILE: src/stream.rs
  type Stream (line 16) | pub struct Stream {
    method new (line 48) | pub fn new() -> Self {
    method subscriber (line 57) | pub fn subscriber(&self) -> Subscriber {
    method start (line 61) | pub async fn start(self, metadata: &Metadata) -> LiveStream {
  type Request (line 21) | type Request = oneshot::Sender<Subscription>;
  type Subscription (line 23) | struct Subscription {
  type EventId (line 29) | pub struct EventId(u64);
    method new (line 171) | fn new(id: u64) -> Self {
    method next (line 175) | fn next(&self) -> Self {
    method as_u64 (line 179) | pub fn as_u64(&self) -> u64 {
    method from (line 191) | fn from(id: u64) -> Self {
  type Event (line 32) | pub enum Event {
  type Subscriber (line 43) | pub struct Subscriber(mpsc::Sender<Request>);
    method subscribe (line 197) | pub async fn subscribe(
  type LiveStream (line 45) | pub struct LiveStream(mpsc::Sender<session::Event>);
    method event (line 220) | async fn event(&mut self, event: session::Event) -> io::Result<()> {
    method flush (line 224) | async fn flush(&mut self) -> io::Result<()> {
  function run (line 76) | async fn run(
  function from (line 185) | fn from(id: EventId) -> Self {
  function build_vt (line 211) | fn build_vt(tty_size: TtySize) -> Vt {

FILE: src/tty.rs
  type TtySize (line 25) | pub struct TtySize(pub u16, pub u16);
    method from (line 65) | fn from(winsize: Winsize) -> Self {
    method from (line 82) | fn from((cols, rows): (usize, usize)) -> Self {
  type TtyTheme (line 28) | pub struct TtyTheme {
  type NullTty (line 34) | pub struct NullTty;
  type FixedSizeTty (line 36) | pub struct FixedSizeTty<T> {
  type RawTty (line 43) | pub trait RawTty {
    method get_size (line 44) | fn get_size(&self) -> Winsize;
    method read (line 45) | async fn read(&self, buf: &mut [u8]) -> io::Result<usize>;
    method write (line 46) | async fn write(&self, buf: &[u8]) -> io::Result<usize>;
    method write_all (line 48) | async fn write_all(&self, mut buf: &[u8]) -> io::Result<()> {
    method get_size (line 101) | fn get_size(&self) -> Winsize {
    method read (line 110) | async fn read(&self, _buf: &mut [u8]) -> io::Result<usize> {
    method write (line 114) | async fn write(&self, buf: &[u8]) -> io::Result<usize> {
    method get_size (line 121) | fn get_size(&self) -> Winsize {
    method read (line 135) | async fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
    method write (line 139) | async fn write(&self, buf: &[u8]) -> io::Result<usize> {
  method default (line 59) | fn default() -> Self {
  method from (line 71) | fn from(tty_size: TtySize) -> Self {
  function from (line 88) | fn from(tty_size: TtySize) -> Self {
  function new (line 94) | pub fn new(inner: T, cols: Option<u16>, rows: Option<u16>) -> Self {
  function make_raw (line 144) | fn make_raw<F: AsFd>(fd: F) -> anyhow::Result<libc::termios> {
  function fixed_size_tty_get_size (line 160) | fn fixed_size_tty_get_size() {

FILE: src/tty/default.rs
  type DevTty (line 15) | pub struct DevTty {
    method open (line 21) | pub async fn open() -> anyhow::Result<Self> {
    method resize (line 34) | pub async fn resize(&mut self, size: TtySize) -> io::Result<()> {
  method drop (line 43) | fn drop(&mut self) {
  method get_size (line 51) | fn get_size(&self) -> Winsize {
  method read (line 64) | async fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
  method write (line 70) | async fn write(&self, buf: &[u8]) -> io::Result<usize> {

FILE: src/tty/inspect.rs
  constant INSPECT_QUERY (line 6) | const INSPECT_QUERY: &str = concat!(
  function inspect (line 16) | pub(crate) async fn inspect<T: RawTty + ?Sized>(tty: &T) -> (Option<Stri...
  type ParseResult (line 22) | enum ParseResult {
  function query (line 27) | async fn query<T: RawTty + ?Sized>(
  type ReplyParser (line 59) | struct ReplyParser {
    method new (line 68) | fn new() -> Self {
    method feed (line 80) | fn feed(&mut self, chunk: &[u8]) -> ParseResult {
    method result (line 178) | fn result(self) -> (Option<String>, Option<TtyTheme>) {
    method build_theme (line 184) | fn build_theme(&self) -> Option<TtyTheme> {
  type PrefixMatch (line 197) | enum PrefixMatch<'a> {
  function match_seq_prefix (line 202) | fn match_seq_prefix<'a>(a: &'a [u8], b: &[u8]) -> Option<PrefixMatch<'a>> {
  function find_osc_end (line 212) | fn find_osc_end(buf: &[u8]) -> Option<(usize, usize)> {
  function find_dcs_end (line 230) | fn find_dcs_end(buf: &[u8]) -> Option<(usize, usize)> {
  function find_dec_prv_final (line 244) | fn find_dec_prv_final(buf: &[u8]) -> Option<(usize, char)> {
  function parse_dcs_reply (line 258) | fn parse_dcs_reply(reply: &[u8], prefix: &[u8]) -> Option<String> {
  function parse_palette_entries (line 264) | fn parse_palette_entries(reply: &[u8]) -> Vec<(usize, RGB8)> {
  function parse_rgb_color (line 291) | fn parse_rgb_color(rgb: &[u8]) -> Option<RGB8> {
  function parse_hex_byte (line 304) | fn parse_hex_byte(bytes: &[u8]) -> Option<u8> {
  function hex_value (line 315) | fn hex_value(byte: u8) -> Option<u8> {
  constant PALETTE_RESP (line 330) | const PALETTE_RESP: &[u8] = concat!(
  constant FG_RESP (line 350) | const FG_RESP: &[u8] = b"\x1b]10;rgb:1122/3344/5566\x07";
  constant BG_RESP (line 351) | const BG_RESP: &[u8] = b"\x1b]11;rgb:7788/99aa/bbcc\x07";
  constant DA_RESP (line 352) | const DA_RESP: &[u8] = b"\x1b[?1;2c";
  constant XTVERSION_RESP (line 353) | const XTVERSION_RESP: &[u8] = b"\x1bP>|xterm-395\x1b\\";
  function feed_chunks (line 355) | fn feed_chunks(chunks: &[&[u8]]) -> (Option<String>, Option<super::TtyTh...
  function parse_rgb_color (line 371) | fn parse_rgb_color() {
  function parse_palette_entries (line 396) | fn parse_palette_entries() {
  function parser_version_only (line 420) | fn parser_version_only() {
  function parser_theme_only (line 442) | fn parser_theme_only() {
  function parser_version_and_theme (line 479) | fn parser_version_and_theme() {
  function parser_packed_palette (line 499) | fn parser_packed_palette() {
  function parser_chunked_response (line 524) | fn parser_chunked_response() {
  function parser_garbage_ignored (line 561) | fn parser_garbage_ignored() {
  function parser_incomplete_theme (line 584) | fn parser_incomplete_theme() {

FILE: src/tty/macos.rs
  constant BUF_SIZE (line 28) | const BUF_SIZE: usize = 128 * 1024;
  type DevTty (line 30) | pub struct DevTty {
    method open (line 38) | pub async fn open() -> anyhow::Result<Self> {
    method resize (line 81) | pub async fn resize(&mut self, size: TtySize) -> io::Result<()> {
  method drop (line 90) | fn drop(&mut self) {
  method get_size (line 98) | fn get_size(&self) -> Winsize {
  method read (line 111) | async fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
  method write (line 119) | async fn write(&self, buf: &[u8]) -> io::Result<usize> {
  function copy (line 128) | fn copy<F: AsFd, G: AsFd>(src_fd: F, dst_fd: G) {

FILE: src/util.rs
  function get_local_path (line 10) | pub fn get_local_path(filename: &str) -> anyhow::Result<Box<dyn AsRef<Pa...
  function download_asciicast (line 21) | fn download_asciicast(url: &str) -> anyhow::Result<NamedTempFile> {
  type Utf8Decoder (line 53) | pub struct Utf8Decoder(Vec<u8>);
    method new (line 56) | pub fn new() -> Self {
    method feed (line 60) | pub fn feed(&mut self, input: &[u8]) -> String {
  type Quantizer (line 98) | pub struct Quantizer {
    method new (line 104) | pub fn new(q: u128) -> Self {
    method next (line 111) | pub fn next(&mut self, value: u128) -> u128 {
  function utf8_decoder (line 128) | fn utf8_decoder() {
  function quantizer (line 148) | fn quantizer() {
Condensed preview — 70 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (399K chars).
[
  {
    "path": ".cargo/config.toml",
    "chars": 30,
    "preview": "[env]\nRUST_TEST_THREADS = \"1\"\n"
  },
  {
    "path": ".gitattributes",
    "chars": 44,
    "preview": "assets/asciinema-player.* linguist-vendored\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug-report.yml",
    "chars": 3223,
    "preview": "name: Bug Report\ndescription: Report a bug to help improve asciinema CLI\nbody:\n  - type: markdown\n    attributes:\n      "
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "chars": 401,
    "preview": "blank_issues_enabled: false\ncontact_links:\n  - name: Forum\n    url: https://discourse.asciinema.org/\n    about: Ideas, f"
  },
  {
    "path": ".github/workflows/ci.yml",
    "chars": 1205,
    "preview": "name: CI\n\non:\n  push:\n    branches: [\"develop\"]\n  pull_request:\n    branches: [\"develop\"]\n\nenv:\n  CARGO_TERM_COLOR: alwa"
  },
  {
    "path": ".github/workflows/release.yml",
    "chars": 2273,
    "preview": "name: Release\n\npermissions:\n  contents: write\n\non:\n  push:\n    tags:\n      - v[0-9]+.*\n\njobs:\n  create-release:\n    name"
  },
  {
    "path": ".gitignore",
    "chars": 31,
    "preview": "target/\n.envrc\n.direnv\n/result\n"
  },
  {
    "path": "CHANGELOG.md",
    "chars": 16115,
    "preview": "# asciinema changelog\n\n## 3.2.0 (2026-03-01)\n\n* Improved querying for terminal theme and version\n* Added support for pla"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 1778,
    "preview": "# Contributing to asciinema\n\nFirst, if you're opening a GitHub issue make sure it goes to the correct\nrepository:\n\n- [as"
  },
  {
    "path": "Cargo.toml",
    "chars": 2442,
    "preview": "[package]\nname = \"asciinema\"\nversion = \"3.2.0\"\nedition = \"2021\"\nauthors = [\"Marcin Kulik <m@ku1ik.com>\"]\nhomepage = \"htt"
  },
  {
    "path": "Dockerfile",
    "chars": 695,
    "preview": "ARG RUST_VERSION=1.90.0\nFROM rust:${RUST_VERSION}-slim-trixie AS builder\nWORKDIR /app\n\nRUN --mount=type=bind,source=src,"
  },
  {
    "path": "LICENSE",
    "chars": 35147,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 4882,
    "preview": "# asciinema\n\n[![Build Status](https://github.com/asciinema/asciinema/actions/workflows/ci.yml/badge.svg)](https://github"
  },
  {
    "path": "assets/asciinema-player.css",
    "chars": 17936,
    "preview": ".ap-default-term-ff {\n  --term-font-family: \"Cascadia Code\", \"Source Code Pro\", Menlo, Consolas, \"DejaVu Sans Mono\", mon"
  },
  {
    "path": "assets/index.html",
    "chars": 2402,
    "preview": "<!DOCTYPE html>\n<html>\n<head>\n  <meta charset=\"UTF-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scal"
  },
  {
    "path": "build.rs",
    "chars": 979,
    "preview": "use clap::CommandFactory;\nuse clap::ValueEnum;\nuse std::env;\nuse std::fs::create_dir_all;\nuse std::path::Path;\nuse std::"
  },
  {
    "path": "default.nix",
    "chars": 510,
    "preview": "{\n  lib,\n  stdenv,\n  rust,\n  makeRustPlatform,\n  version,\n  libiconv,\n  python3,\n}:\n(makeRustPlatform {\n  cargo = rust;\n"
  },
  {
    "path": "flake.nix",
    "chars": 1133,
    "preview": "{\n  description = \"Terminal session recorder\";\n\n  inputs = {\n    nixpkgs.url = \"github:NixOS/nixpkgs/nixos-unstable\";\n  "
  },
  {
    "path": "shell.nix",
    "chars": 474,
    "preview": "{\n  package,\n  shellcheck,\n  mkShell,\n  rust,\n}:\nlet\n  mkDevShell =\n    rust:\n    mkShell {\n      inputsFrom = [\n       "
  },
  {
    "path": "src/alis.rs",
    "chars": 15498,
    "preview": "// This module implements ALiS (asciinema live stream) protocol, which is an application level\n// protocol built on top "
  },
  {
    "path": "src/api.rs",
    "chars": 8210,
    "preview": "use std::collections::HashMap;\nuse std::env;\nuse std::fmt::Debug;\n\nuse anyhow::{bail, Context, Result};\nuse reqwest::{he"
  },
  {
    "path": "src/asciicast/util.rs",
    "chars": 1111,
    "preview": "use std::time::Duration;\n\nuse anyhow::Result;\nuse serde::{Deserialize, Deserializer};\n\npub fn deserialize_time<'de, D>(d"
  },
  {
    "path": "src/asciicast/v1.rs",
    "chars": 1808,
    "preview": "use std::collections::HashMap;\nuse std::time::Duration;\n\nuse anyhow::{bail, Result};\nuse serde::Deserialize;\n\nuse super:"
  },
  {
    "path": "src/asciicast/v2.rs",
    "chars": 11469,
    "preview": "use std::collections::HashMap;\nuse std::fmt;\nuse std::io;\nuse std::time::Duration;\n\nuse anyhow::{anyhow, bail, Context, "
  },
  {
    "path": "src/asciicast/v3.rs",
    "chars": 12591,
    "preview": "use std::collections::HashMap;\nuse std::fmt;\nuse std::io;\nuse std::time::Duration;\n\nuse anyhow::{anyhow, bail, Context, "
  },
  {
    "path": "src/asciicast.rs",
    "chars": 19070,
    "preview": "mod util;\nmod v1;\nmod v2;\nmod v3;\n\nuse std::collections::HashMap;\nuse std::fmt::Display;\nuse std::fs;\nuse std::io::{self"
  },
  {
    "path": "src/cli.rs",
    "chars": 40979,
    "preview": "use std::net::SocketAddr;\nuse std::num::ParseIntError;\nuse std::path::PathBuf;\n\nuse clap::{ArgGroup, Args, Parser, Subco"
  },
  {
    "path": "src/cmd/auth.rs",
    "chars": 736,
    "preview": "use anyhow::Result;\n\nuse crate::api;\nuse crate::cli;\nuse crate::config::Config;\n\nimpl cli::Auth {\n    pub fn run(self) -"
  },
  {
    "path": "src/cmd/cat.rs",
    "chars": 2028,
    "preview": "use std::io;\nuse std::io::Write;\nuse std::time::Duration;\n\nuse anyhow::{anyhow, Result};\n\nuse crate::asciicast::{self, A"
  },
  {
    "path": "src/cmd/convert.rs",
    "chars": 2519,
    "preview": "use std::fs;\nuse std::path::Path;\nuse std::time::Duration;\n\nuse anyhow::{bail, Result};\n\nuse crate::asciicast;\nuse crate"
  },
  {
    "path": "src/cmd/mod.rs",
    "chars": 91,
    "preview": "pub mod auth;\npub mod cat;\npub mod convert;\npub mod play;\npub mod session;\npub mod upload;\n"
  },
  {
    "path": "src/cmd/play.rs",
    "chars": 1881,
    "preview": "use std::path::Path;\n\nuse tokio::runtime::Runtime;\n\nuse crate::asciicast;\nuse crate::cli;\nuse crate::config::{self, Conf"
  },
  {
    "path": "src/cmd/session.rs",
    "chars": 17348,
    "preview": "use std::collections::{HashMap, HashSet};\nuse std::env;\nuse std::path::{Path, PathBuf};\nuse std::process::{self, ExitCod"
  },
  {
    "path": "src/cmd/upload.rs",
    "chars": 1107,
    "preview": "use anyhow::Result;\nuse tokio::runtime::Runtime;\n\nuse crate::api::{self, RecordingChangeset};\nuse crate::asciicast;\nuse "
  },
  {
    "path": "src/config.rs",
    "chars": 9376,
    "preview": "use std::env;\nuse std::fs;\nuse std::io::ErrorKind;\nuse std::path::{Path, PathBuf};\n\nuse anyhow::{anyhow, bail, Result};\n"
  },
  {
    "path": "src/encoder/asciicast.rs",
    "chars": 1575,
    "preview": "use std::time::Duration;\n\nuse crate::asciicast::{Event, Header, V2Encoder, V3Encoder};\n\npub struct AsciicastV2Encoder {\n"
  },
  {
    "path": "src/encoder/mod.rs",
    "chars": 896,
    "preview": "mod asciicast;\nmod raw;\nmod txt;\n\nuse std::fs::File;\nuse std::io::Write;\n\nuse anyhow::Result;\n\nuse crate::asciicast::{Ev"
  },
  {
    "path": "src/encoder/raw.rs",
    "chars": 1843,
    "preview": "use crate::asciicast::{Event, EventData, Header};\n\npub struct RawEncoder;\n\nimpl RawEncoder {\n    pub fn new() -> Self {\n"
  },
  {
    "path": "src/encoder/txt.rs",
    "chars": 2181,
    "preview": "use avt::util::TextCollector;\n\nuse crate::asciicast::{Event, EventData, Header};\n\npub struct TextEncoder {\n    collector"
  },
  {
    "path": "src/fd.rs",
    "chars": 418,
    "preview": "use std::io;\nuse std::os::fd::AsFd;\n\nuse nix::fcntl::{self, FcntlArg::*, OFlag};\n\npub trait FdExt: AsFd {\n    fn set_non"
  },
  {
    "path": "src/file_writer.rs",
    "chars": 3397,
    "preview": "use std::time::UNIX_EPOCH;\n\nuse async_trait::async_trait;\nuse tokio::io::{self, AsyncWrite, AsyncWriteExt};\n\nuse crate::"
  },
  {
    "path": "src/forwarder.rs",
    "chars": 10522,
    "preview": "use core::future::{self, Future};\nuse std::pin::Pin;\nuse std::time::Duration;\n\nuse anyhow::{anyhow, bail};\nuse axum::htt"
  },
  {
    "path": "src/hash.rs",
    "chars": 876,
    "preview": "// This module implements FNV-1a hashing algorithm\n// http://www.isthe.com/chongo/tech/comp/fnv/\n\nconst FNV_128_PRIME: u"
  },
  {
    "path": "src/html.rs",
    "chars": 7519,
    "preview": "pub fn extract_asciicast_link(html: &str) -> Option<String> {\n    let html_lc = html.to_ascii_lowercase();\n    let head_"
  },
  {
    "path": "src/leb128.rs",
    "chars": 872,
    "preview": "pub fn encode<N: Into<u64>>(value: N) -> Vec<u8> {\n    let mut value: u64 = value.into();\n    let mut bytes = Vec::new()"
  },
  {
    "path": "src/locale.rs",
    "chars": 1210,
    "preview": "use std::env;\nuse std::ffi::CStr;\n\nuse nix::libc::{self, CODESET, LC_ALL};\n\npub fn check_utf8_locale() -> anyhow::Result"
  },
  {
    "path": "src/main.rs",
    "chars": 2818,
    "preview": "mod alis;\nmod api;\nmod asciicast;\nmod cli;\nmod cmd;\nmod config;\nmod encoder;\nmod fd;\nmod file_writer;\nmod forwarder;\nmod"
  },
  {
    "path": "src/notifier.rs",
    "chars": 3810,
    "preview": "use std::env;\nuse std::ffi::OsStr;\nuse std::path::PathBuf;\nuse std::process::Stdio;\n\nuse async_trait::async_trait;\nuse t"
  },
  {
    "path": "src/player.rs",
    "chars": 5805,
    "preview": "use anyhow::Result;\nuse tokio::sync::mpsc;\nuse tokio::time::{self, Duration, Instant};\n\nuse crate::asciicast::{self, Eve"
  },
  {
    "path": "src/pty.rs",
    "chars": 4931,
    "preview": "use std::collections::HashMap;\nuse std::env;\nuse std::ffi::{CString, NulError};\nuse std::os::fd::OwnedFd;\nuse std::os::u"
  },
  {
    "path": "src/server.rs",
    "chars": 9363,
    "preview": "use std::cmp;\nuse std::collections::HashMap;\nuse std::future;\nuse std::io;\nuse std::net::SocketAddr;\nuse std::path::Path"
  },
  {
    "path": "src/session.rs",
    "chars": 10008,
    "preview": "use std::collections::HashMap;\nuse std::time::{Duration, SystemTime};\n\nuse async_trait::async_trait;\nuse bytes::{Buf, By"
  },
  {
    "path": "src/status.rs",
    "chars": 761,
    "preview": "use std::sync::atomic::{AtomicBool, Ordering::SeqCst};\nstatic ENABLED: AtomicBool = AtomicBool::new(true);\n\npub fn disab"
  },
  {
    "path": "src/stream.rs",
    "chars": 6840,
    "preview": "use std::future;\nuse std::time::{Duration, Instant};\n\nuse async_trait::async_trait;\nuse avt::Vt;\nuse futures_util::{stre"
  },
  {
    "path": "src/tty/default.rs",
    "chars": 1872,
    "preview": "use std::fs::File;\nuse std::io::{Read, Write};\nuse std::os::fd::{AsFd, AsRawFd};\nuse std::os::unix::fs::OpenOptionsExt;\n"
  },
  {
    "path": "src/tty/inspect.rs",
    "chars": 19958,
    "preview": "use rgb::RGB8;\nuse tokio::time::{self, Duration};\n\nuse super::{RawTty, TtyTheme};\n\nconst INSPECT_QUERY: &str = concat!(\n"
  },
  {
    "path": "src/tty/macos.rs",
    "chars": 5751,
    "preview": "/// This is an alternative implementation of DevTty that we use on macOS due to a bug in macOS's\n/// kqueue implementati"
  },
  {
    "path": "src/tty.rs",
    "chars": 4035,
    "preview": "mod inspect;\n\nuse std::os::fd::AsFd;\n\nuse async_trait::async_trait;\nuse nix::libc;\nuse nix::pty::Winsize;\nuse nix::sys::"
  },
  {
    "path": "src/util.rs",
    "chars": 5288,
    "preview": "use std::io;\nuse std::path::{Path, PathBuf};\n\nuse anyhow::{anyhow, bail};\nuse reqwest::Url;\nuse tempfile::NamedTempFile;"
  },
  {
    "path": "tests/casts/demo.cast",
    "chars": 5164,
    "preview": "{\"env\": {\"TERM\": \"xterm-256color\", \"SHELL\": \"/usr/local/bin/fish\"}, \"width\": 75, \"height\": 18, \"timestamp\": 1509091818, "
  },
  {
    "path": "tests/casts/demo.json",
    "chars": 5641,
    "preview": "{\n  \"version\": 1,\n  \"width\": 80,\n  \"height\": 40,\n  \"duration\": 6.46111,\n  \"command\": \"/bin/bash\",\n  \"title\": null,\n  \"en"
  },
  {
    "path": "tests/casts/full-v1.json",
    "chars": 317,
    "preview": "{\n  \"version\": 1,\n  \"width\": 100,\n  \"height\": 50,\n  \"duration\": 10.5,\n  \"command\": \"/bin/bash\",\n  \"title\": null,\n  \"env\""
  },
  {
    "path": "tests/casts/full-v2.cast",
    "chars": 417,
    "preview": "{\"version\":2,\"width\":100,\"height\":50,\"timestamp\": 1509091818,\"command\":\"/bin/bash\",\"env\":{\"TERM\":\"xterm-256color\",\"SHELL"
  },
  {
    "path": "tests/casts/full-v3.cast",
    "chars": 423,
    "preview": "{\"version\":3,\"term\":{\"cols\":100,\"rows\":50,\"theme\":{\"fg\":\"#000000\",\"bg\":\"#ffffff\",\"palette\":\"#241f31:#c01c28:#2ec27e:#f5c"
  },
  {
    "path": "tests/casts/minimal-v1.json",
    "chars": 112,
    "preview": "{\n  \"version\": 1,\n  \"width\": 100,\n  \"height\": 50,\n  \"stdout\": [\n    [\n      1.230000,\n      \"hello\"\n    ]\n  ]\n}\n"
  },
  {
    "path": "tests/casts/minimal-v2.cast",
    "chars": 59,
    "preview": "{\"version\":2,\"width\":100,\"height\":50}\n[1.23, \"o\", \"hello\"]\n"
  },
  {
    "path": "tests/casts/minimal-v3.cast",
    "chars": 65,
    "preview": "{\"version\":3,\"term\":{\"cols\":100,\"rows\":50}}\n[1.23, \"o\", \"hello\"]\n"
  },
  {
    "path": "tests/casts/nulls-v1.json",
    "chars": 171,
    "preview": "{\n  \"version\": 1,\n  \"width\": 100,\n  \"height\": 50,\n  \"env\": {\n    \"SHELL\": \"/bin/bash\",\n    \"TERM\": null\n  },\n  \"stdout\":"
  },
  {
    "path": "tests/casts/nulls-v2.cast",
    "chars": 99,
    "preview": "{\"version\":2,\"width\":100,\"height\":50,\"env\":{\"TERM\":null,\"SHELL\":\"/bin/bash\"}}\n[1.23, \"o\", \"hello\"]\n"
  },
  {
    "path": "tests/integration.sh",
    "chars": 17360,
    "preview": "#!/usr/bin/env bash\n\nset -eEuo pipefail -o errtrace\n\n# Colors for output (disabled if no TTY or NO_COLOR set)\nif [[ ! -t"
  }
]

About this extraction

This page contains the full source code of the asciinema/asciinema GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 70 files (371.0 KB), approximately 98.8k tokens, and a symbol index with 507 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!