mirror of
https://github.com/crunchy-labs/crunchy-cli.git
synced 2026-01-21 12:12:00 -06:00
Compare commits
85 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4332b1beef | ||
|
|
2cf9125de3 | ||
|
|
756022b955 | ||
|
|
509683d23a | ||
|
|
8047680799 | ||
|
|
287df84382 | ||
|
|
e7ac6d8874 | ||
|
|
fb8e535644 | ||
|
|
67c267be20 | ||
|
|
a1c7b2069d | ||
|
|
74e5e05b0f | ||
|
|
7d2ae719c8 | ||
|
|
5593046aae | ||
|
|
f8bd092987 | ||
|
|
cbe57e2b6e | ||
|
|
f7ce888329 | ||
|
|
301dac478f | ||
|
|
9819b62259 | ||
|
|
5279a9b759 | ||
|
|
a98e31f959 | ||
|
|
590242712b | ||
|
|
817963af4f | ||
|
|
48bb7a5ef6 | ||
|
|
53a710a373 | ||
|
|
ab63dcd2e0 | ||
|
|
4d1df83342 | ||
|
|
89b9c5db39 | ||
|
|
96d3de48cf | ||
|
|
dad91dba91 | ||
|
|
757d3094ea | ||
|
|
fca1b74cac | ||
|
|
0f7d7d928c | ||
|
|
f77804fcb5 | ||
|
|
4066b8511c | ||
|
|
dcbe433a9c | ||
|
|
55f1e1d32d | ||
|
|
442173c08c | ||
|
|
173292ff32 | ||
|
|
72c574c883 | ||
|
|
f237033aff | ||
|
|
bf28dbf1ce | ||
|
|
cf8bfb02ac | ||
|
|
74aaed4e7a | ||
|
|
177ceb1920 | ||
|
|
541f0e2747 | ||
|
|
777b39aba1 | ||
|
|
4f3475131c | ||
|
|
177aa37631 | ||
|
|
8fff807ae6 | ||
|
|
db6e45e7f4 | ||
|
|
8ada822396 | ||
|
|
9bdd3aa85b | ||
|
|
4fc20c7c1c | ||
|
|
6515d3025f | ||
|
|
fe17f3951e | ||
|
|
cdad7fc000 | ||
|
|
d7dac2acd4 | ||
|
|
dbbb445c55 | ||
|
|
733d9f9787 | ||
|
|
0257fdea0d | ||
|
|
9e5feef4d4 | ||
|
|
b9f5fadbb3 | ||
|
|
ea39dcbc71 | ||
|
|
a73773ce1d | ||
|
|
0115730d60 | ||
|
|
18534b259b | ||
|
|
77103ff1f1 | ||
|
|
771594a231 | ||
|
|
1a511e12f9 | ||
|
|
fe49161e93 | ||
|
|
25cde6163c | ||
|
|
4b74299733 | ||
|
|
c40ea8b132 | ||
|
|
6b6d24a575 | ||
|
|
8c1868f2fd | ||
|
|
af8ab24826 | ||
|
|
c0f3346846 | ||
|
|
111e461b30 | ||
|
|
f16cd25ea4 | ||
|
|
e694046b07 | ||
|
|
ba8028737d | ||
|
|
89be8ac429 | ||
|
|
26a858c1a1 | ||
|
|
d3696c783c | ||
|
|
88a28e843f |
31 changed files with 2411 additions and 1811 deletions
|
|
@ -12,14 +12,26 @@ depends=('ffmpeg' 'openssl')
|
||||||
makedepends=('cargo')
|
makedepends=('cargo')
|
||||||
source=("${pkgname}-${pkgver}.tar.gz::https://github.com/crunchy-labs/crunchy-cli/archive/refs/tags/v${pkgver}.tar.gz")
|
source=("${pkgname}-${pkgver}.tar.gz::https://github.com/crunchy-labs/crunchy-cli/archive/refs/tags/v${pkgver}.tar.gz")
|
||||||
sha256sums=('$CI_SHA_SUM')
|
sha256sums=('$CI_SHA_SUM')
|
||||||
|
# lto causes linking errors when executed by this buildscript. besides, lto is already done by cargo itself (which doesn't cause linking errors)
|
||||||
|
options=(!lto)
|
||||||
|
|
||||||
|
prepare() {
|
||||||
|
cd "$srcdir/${pkgname}-$pkgver"
|
||||||
|
|
||||||
|
export RUSTUP_TOOLCHAIN=stable
|
||||||
|
export CARGO_HOME="$srcdir/cargo-home"
|
||||||
|
|
||||||
|
cargo fetch --locked --target "$(rustc -vV | sed -n 's/host: //p')"
|
||||||
|
}
|
||||||
|
|
||||||
build() {
|
build() {
|
||||||
cd "$srcdir/${pkgname}-$pkgver"
|
cd "$srcdir/${pkgname}-$pkgver"
|
||||||
|
|
||||||
export CARGO_HOME="$srcdir/cargo-home"
|
|
||||||
export RUSTUP_TOOLCHAIN=stable
|
export RUSTUP_TOOLCHAIN=stable
|
||||||
|
export CARGO_HOME="$srcdir/cargo-home"
|
||||||
|
|
||||||
cargo build --release
|
export CRUNCHY_CLI_GIT_HASH=$CI_GIT_HASH
|
||||||
|
cargo build --frozen --release
|
||||||
}
|
}
|
||||||
|
|
||||||
package() {
|
package() {
|
||||||
|
|
@ -1,7 +1,9 @@
|
||||||
name: ci
|
name: build
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
|
branches:
|
||||||
|
- '*'
|
||||||
pull_request:
|
pull_request:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
|
|
@ -39,7 +41,7 @@ jobs:
|
||||||
run: cargo install --force cross
|
run: cargo install --force cross
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
run: cross build --release --no-default-features --features openssl-tls-static --target ${{ matrix.toolchain }}
|
run: cross build --locked --release --no-default-features --features openssl-tls-static --target ${{ matrix.toolchain }}
|
||||||
|
|
||||||
- name: Upload binary artifact
|
- name: Upload binary artifact
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
|
|
@ -99,7 +101,7 @@ jobs:
|
||||||
toolchain: stable
|
toolchain: stable
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
run: cargo build --release --target ${{ matrix.toolchain }}
|
run: cargo build --locked --release --target ${{ matrix.toolchain }}
|
||||||
|
|
||||||
- name: Upload binary artifact
|
- name: Upload binary artifact
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
|
|
@ -133,7 +135,7 @@ jobs:
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
shell: msys2 {0}
|
shell: msys2 {0}
|
||||||
run: cargo build --release --target x86_64-pc-windows-gnu
|
run: cargo build --locked --release --target x86_64-pc-windows-gnu
|
||||||
|
|
||||||
- name: Upload binary artifact
|
- name: Upload binary artifact
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
58
.github/workflows/lint.yml
vendored
Normal file
58
.github/workflows/lint.yml
vendored
Normal file
|
|
@ -0,0 +1,58 @@
|
||||||
|
name: lint
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- '*'
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
fmt:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Cargo cache
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/.cargo/bin/
|
||||||
|
~/.cargo/registry/index/
|
||||||
|
~/.cargo/registry/cache/
|
||||||
|
~/.cargo/git/db/
|
||||||
|
target/
|
||||||
|
key: x86_64-unknown-linux-gnu-cargo-${{ hashFiles('**/Cargo.lock') }}
|
||||||
|
|
||||||
|
- name: Setup Rust
|
||||||
|
uses: dtolnay/rust-toolchain@stable
|
||||||
|
with:
|
||||||
|
toolchain: stable
|
||||||
|
|
||||||
|
- name: Check fmt
|
||||||
|
run: cargo fmt --check
|
||||||
|
|
||||||
|
lint:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Cargo cache
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/.cargo/bin/
|
||||||
|
~/.cargo/registry/index/
|
||||||
|
~/.cargo/registry/cache/
|
||||||
|
~/.cargo/git/db/
|
||||||
|
target/
|
||||||
|
key: x86_64-unknown-linux-gnu-cargo-${{ hashFiles('**/Cargo.lock') }}
|
||||||
|
|
||||||
|
- name: Setup Rust
|
||||||
|
uses: dtolnay/rust-toolchain@stable
|
||||||
|
with:
|
||||||
|
toolchain: stable
|
||||||
|
|
||||||
|
- name: Lint
|
||||||
|
run: cargo clippy -- -D warnings
|
||||||
8
.github/workflows/publish.yml
vendored
8
.github/workflows/publish.yml
vendored
|
|
@ -20,11 +20,15 @@ jobs:
|
||||||
curl -LO https://github.com/crunchy-labs/crunchy-cli/archive/refs/tags/${{ github.ref_name }}.tar.gz
|
curl -LO https://github.com/crunchy-labs/crunchy-cli/archive/refs/tags/${{ github.ref_name }}.tar.gz
|
||||||
echo "CRUNCHY_CLI_SHA256=$(sha256sum ${{ github.ref_name }}.tar.gz | cut -f 1 -d ' ')" >> $GITHUB_ENV
|
echo "CRUNCHY_CLI_SHA256=$(sha256sum ${{ github.ref_name }}.tar.gz | cut -f 1 -d ' ')" >> $GITHUB_ENV
|
||||||
|
|
||||||
|
- name: Get release commit hash
|
||||||
|
run: echo "CRUNCHY_CLI_GIT_HASH=$(git rev-parse --short HEAD)" >> $GITHUB_ENV
|
||||||
|
|
||||||
- name: Generate crunchy-cli PKGBUILD
|
- name: Generate crunchy-cli PKGBUILD
|
||||||
env:
|
env:
|
||||||
CI_PKG_VERSION: ${{ env.RELEASE_VERSION }}
|
CI_PKG_VERSION: ${{ env.RELEASE_VERSION }}
|
||||||
CI_SHA_SUM: ${{ env.CRUNCHY_CLI_SHA256 }}
|
CI_SHA_SUM: ${{ env.CRUNCHY_CLI_SHA256 }}
|
||||||
run: envsubst '$CI_PKG_VERSION,$CI_SHA_SUM' < .github/scripts/PKGBUILD.source > PKGBUILD
|
CI_GIT_HASH: ${{ env.CRUNCHY_CLI_GIT_HASH }}
|
||||||
|
run: envsubst '$CI_PKG_VERSION,$CI_SHA_SUM,$CI_GIT_HASH' < .github/workflow-resources/PKGBUILD.source > PKGBUILD
|
||||||
|
|
||||||
- name: Publish crunchy-cli to AUR
|
- name: Publish crunchy-cli to AUR
|
||||||
uses: KSXGitHub/github-actions-deploy-aur@v2.7.0
|
uses: KSXGitHub/github-actions-deploy-aur@v2.7.0
|
||||||
|
|
@ -57,7 +61,7 @@ jobs:
|
||||||
CI_MANPAGES_SHA_SUM: ${{ env.CRUNCHY_CLI_BIN_MANPAGES_SHA256 }}
|
CI_MANPAGES_SHA_SUM: ${{ env.CRUNCHY_CLI_BIN_MANPAGES_SHA256 }}
|
||||||
CI_COMPLETIONS_SHA_SUM: ${{ env.CRUNCHY_CLI_BIN_COMPLETIONS_SHA256 }}
|
CI_COMPLETIONS_SHA_SUM: ${{ env.CRUNCHY_CLI_BIN_COMPLETIONS_SHA256 }}
|
||||||
CI_LICENSE_SHA_SUM: ${{ env.CRUNCHY_CLI_BIN_LICENSE_SHA256 }}
|
CI_LICENSE_SHA_SUM: ${{ env.CRUNCHY_CLI_BIN_LICENSE_SHA256 }}
|
||||||
run: envsubst '$CI_PKG_VERSION,$CI_AMD_BINARY_SHA_SUM,$CI_ARM_BINARY_SHA_SUM,$CI_COMPLETIONS_SHA_SUM,$CI_MANPAGES_SHA_SUM,$CI_LICENSE_SHA_SUM' < .github/scripts/PKGBUILD.binary > PKGBUILD
|
run: envsubst '$CI_PKG_VERSION,$CI_AMD_BINARY_SHA_SUM,$CI_ARM_BINARY_SHA_SUM,$CI_COMPLETIONS_SHA_SUM,$CI_MANPAGES_SHA_SUM,$CI_LICENSE_SHA_SUM' < .github/workflow-resources/PKGBUILD.binary > PKGBUILD
|
||||||
|
|
||||||
- name: Publish crunchy-cli-bin to AUR
|
- name: Publish crunchy-cli-bin to AUR
|
||||||
uses: KSXGitHub/github-actions-deploy-aur@v2.7.0
|
uses: KSXGitHub/github-actions-deploy-aur@v2.7.0
|
||||||
|
|
|
||||||
965
Cargo.lock
generated
965
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
|
@ -1,7 +1,7 @@
|
||||||
[package]
|
[package]
|
||||||
name = "crunchy-cli"
|
name = "crunchy-cli"
|
||||||
authors = ["Crunchy Labs Maintainers"]
|
authors = ["Crunchy Labs Maintainers"]
|
||||||
version = "3.3.0"
|
version = "3.6.7"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
|
|
||||||
|
|
@ -14,9 +14,9 @@ openssl-tls = ["dep:native-tls-crate", "native-tls-crate/openssl", "crunchy-cli-
|
||||||
openssl-tls-static = ["dep:native-tls-crate", "native-tls-crate/openssl", "crunchy-cli-core/openssl-tls-static"]
|
openssl-tls-static = ["dep:native-tls-crate", "native-tls-crate/openssl", "crunchy-cli-core/openssl-tls-static"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
tokio = { version = "1.36", features = ["macros", "rt-multi-thread", "time"], default-features = false }
|
tokio = { version = "1.38", features = ["macros", "rt-multi-thread", "time"], default-features = false }
|
||||||
|
|
||||||
native-tls-crate = { package = "native-tls", version = "0.2.11", optional = true }
|
native-tls-crate = { package = "native-tls", version = "0.2.12", optional = true }
|
||||||
|
|
||||||
crunchy-cli-core = { path = "./crunchy-cli-core" }
|
crunchy-cli-core = { path = "./crunchy-cli-core" }
|
||||||
|
|
||||||
|
|
@ -34,7 +34,7 @@ members = ["crunchy-cli-core"]
|
||||||
[patch.crates-io]
|
[patch.crates-io]
|
||||||
# fork of the `native-tls` crate which can use openssl as backend on every platform. this is done as `reqwest` only
|
# fork of the `native-tls` crate which can use openssl as backend on every platform. this is done as `reqwest` only
|
||||||
# supports `rustls` and `native-tls` as tls backend
|
# supports `rustls` and `native-tls` as tls backend
|
||||||
native-tls = { git = "https://github.com/crunchy-labs/rust-not-so-native-tls.git", rev = "fdba246" }
|
native-tls = { git = "https://github.com/crunchy-labs/rust-not-so-native-tls.git", rev = "c7ac566" }
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
strip = true
|
strip = true
|
||||||
|
|
|
||||||
143
README.md
143
README.md
|
|
@ -1,3 +1,5 @@
|
||||||
|
# This project has been sunset as Crunchyroll moved to a DRM-only system. See [#362](https://github.com/crunchy-labs/crunchy-cli/issues/362).
|
||||||
|
|
||||||
# crunchy-cli
|
# crunchy-cli
|
||||||
|
|
||||||
👇 A Command-line downloader for [Crunchyroll](https://www.crunchyroll.com).
|
👇 A Command-line downloader for [Crunchyroll](https://www.crunchyroll.com).
|
||||||
|
|
@ -18,8 +20,8 @@
|
||||||
<a href="https://discord.gg/PXGPGpQxgk">
|
<a href="https://discord.gg/PXGPGpQxgk">
|
||||||
<img src="https://img.shields.io/discord/994882878125121596?label=discord&style=flat-square" alt="Discord">
|
<img src="https://img.shields.io/discord/994882878125121596?label=discord&style=flat-square" alt="Discord">
|
||||||
</a>
|
</a>
|
||||||
<a href="https://github.com/crunchy-labs/crunchy-cli/actions/workflows/ci.yml">
|
<a href="https://github.com/crunchy-labs/crunchy-cli/actions/workflows/build.yml">
|
||||||
<img src="https://img.shields.io/github/actions/workflow/status/crunchy-labs/crunchy-cli/ci.yml?branch=master&style=flat-square" alt="CI">
|
<img src="https://img.shields.io/github/actions/workflow/status/crunchy-labs/crunchy-cli/build.yml?branch=master&style=flat-square" alt="Build">
|
||||||
</a>
|
</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
|
@ -112,23 +114,13 @@ crunchy-cli requires you to log in.
|
||||||
Though you can use a non-premium account, you will not have access to premium content without a subscription.
|
Though you can use a non-premium account, you will not have access to premium content without a subscription.
|
||||||
You can authenticate with your credentials (email:password) or by using a refresh token.
|
You can authenticate with your credentials (email:password) or by using a refresh token.
|
||||||
|
|
||||||
- Credentials
|
- <span id="global-credentials">Credentials</span>
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
$ crunchy-cli --credentials "email:password" <command>
|
$ crunchy-cli --credentials "email:password" <command>
|
||||||
```
|
```
|
||||||
|
|
||||||
- Refresh Token
|
- <span id="global-anonymous">Stay Anonymous</span>
|
||||||
|
|
||||||
To obtain a refresh token, you have to log in at [crunchyroll.com](https://www.crunchyroll.com/) and extract the `etp_rt` cookie.
|
|
||||||
The easiest way to get it is via a browser extension which lets you export your cookies, like [Cookie-Editor](https://cookie-editor.cgagnier.ca/) ([Firefox](https://addons.mozilla.org/en-US/firefox/addon/cookie-editor/) / [Chrome](https://chrome.google.com/webstore/detail/cookie-editor/hlkenndednhfkekhgcdicdfddnkalmdm)).
|
|
||||||
When installed, look for the `etp_rt` entry and extract its value.
|
|
||||||
|
|
||||||
```shell
|
|
||||||
$ crunchy-cli --etp-rt "4ebf1690-53a4-491a-a2ac-488309120f5d" <command>
|
|
||||||
```
|
|
||||||
|
|
||||||
- Stay Anonymous
|
|
||||||
|
|
||||||
Login without an account (you won't be able to access premium content):
|
Login without an account (you won't be able to access premium content):
|
||||||
|
|
||||||
|
|
@ -140,7 +132,7 @@ You can authenticate with your credentials (email:password) or by using a refres
|
||||||
|
|
||||||
You can set specific settings which will be
|
You can set specific settings which will be
|
||||||
|
|
||||||
- Verbose output
|
- <span id="global-verbose">Verbose output</span>
|
||||||
|
|
||||||
If you want to include debug information in the output, use the `-v` / `--verbose` flag to show it.
|
If you want to include debug information in the output, use the `-v` / `--verbose` flag to show it.
|
||||||
|
|
||||||
|
|
@ -148,9 +140,9 @@ You can set specific settings which will be
|
||||||
$ crunchy-cli -v <command>
|
$ crunchy-cli -v <command>
|
||||||
```
|
```
|
||||||
|
|
||||||
This flag can't be used with `-q` / `--quiet`.
|
This flag can't be used in combination with `-q` / `--quiet`.
|
||||||
|
|
||||||
- Quiet output
|
- <span id="global-quiet">Quiet output</span>
|
||||||
|
|
||||||
If you want to hide all output, use the `-q` / `--quiet` flag to do so.
|
If you want to hide all output, use the `-q` / `--quiet` flag to do so.
|
||||||
This is especially useful if you want to pipe the output video to an external program (like a video player).
|
This is especially useful if you want to pipe the output video to an external program (like a video player).
|
||||||
|
|
@ -159,7 +151,9 @@ You can set specific settings which will be
|
||||||
$ crunchy-cli -q <command>
|
$ crunchy-cli -q <command>
|
||||||
```
|
```
|
||||||
|
|
||||||
- Language
|
This flag can't be used in combination with `-v` / `--verbose`.
|
||||||
|
|
||||||
|
- <span id="global-lang">Language</span>
|
||||||
|
|
||||||
By default, the resulting metadata like title or description are shown in your system language (if Crunchyroll supports it, else in English).
|
By default, the resulting metadata like title or description are shown in your system language (if Crunchyroll supports it, else in English).
|
||||||
If you want to show the results in another language, use the `--lang` flag to set it.
|
If you want to show the results in another language, use the `--lang` flag to set it.
|
||||||
|
|
@ -168,7 +162,7 @@ You can set specific settings which will be
|
||||||
$ crunchy-cli --lang de-DE <command>
|
$ crunchy-cli --lang de-DE <command>
|
||||||
```
|
```
|
||||||
|
|
||||||
- Experimental fixes
|
- <span id="global-experimental-fixes">Experimental fixes</span>
|
||||||
|
|
||||||
Crunchyroll constantly changes and breaks its services or just delivers incorrect answers.
|
Crunchyroll constantly changes and breaks its services or just delivers incorrect answers.
|
||||||
The `--experimental-fixes` flag tries to fix some of those issues.
|
The `--experimental-fixes` flag tries to fix some of those issues.
|
||||||
|
|
@ -180,7 +174,7 @@ You can set specific settings which will be
|
||||||
|
|
||||||
For an overview which parts this flag affects, see the [documentation](https://docs.rs/crunchyroll-rs/latest/crunchyroll_rs/crunchyroll/struct.CrunchyrollBuilder.html) of the underlying Crunchyroll library, all functions beginning with `stabilization_` are applied.
|
For an overview which parts this flag affects, see the [documentation](https://docs.rs/crunchyroll-rs/latest/crunchyroll_rs/crunchyroll/struct.CrunchyrollBuilder.html) of the underlying Crunchyroll library, all functions beginning with `stabilization_` are applied.
|
||||||
|
|
||||||
- Proxy
|
- <span id="global-proxy">Proxy</span>
|
||||||
|
|
||||||
The `--proxy` flag supports https and socks5 proxies to route all your traffic through.
|
The `--proxy` flag supports https and socks5 proxies to route all your traffic through.
|
||||||
This may be helpful to bypass the geo-restrictions Crunchyroll has on certain series.
|
This may be helpful to bypass the geo-restrictions Crunchyroll has on certain series.
|
||||||
|
|
@ -193,7 +187,7 @@ You can set specific settings which will be
|
||||||
|
|
||||||
Make sure that proxy can either forward TLS requests, which is needed to bypass the (cloudflare) bot protection, or that it is configured so that the proxy can bypass the protection itself.
|
Make sure that proxy can either forward TLS requests, which is needed to bypass the (cloudflare) bot protection, or that it is configured so that the proxy can bypass the protection itself.
|
||||||
|
|
||||||
- User Agent
|
- <span id="global-user-agent">User Agent</span>
|
||||||
|
|
||||||
There might be cases where a custom user agent is necessary, e.g. to bypass the cloudflare bot protection (#104).
|
There might be cases where a custom user agent is necessary, e.g. to bypass the cloudflare bot protection (#104).
|
||||||
In such cases, the `--user-agent` flag can be used to set a custom user agent.
|
In such cases, the `--user-agent` flag can be used to set a custom user agent.
|
||||||
|
|
@ -204,7 +198,7 @@ You can set specific settings which will be
|
||||||
|
|
||||||
Default is the user agent, defined in the underlying [library](https://github.com/crunchy-labs/crunchyroll-rs).
|
Default is the user agent, defined in the underlying [library](https://github.com/crunchy-labs/crunchyroll-rs).
|
||||||
|
|
||||||
- Speed limit
|
- <span id="global-speed-limit">Speed limit</span>
|
||||||
|
|
||||||
If you want to limit how fast requests/downloads should be, you can use the `--speed-limit` flag. Allowed units are `B` (bytes), `KB` (kilobytes) and `MB` (megabytes).
|
If you want to limit how fast requests/downloads should be, you can use the `--speed-limit` flag. Allowed units are `B` (bytes), `KB` (kilobytes) and `MB` (megabytes).
|
||||||
|
|
||||||
|
|
@ -220,11 +214,9 @@ The `login` command can store your session, so you don't have to authenticate ev
|
||||||
# save the refresh token which gets generated when login with credentials.
|
# save the refresh token which gets generated when login with credentials.
|
||||||
# your email and password won't be stored at any time on disk
|
# your email and password won't be stored at any time on disk
|
||||||
$ crunchy-cli login --credentials "email:password"
|
$ crunchy-cli login --credentials "email:password"
|
||||||
# save etp-rt cookie
|
|
||||||
$ crunchy-cli login --etp-rt "4ebf1690-53a4-491a-a2ac-488309120f5d"
|
|
||||||
```
|
```
|
||||||
|
|
||||||
With the session stored, you do not need to pass `--credentials` / `--etp-rt` / `--anonymous` anymore when you want to execute a command.
|
With the session stored, you do not need to pass `--credentials` / `--anonymous` anymore when you want to execute a command.
|
||||||
|
|
||||||
### Download
|
### Download
|
||||||
|
|
||||||
|
|
@ -243,7 +235,7 @@ The `download` command lets you download episodes with a specific audio language
|
||||||
|
|
||||||
**Options**
|
**Options**
|
||||||
|
|
||||||
- Audio language
|
- <span id="download-audio">Audio language</span>
|
||||||
|
|
||||||
Set the audio language with the `-a` / `--audio` flag.
|
Set the audio language with the `-a` / `--audio` flag.
|
||||||
This only works if the url points to a series since episode urls are language specific.
|
This only works if the url points to a series since episode urls are language specific.
|
||||||
|
|
@ -254,7 +246,7 @@ The `download` command lets you download episodes with a specific audio language
|
||||||
|
|
||||||
Default is your system locale. If not supported by Crunchyroll, `en-US` (American English) is the default.
|
Default is your system locale. If not supported by Crunchyroll, `en-US` (American English) is the default.
|
||||||
|
|
||||||
- Subtitle language
|
- <span id="download-subtitle">Subtitle language</span>
|
||||||
|
|
||||||
Besides the audio, you can specify the subtitle language by using the `-s` / `--subtitle` flag.
|
Besides the audio, you can specify the subtitle language by using the `-s` / `--subtitle` flag.
|
||||||
In formats that support it (.mp4, .mov and .mkv ), subtitles are stored as soft-subs. All other formats are hardsubbed: the subtitles will be burned into the video track (cf. [hardsub](https://www.urbandictionary.com/define.php?term=hardsub)) and thus can not be turned off.
|
In formats that support it (.mp4, .mov and .mkv ), subtitles are stored as soft-subs. All other formats are hardsubbed: the subtitles will be burned into the video track (cf. [hardsub](https://www.urbandictionary.com/define.php?term=hardsub)) and thus can not be turned off.
|
||||||
|
|
@ -265,7 +257,7 @@ The `download` command lets you download episodes with a specific audio language
|
||||||
|
|
||||||
Default is none.
|
Default is none.
|
||||||
|
|
||||||
- Output template
|
- <span id="download-output">Output template</span>
|
||||||
|
|
||||||
Define an output template by using the `-o` / `--output` flag.
|
Define an output template by using the `-o` / `--output` flag.
|
||||||
|
|
||||||
|
|
@ -275,7 +267,7 @@ The `download` command lets you download episodes with a specific audio language
|
||||||
|
|
||||||
Default is `{title}.mp4`. See the [Template Options section](#output-template-options) below for more options.
|
Default is `{title}.mp4`. See the [Template Options section](#output-template-options) below for more options.
|
||||||
|
|
||||||
- Output template for special episodes
|
- <span id="download-output-specials">Output template for special episodes</span>
|
||||||
|
|
||||||
Define an output template which only gets used when the episode is a special (episode number is 0 or has non-zero decimal places) by using the `--output-special` flag.
|
Define an output template which only gets used when the episode is a special (episode number is 0 or has non-zero decimal places) by using the `--output-special` flag.
|
||||||
|
|
||||||
|
|
@ -285,7 +277,7 @@ The `download` command lets you download episodes with a specific audio language
|
||||||
|
|
||||||
Default is the template, set by the `-o` / `--output` flag. See the [Template Options section](#output-template-options) below for more options.
|
Default is the template, set by the `-o` / `--output` flag. See the [Template Options section](#output-template-options) below for more options.
|
||||||
|
|
||||||
- Universal output
|
- <span id="download-universal-output">Universal output</span>
|
||||||
|
|
||||||
The output template options can be forced to get sanitized via the `--universal-output` flag to be valid across all supported operating systems (Windows has a lot of characters which aren't allowed in filenames...).
|
The output template options can be forced to get sanitized via the `--universal-output` flag to be valid across all supported operating systems (Windows has a lot of characters which aren't allowed in filenames...).
|
||||||
|
|
||||||
|
|
@ -293,7 +285,7 @@ The `download` command lets you download episodes with a specific audio language
|
||||||
$ crunchy-cli download --universal-output -o https://www.crunchyroll.com/watch/G7PU4XD48/tales-veldoras-journal-2
|
$ crunchy-cli download --universal-output -o https://www.crunchyroll.com/watch/G7PU4XD48/tales-veldoras-journal-2
|
||||||
```
|
```
|
||||||
|
|
||||||
- Resolution
|
- <span id="download-resolution">Resolution</span>
|
||||||
|
|
||||||
The resolution for videos can be set via the `-r` / `--resolution` flag.
|
The resolution for videos can be set via the `-r` / `--resolution` flag.
|
||||||
|
|
||||||
|
|
@ -303,7 +295,7 @@ The `download` command lets you download episodes with a specific audio language
|
||||||
|
|
||||||
Default is `best`.
|
Default is `best`.
|
||||||
|
|
||||||
- Language tagging
|
- <span id="download-language-tagging">Language tagging</span>
|
||||||
|
|
||||||
You can force the usage of a specific language tagging in the output file with the `--language-tagging` flag.
|
You can force the usage of a specific language tagging in the output file with the `--language-tagging` flag.
|
||||||
This might be useful as some video players doesn't recognize the language tagging Crunchyroll uses internally.
|
This might be useful as some video players doesn't recognize the language tagging Crunchyroll uses internally.
|
||||||
|
|
@ -312,7 +304,7 @@ The `download` command lets you download episodes with a specific audio language
|
||||||
$ crunchy-cli download --language-tagging ietf https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome
|
$ crunchy-cli download --language-tagging ietf https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome
|
||||||
```
|
```
|
||||||
|
|
||||||
- FFmpeg Preset
|
- <span id="download-ffmpeg-preset">FFmpeg Preset</span>
|
||||||
|
|
||||||
You can specify specific built-in presets with the `--ffmpeg-preset` flag to convert videos to a specific coding while downloading.
|
You can specify specific built-in presets with the `--ffmpeg-preset` flag to convert videos to a specific coding while downloading.
|
||||||
Multiple predefined presets how videos should be encoded (h264, h265, av1, ...) are available, you can see them with `crunchy-cli download --help`.
|
Multiple predefined presets how videos should be encoded (h264, h265, av1, ...) are available, you can see them with `crunchy-cli download --help`.
|
||||||
|
|
@ -322,7 +314,7 @@ The `download` command lets you download episodes with a specific audio language
|
||||||
$ crunchy-cli download --ffmpeg-preset av1-lossless https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome
|
$ crunchy-cli download --ffmpeg-preset av1-lossless https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome
|
||||||
```
|
```
|
||||||
|
|
||||||
- FFmpeg threads
|
- <span id="download-ffmpeg-threads">FFmpeg threads</span>
|
||||||
|
|
||||||
If you want to manually set how many threads FFmpeg should use, you can use the `--ffmpeg-threads` flag. This does not work with every codec/preset and is skipped entirely when specifying custom ffmpeg output arguments instead of a preset for `--ffmpeg-preset`.
|
If you want to manually set how many threads FFmpeg should use, you can use the `--ffmpeg-threads` flag. This does not work with every codec/preset and is skipped entirely when specifying custom ffmpeg output arguments instead of a preset for `--ffmpeg-preset`.
|
||||||
|
|
||||||
|
|
@ -330,7 +322,7 @@ The `download` command lets you download episodes with a specific audio language
|
||||||
$ crunchy-cli download --ffmpeg-threads 4 https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome
|
$ crunchy-cli download --ffmpeg-threads 4 https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome
|
||||||
```
|
```
|
||||||
|
|
||||||
- Skip existing
|
- <span id="download-skip-existing">Skip existing</span>
|
||||||
|
|
||||||
If you re-download a series but want to skip episodes you've already downloaded, the `--skip-existing` flag skips the already existing/downloaded files.
|
If you re-download a series but want to skip episodes you've already downloaded, the `--skip-existing` flag skips the already existing/downloaded files.
|
||||||
|
|
||||||
|
|
@ -338,7 +330,7 @@ The `download` command lets you download episodes with a specific audio language
|
||||||
$ crunchy-cli download --skip-existing https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx
|
$ crunchy-cli download --skip-existing https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx
|
||||||
```
|
```
|
||||||
|
|
||||||
- Skip specials
|
- <span id="download-skip-specials">Skip specials</span>
|
||||||
|
|
||||||
If you doesn't want to download special episodes, use the `--skip-specials` flag to skip the download of them.
|
If you doesn't want to download special episodes, use the `--skip-specials` flag to skip the download of them.
|
||||||
|
|
||||||
|
|
@ -346,7 +338,7 @@ The `download` command lets you download episodes with a specific audio language
|
||||||
$ crunchy-cli download --skip-specials https://www.crunchyroll.com/series/GYZJ43JMR/that-time-i-got-reincarnated-as-a-slime[S2]
|
$ crunchy-cli download --skip-specials https://www.crunchyroll.com/series/GYZJ43JMR/that-time-i-got-reincarnated-as-a-slime[S2]
|
||||||
```
|
```
|
||||||
|
|
||||||
- Include chapters
|
- <span id="download-include-chapters">Include chapters</span>
|
||||||
|
|
||||||
Crunchyroll sometimes provide information about skippable events like the intro or credits.
|
Crunchyroll sometimes provide information about skippable events like the intro or credits.
|
||||||
These information can be stored as chapters in the resulting video file via the `--include-chapters` flag.
|
These information can be stored as chapters in the resulting video file via the `--include-chapters` flag.
|
||||||
|
|
@ -355,7 +347,7 @@ The `download` command lets you download episodes with a specific audio language
|
||||||
$ crunchy-cli download --include-chapters https://www.crunchyroll.com/watch/G0DUND0K2/the-journeys-end
|
$ crunchy-cli download --include-chapters https://www.crunchyroll.com/watch/G0DUND0K2/the-journeys-end
|
||||||
```
|
```
|
||||||
|
|
||||||
- Yes
|
- <span id="download-yes">Yes</span>
|
||||||
|
|
||||||
Sometimes different seasons have the same season number (e.g. Sword Art Online Alicization and Alicization War of Underworld are both marked as season 3), in such cases an interactive prompt is shown which needs user further user input to decide which season to download.
|
Sometimes different seasons have the same season number (e.g. Sword Art Online Alicization and Alicization War of Underworld are both marked as season 3), in such cases an interactive prompt is shown which needs user further user input to decide which season to download.
|
||||||
The `--yes` flag suppresses this interactive prompt and just downloads all seasons.
|
The `--yes` flag suppresses this interactive prompt and just downloads all seasons.
|
||||||
|
|
@ -366,7 +358,7 @@ The `download` command lets you download episodes with a specific audio language
|
||||||
|
|
||||||
If you've passed the `-q` / `--quiet` [global flag](#global-settings), this flag is automatically set.
|
If you've passed the `-q` / `--quiet` [global flag](#global-settings), this flag is automatically set.
|
||||||
|
|
||||||
- Force hardsub
|
- <span id="download-force-hardsub">Force hardsub</span>
|
||||||
|
|
||||||
If you want to burn-in the subtitles, even if the output format/container supports soft-subs (e.g. `.mp4`), use the `--force-hardsub` flag to do so.
|
If you want to burn-in the subtitles, even if the output format/container supports soft-subs (e.g. `.mp4`), use the `--force-hardsub` flag to do so.
|
||||||
|
|
||||||
|
|
@ -374,7 +366,7 @@ The `download` command lets you download episodes with a specific audio language
|
||||||
$ crunchy-cli download --force-hardsub -s en-US https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome
|
$ crunchy-cli download --force-hardsub -s en-US https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome
|
||||||
```
|
```
|
||||||
|
|
||||||
- Threads
|
- <span id="download-threads">Threads</span>
|
||||||
|
|
||||||
To increase the download speed, video segments are downloaded simultaneously by creating multiple threads.
|
To increase the download speed, video segments are downloaded simultaneously by creating multiple threads.
|
||||||
If you want to manually specify how many threads to use when downloading, do this with the `-t` / `--threads` flag.
|
If you want to manually specify how many threads to use when downloading, do this with the `-t` / `--threads` flag.
|
||||||
|
|
@ -402,7 +394,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
|
||||||
|
|
||||||
**Options**
|
**Options**
|
||||||
|
|
||||||
- Audio languages
|
- <span id="archive-audio">Audio languages</span>
|
||||||
|
|
||||||
Set the audio language with the `-a` / `--audio` flag. Can be used multiple times.
|
Set the audio language with the `-a` / `--audio` flag. Can be used multiple times.
|
||||||
|
|
||||||
|
|
@ -412,7 +404,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
|
||||||
|
|
||||||
Default is your system locale (if not supported by Crunchyroll, `en-US` (American English) and `ja-JP` (Japanese) are used).
|
Default is your system locale (if not supported by Crunchyroll, `en-US` (American English) and `ja-JP` (Japanese) are used).
|
||||||
|
|
||||||
- Subtitle languages
|
- <span id="archive-subtitle">Subtitle languages</span>
|
||||||
|
|
||||||
Besides the audio, you can specify the subtitle language by using the `-s` / `--subtitle` flag.
|
Besides the audio, you can specify the subtitle language by using the `-s` / `--subtitle` flag.
|
||||||
|
|
||||||
|
|
@ -422,7 +414,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
|
||||||
|
|
||||||
Default is `all` subtitles.
|
Default is `all` subtitles.
|
||||||
|
|
||||||
- Output template
|
- <span id="archive-output">Output template</span>
|
||||||
|
|
||||||
Define an output template by using the `-o` / `--output` flag.
|
Define an output template by using the `-o` / `--output` flag.
|
||||||
_crunchy-cli_ exclusively uses the [`.mkv`](https://en.wikipedia.org/wiki/Matroska) container format, because of its ability to store multiple audio, video and subtitle tracks at once.
|
_crunchy-cli_ exclusively uses the [`.mkv`](https://en.wikipedia.org/wiki/Matroska) container format, because of its ability to store multiple audio, video and subtitle tracks at once.
|
||||||
|
|
@ -433,7 +425,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
|
||||||
|
|
||||||
Default is `{title}.mkv`. See the [Template Options section](#output-template-options) below for more options.
|
Default is `{title}.mkv`. See the [Template Options section](#output-template-options) below for more options.
|
||||||
|
|
||||||
- Output template for special episodes
|
- <span id="archive-output-specials">Output template for special episodes</span>
|
||||||
|
|
||||||
Define an output template which only gets used when the episode is a special (episode number is 0 or has non-zero decimal places) by using the `--output-special` flag.
|
Define an output template which only gets used when the episode is a special (episode number is 0 or has non-zero decimal places) by using the `--output-special` flag.
|
||||||
_crunchy-cli_ exclusively uses the [`.mkv`](https://en.wikipedia.org/wiki/Matroska) container format, because of its ability to store multiple audio, video and subtitle tracks at once.
|
_crunchy-cli_ exclusively uses the [`.mkv`](https://en.wikipedia.org/wiki/Matroska) container format, because of its ability to store multiple audio, video and subtitle tracks at once.
|
||||||
|
|
@ -444,7 +436,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
|
||||||
|
|
||||||
Default is the template, set by the `-o` / `--output` flag. See the [Template Options section](#output-template-options) below for more options.
|
Default is the template, set by the `-o` / `--output` flag. See the [Template Options section](#output-template-options) below for more options.
|
||||||
|
|
||||||
- Universal output
|
- <span id="archive-universal-output">Universal output</span>
|
||||||
|
|
||||||
The output template options can be forced to get sanitized via the `--universal-output` flag to be valid across all supported operating systems (Windows has a lot of characters which aren't allowed in filenames...).
|
The output template options can be forced to get sanitized via the `--universal-output` flag to be valid across all supported operating systems (Windows has a lot of characters which aren't allowed in filenames...).
|
||||||
|
|
||||||
|
|
@ -452,7 +444,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
|
||||||
$ crunchy-cli archive --universal-output -o https://www.crunchyroll.com/watch/G7PU4XD48/tales-veldoras-journal-2
|
$ crunchy-cli archive --universal-output -o https://www.crunchyroll.com/watch/G7PU4XD48/tales-veldoras-journal-2
|
||||||
```
|
```
|
||||||
|
|
||||||
- Resolution
|
- <span id="archive-resolution">Resolution</span>
|
||||||
|
|
||||||
The resolution for videos can be set via the `-r` / `--resolution` flag.
|
The resolution for videos can be set via the `-r` / `--resolution` flag.
|
||||||
|
|
||||||
|
|
@ -462,13 +454,13 @@ The `archive` command lets you download episodes with multiple audios and subtit
|
||||||
|
|
||||||
Default is `best`.
|
Default is `best`.
|
||||||
|
|
||||||
- Merge behavior
|
- <span id="archive-merge">Merge behavior</span>
|
||||||
|
|
||||||
Due to censorship, some episodes have multiple lengths for different languages.
|
Due to censorship or additional intros, some episodes have multiple lengths for different languages.
|
||||||
In the best case, when multiple audio & subtitle tracks are used, there is only one *video* track and all other languages can be stored as audio-only.
|
In the best case, when multiple audio & subtitle tracks are used, there is only one *video* track and all other languages can be stored as audio-only.
|
||||||
But, as said, this is not always the case.
|
But, as said, this is not always the case.
|
||||||
With the `-m` / `--merge` flag you can define the behaviour when an episodes' video tracks differ in length.
|
With the `-m` / `--merge` flag you can define the behaviour when an episodes' video tracks differ in length.
|
||||||
Valid options are `audio` - store one video and all other languages as audio only; `video` - store the video + audio for every language; `auto` - detect if videos differ in length: if so, behave like `video` - otherwise like `audio`.
|
Valid options are `audio` - store one video and all other languages as audio only; `video` - store the video + audio for every language; `auto` - detect if videos differ in length: if so, behave like `video` - otherwise like `audio`; `sync` - detect if videos differ in length: if so, it tries to find the offset of matching audio parts and removes the offset from the beginning, otherwise it behaves like `audio`.
|
||||||
Subtitles will always match the primary audio and video.
|
Subtitles will always match the primary audio and video.
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
|
|
@ -477,18 +469,39 @@ The `archive` command lets you download episodes with multiple audios and subtit
|
||||||
|
|
||||||
Default is `auto`.
|
Default is `auto`.
|
||||||
|
|
||||||
- Merge auto tolerance
|
- <span id="archive-merge-time-tolerance">Merge time tolerance</span>
|
||||||
|
|
||||||
Sometimes two video tracks are downloaded with `--merge` set to `auto` even if they only differ some milliseconds in length which shouldn't be noticeable to the viewer.
|
Sometimes two video tracks are downloaded with `--merge` set to `auto` even if they only differ some milliseconds in length which shouldn't be noticeable to the viewer.
|
||||||
To prevent this, you can specify a range in milliseconds with the `--merge-auto-tolerance` flag that only downloads one video if the length difference is in the given range.
|
To prevent this, you can specify a range in milliseconds with the `--merge-time-tolerance` flag that only downloads one video if the length difference is in the given range.
|
||||||
|
|
||||||
```shell
|
```shell
|
||||||
$ crunchy-cli archive -m auto --merge-auto-tolerance 100 https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx
|
$ crunchy-cli archive -m auto --merge-time-tolerance 100 https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx
|
||||||
```
|
```
|
||||||
|
|
||||||
Default are `200` milliseconds.
|
Default are `200` milliseconds.
|
||||||
|
|
||||||
- Language tagging
|
- <span id="archive-merge-sync-tolerance">Merge sync tolerance</span>
|
||||||
|
|
||||||
|
Sometimes two video tracks are downloaded with `--merge` set to `sync` because the audio fingerprinting fails to identify matching audio parts (e.g. opening).
|
||||||
|
To prevent this, you can use the `--merge-sync-tolerance` flag to specify the difference by which two fingerprints are considered equal.
|
||||||
|
|
||||||
|
```shell
|
||||||
|
$ crunchy-cli archive -m sync --merge-sync-tolerance 3 https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome
|
||||||
|
```
|
||||||
|
|
||||||
|
Default is `6`.
|
||||||
|
|
||||||
|
- <span id="archive-merge-sync-precision">Merge sync precision</span>
|
||||||
|
|
||||||
|
If you use `--merge` set to `sync` and the syncing seems to be not accurate enough or takes to long, you can use the `--sync-precision` flag to specify the amount of offset determination runs from which the final offset is calculated.
|
||||||
|
|
||||||
|
```shell
|
||||||
|
$ crunchy-cli archive -m sync --merge-sync-precision 3 https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome
|
||||||
|
```
|
||||||
|
|
||||||
|
Default is `4`.
|
||||||
|
|
||||||
|
- <span id="archive-language-tagging">Language tagging</span>
|
||||||
|
|
||||||
You can force the usage of a specific language tagging in the output file with the `--language-tagging` flag.
|
You can force the usage of a specific language tagging in the output file with the `--language-tagging` flag.
|
||||||
This might be useful as some video players doesn't recognize the language tagging Crunchyroll uses internally.
|
This might be useful as some video players doesn't recognize the language tagging Crunchyroll uses internally.
|
||||||
|
|
@ -497,7 +510,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
|
||||||
$ crunchy-cli archive --language-tagging ietf https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx
|
$ crunchy-cli archive --language-tagging ietf https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx
|
||||||
```
|
```
|
||||||
|
|
||||||
- FFmpeg Preset
|
- <span id="archive-ffmpeg-preset">FFmpeg Preset</span>
|
||||||
|
|
||||||
You can specify specific built-in presets with the `--ffmpeg-preset` flag to convert videos to a specific coding while downloading.
|
You can specify specific built-in presets with the `--ffmpeg-preset` flag to convert videos to a specific coding while downloading.
|
||||||
Multiple predefined presets how videos should be encoded (h264, h265, av1, ...) are available, you can see them with `crunchy-cli archive --help`.
|
Multiple predefined presets how videos should be encoded (h264, h265, av1, ...) are available, you can see them with `crunchy-cli archive --help`.
|
||||||
|
|
@ -507,7 +520,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
|
||||||
$ crunchy-cli archive --ffmpeg-preset av1-lossless https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome
|
$ crunchy-cli archive --ffmpeg-preset av1-lossless https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome
|
||||||
```
|
```
|
||||||
|
|
||||||
- FFmpeg threads
|
- <span id="archive-ffmpeg-threads">FFmpeg threads</span>
|
||||||
|
|
||||||
If you want to manually set how many threads FFmpeg should use, you can use the `--ffmpeg-threads` flag. This does not work with every codec/preset and is skipped entirely when specifying custom ffmpeg output arguments instead of a preset for `--ffmpeg-preset`.
|
If you want to manually set how many threads FFmpeg should use, you can use the `--ffmpeg-threads` flag. This does not work with every codec/preset and is skipped entirely when specifying custom ffmpeg output arguments instead of a preset for `--ffmpeg-preset`.
|
||||||
|
|
||||||
|
|
@ -515,7 +528,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
|
||||||
$ crunchy-cli archive --ffmpeg-threads 4 https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome
|
$ crunchy-cli archive --ffmpeg-threads 4 https://www.crunchyroll.com/watch/GRDQPM1ZY/alone-and-lonesome
|
||||||
```
|
```
|
||||||
|
|
||||||
- Default subtitle
|
- <span id="archive-default-subtitle">Default subtitle</span>
|
||||||
|
|
||||||
`--default-subtitle` Set which subtitle language is to be flagged as **default** and **forced**.
|
`--default-subtitle` Set which subtitle language is to be flagged as **default** and **forced**.
|
||||||
|
|
||||||
|
|
@ -525,7 +538,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
|
||||||
|
|
||||||
Default is none.
|
Default is none.
|
||||||
|
|
||||||
- Include fonts
|
- <span id="archive-include-fonts">Include fonts</span>
|
||||||
|
|
||||||
You can include the fonts required by subtitles directly into the output file with the `--include-fonts` flag. This will use the embedded font for subtitles instead of the system font when playing the video in a video player which supports it.
|
You can include the fonts required by subtitles directly into the output file with the `--include-fonts` flag. This will use the embedded font for subtitles instead of the system font when playing the video in a video player which supports it.
|
||||||
|
|
||||||
|
|
@ -533,7 +546,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
|
||||||
$ crunchy-cli archive --include-fonts https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx
|
$ crunchy-cli archive --include-fonts https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx
|
||||||
```
|
```
|
||||||
|
|
||||||
- Include chapters
|
- <span id="archive-include-chapters">Include chapters</span>
|
||||||
|
|
||||||
Crunchyroll sometimes provide information about skippable events like the intro or credits.
|
Crunchyroll sometimes provide information about skippable events like the intro or credits.
|
||||||
These information can be stored as chapters in the resulting video file via the `--include-chapters` flag.
|
These information can be stored as chapters in the resulting video file via the `--include-chapters` flag.
|
||||||
|
|
@ -543,7 +556,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
|
||||||
$ crunchy-cli archive --include-chapters https://www.crunchyroll.com/watch/G0DUND0K2/the-journeys-end
|
$ crunchy-cli archive --include-chapters https://www.crunchyroll.com/watch/G0DUND0K2/the-journeys-end
|
||||||
```
|
```
|
||||||
|
|
||||||
- Skip existing
|
- <span id="archive-skip-existing">Skip existing</span>
|
||||||
|
|
||||||
If you re-download a series but want to skip episodes you've already downloaded, the `--skip-existing` flag skips the already existing/downloaded files.
|
If you re-download a series but want to skip episodes you've already downloaded, the `--skip-existing` flag skips the already existing/downloaded files.
|
||||||
|
|
||||||
|
|
@ -551,7 +564,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
|
||||||
$ crunchy-cli archive --skip-existing https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx
|
$ crunchy-cli archive --skip-existing https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx
|
||||||
```
|
```
|
||||||
|
|
||||||
- Skip existing method
|
- <span id="archive-skip-existing-method">Skip existing method</span>
|
||||||
|
|
||||||
By default, already existing files are determined by their name and the download of the corresponding episode is skipped.
|
By default, already existing files are determined by their name and the download of the corresponding episode is skipped.
|
||||||
But sometimes Crunchyroll adds dubs or subs to an already existing episode and these changes aren't recognized and `--skip-existing` just skips it.
|
But sometimes Crunchyroll adds dubs or subs to an already existing episode and these changes aren't recognized and `--skip-existing` just skips it.
|
||||||
|
|
@ -561,7 +574,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
|
||||||
$ crunchy-cli archive --skip-existing-method audio --skip-existing-method video https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx
|
$ crunchy-cli archive --skip-existing-method audio --skip-existing-method video https://www.crunchyroll.com/series/GY8VEQ95Y/darling-in-the-franxx
|
||||||
```
|
```
|
||||||
|
|
||||||
- Skip specials
|
- <span id="archive-skip-specials">Skip specials</span>
|
||||||
|
|
||||||
If you doesn't want to download special episodes, use the `--skip-specials` flag to skip the download of them.
|
If you doesn't want to download special episodes, use the `--skip-specials` flag to skip the download of them.
|
||||||
|
|
||||||
|
|
@ -569,7 +582,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
|
||||||
$ crunchy-cli archive --skip-specials https://www.crunchyroll.com/series/GYZJ43JMR/that-time-i-got-reincarnated-as-a-slime[S2]
|
$ crunchy-cli archive --skip-specials https://www.crunchyroll.com/series/GYZJ43JMR/that-time-i-got-reincarnated-as-a-slime[S2]
|
||||||
```
|
```
|
||||||
|
|
||||||
- Yes
|
- <span id="archive-yes">Yes</span>
|
||||||
|
|
||||||
Sometimes different seasons have the same season number (e.g. Sword Art Online Alicization and Alicization War of Underworld are both marked as season 3), in such cases an interactive prompt is shown which needs user further user input to decide which season to download.
|
Sometimes different seasons have the same season number (e.g. Sword Art Online Alicization and Alicization War of Underworld are both marked as season 3), in such cases an interactive prompt is shown which needs user further user input to decide which season to download.
|
||||||
The `--yes` flag suppresses this interactive prompt and just downloads all seasons.
|
The `--yes` flag suppresses this interactive prompt and just downloads all seasons.
|
||||||
|
|
@ -580,7 +593,7 @@ The `archive` command lets you download episodes with multiple audios and subtit
|
||||||
|
|
||||||
If you've passed the `-q` / `--quiet` [global flag](#global-settings), this flag is automatically set.
|
If you've passed the `-q` / `--quiet` [global flag](#global-settings), this flag is automatically set.
|
||||||
|
|
||||||
- Threads
|
- <span id="archive-threads">Threads</span>
|
||||||
|
|
||||||
To increase the download speed, video segments are downloaded simultaneously by creating multiple threads.
|
To increase the download speed, video segments are downloaded simultaneously by creating multiple threads.
|
||||||
If you want to manually specify how many threads to use when downloading, do this with the `-t` / `--threads` flag.
|
If you want to manually specify how many threads to use when downloading, do this with the `-t` / `--threads` flag.
|
||||||
|
|
@ -614,7 +627,7 @@ _Using this command with the `--anonymous` flag or a non-premium account may ret
|
||||||
|
|
||||||
**Options**
|
**Options**
|
||||||
|
|
||||||
- Audio
|
- <span id="search-audio">Audio</span>
|
||||||
|
|
||||||
Set the audio language to search via the `--audio` flag. Can be used multiple times.
|
Set the audio language to search via the `--audio` flag. Can be used multiple times.
|
||||||
|
|
||||||
|
|
@ -624,7 +637,7 @@ _Using this command with the `--anonymous` flag or a non-premium account may ret
|
||||||
|
|
||||||
Default is your system locale.
|
Default is your system locale.
|
||||||
|
|
||||||
- Result limit
|
- <span id="search-result-limit">Result limit</span>
|
||||||
|
|
||||||
If your input is a search term instead of an url, you have multiple options to control which results to process.
|
If your input is a search term instead of an url, you have multiple options to control which results to process.
|
||||||
The `--search-top-results-limit` flag sets the limit of top search results to process.
|
The `--search-top-results-limit` flag sets the limit of top search results to process.
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
[package]
|
[package]
|
||||||
name = "crunchy-cli-core"
|
name = "crunchy-cli-core"
|
||||||
authors = ["Crunchy Labs Maintainers"]
|
authors = ["Crunchy Labs Maintainers"]
|
||||||
version = "3.3.0"
|
version = "3.6.7"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
|
|
||||||
|
|
@ -16,27 +16,30 @@ anyhow = "1.0"
|
||||||
async-speed-limit = "0.4"
|
async-speed-limit = "0.4"
|
||||||
clap = { version = "4.5", features = ["derive", "string"] }
|
clap = { version = "4.5", features = ["derive", "string"] }
|
||||||
chrono = "0.4"
|
chrono = "0.4"
|
||||||
crunchyroll-rs = { version = "0.8.5", features = ["dash-stream", "experimental-stabilizations", "tower"] }
|
crunchyroll-rs = { version = "0.11.4", features = ["experimental-stabilizations", "tower"] }
|
||||||
ctrlc = "3.4"
|
ctrlc = "3.4"
|
||||||
dialoguer = { version = "0.11", default-features = false }
|
dialoguer = { version = "0.11", default-features = false }
|
||||||
dirs = "5.0"
|
dirs = "5.0"
|
||||||
derive_setters = "0.1"
|
derive_setters = "0.1"
|
||||||
futures-util = { version = "0.3", features = ["io"] }
|
futures-util = { version = "0.3", features = ["io"] }
|
||||||
fs2 = "0.4"
|
fs2 = "0.4"
|
||||||
http = "0.2"
|
http = "1.1"
|
||||||
indicatif = "0.17"
|
indicatif = "0.17"
|
||||||
lazy_static = "1.4"
|
lazy_static = "1.4"
|
||||||
log = { version = "0.4", features = ["std"] }
|
log = { version = "0.4", features = ["std"] }
|
||||||
num_cpus = "1.16"
|
num_cpus = "1.16"
|
||||||
regex = "1.10"
|
regex = "1.10"
|
||||||
reqwest = { version = "0.11", default-features = false, features = ["socks", "stream"] }
|
reqwest = { version = "0.12", features = ["socks", "stream"] }
|
||||||
|
rsubs-lib = "~0.3.2"
|
||||||
|
rusty-chromaprint = "0.2"
|
||||||
serde = "1.0"
|
serde = "1.0"
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
serde_plain = "1.0"
|
serde_plain = "1.0"
|
||||||
shlex = "1.3"
|
shlex = "1.3"
|
||||||
sys-locale = "0.3"
|
sys-locale = "0.3"
|
||||||
tempfile = "3.10"
|
tempfile = "3.10"
|
||||||
tokio = { version = "1.36", features = ["io-util", "macros", "net", "rt-multi-thread", "time"] }
|
time = "0.3"
|
||||||
|
tokio = { version = "1.38", features = ["io-util", "macros", "net", "rt-multi-thread", "time"] }
|
||||||
tokio-util = "0.7"
|
tokio-util = "0.7"
|
||||||
tower-service = "0.3"
|
tower-service = "0.3"
|
||||||
rustls-native-certs = { version = "0.7", optional = true }
|
rustls-native-certs = { version = "0.7", optional = true }
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,8 @@
|
||||||
fn main() -> std::io::Result<()> {
|
fn main() -> std::io::Result<()> {
|
||||||
println!(
|
println!(
|
||||||
"cargo:rustc-env=GIT_HASH={}",
|
"cargo:rustc-env=GIT_HASH={}",
|
||||||
get_short_commit_hash()?.unwrap_or_default()
|
std::env::var("CRUNCHY_CLI_GIT_HASH")
|
||||||
|
.or::<std::io::Error>(Ok(get_short_commit_hash()?.unwrap_or_default()))?
|
||||||
);
|
);
|
||||||
println!(
|
println!(
|
||||||
"cargo:rustc-env=BUILD_DATE={}",
|
"cargo:rustc-env=BUILD_DATE={}",
|
||||||
|
|
|
||||||
|
|
@ -1,16 +1,15 @@
|
||||||
use crate::archive::filter::ArchiveFilter;
|
|
||||||
use crate::utils::context::Context;
|
use crate::utils::context::Context;
|
||||||
use crate::utils::download::{
|
use crate::utils::download::{
|
||||||
DownloadBuilder, DownloadFormat, DownloadFormatMetadata, MergeBehavior,
|
DownloadBuilder, DownloadFormat, DownloadFormatMetadata, MergeBehavior,
|
||||||
};
|
};
|
||||||
use crate::utils::ffmpeg::FFmpegPreset;
|
use crate::utils::ffmpeg::FFmpegPreset;
|
||||||
use crate::utils::filter::Filter;
|
use crate::utils::filter::{Filter, FilterMediaScope};
|
||||||
use crate::utils::format::{Format, SingleFormat};
|
use crate::utils::format::{Format, SingleFormat};
|
||||||
use crate::utils::locale::{all_locale_in_locales, resolve_locales, LanguageTagging};
|
use crate::utils::locale::{all_locale_in_locales, resolve_locales, LanguageTagging};
|
||||||
use crate::utils::log::progress;
|
use crate::utils::log::progress;
|
||||||
use crate::utils::os::{free_file, has_ffmpeg, is_special_file};
|
use crate::utils::os::{free_file, has_ffmpeg, is_special_file};
|
||||||
use crate::utils::parse::parse_url;
|
use crate::utils::parse::parse_url;
|
||||||
use crate::utils::video::variant_data_from_stream;
|
use crate::utils::video::stream_data_from_stream;
|
||||||
use crate::Execute;
|
use crate::Execute;
|
||||||
use anyhow::bail;
|
use anyhow::bail;
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
|
|
@ -90,23 +89,33 @@ pub struct Archive {
|
||||||
pub(crate) resolution: Resolution,
|
pub(crate) resolution: Resolution,
|
||||||
|
|
||||||
#[arg(
|
#[arg(
|
||||||
help = "Sets the behavior of the stream merging. Valid behaviors are 'auto', 'audio' and 'video'"
|
help = "Sets the behavior of the stream merging. Valid behaviors are 'auto', 'sync', 'audio' and 'video'"
|
||||||
)]
|
)]
|
||||||
#[arg(
|
#[arg(
|
||||||
long_help = "Because of local restrictions (or other reasons) some episodes with different languages does not have the same length (e.g. when some scenes were cut out). \
|
long_help = "Because of local restrictions (or other reasons) some episodes with different languages does not have the same length (e.g. when some scenes were cut out). \
|
||||||
With this flag you can set the behavior when handling multiple language.
|
With this flag you can set the behavior when handling multiple language.
|
||||||
Valid options are 'audio' (stores one video and all other languages as audio only), 'video' (stores the video + audio for every language) and 'auto' (detects if videos differ in length: if so, behave like 'video' else like 'audio')"
|
Valid options are 'audio' (stores one video and all other languages as audio only), 'video' (stores the video + audio for every language), 'auto' (detects if videos differ in length: if so, behave like 'video' else like 'audio') and 'sync' (detects if videos differ in length: if so, tries to find the offset of matching audio parts and removes it from the beginning, otherwise it behaves like 'audio')"
|
||||||
)]
|
)]
|
||||||
#[arg(short, long, default_value = "auto")]
|
#[arg(short, long, default_value = "auto")]
|
||||||
#[arg(value_parser = MergeBehavior::parse)]
|
#[arg(value_parser = MergeBehavior::parse)]
|
||||||
pub(crate) merge: MergeBehavior,
|
pub(crate) merge: MergeBehavior,
|
||||||
#[arg(
|
#[arg(
|
||||||
help = "If the merge behavior is 'auto', only download multiple video tracks if their length difference is higher than the given milliseconds"
|
help = "If the merge behavior is 'auto' or 'sync', consider videos to be of equal lengths if the difference in length is smaller than the specified milliseconds"
|
||||||
)]
|
)]
|
||||||
#[arg(long, default_value_t = 200)]
|
#[arg(long, default_value_t = 200)]
|
||||||
pub(crate) merge_auto_tolerance: u32,
|
pub(crate) merge_time_tolerance: u32,
|
||||||
|
#[arg(
|
||||||
|
help = "If the merge behavior is 'sync', specify the difference by which two fingerprints are considered equal, higher values can help when the algorithm fails"
|
||||||
|
)]
|
||||||
|
#[arg(long, default_value_t = 6)]
|
||||||
|
pub(crate) merge_sync_tolerance: u32,
|
||||||
|
#[arg(
|
||||||
|
help = "If the merge behavior is 'sync', specify the amount of offset determination runs from which the final offset is calculated, higher values will increase the time required but lead to more precise offsets"
|
||||||
|
)]
|
||||||
|
#[arg(long, default_value_t = 4)]
|
||||||
|
pub(crate) merge_sync_precision: u32,
|
||||||
|
|
||||||
#[arg(
|
#[arg(
|
||||||
long,
|
|
||||||
help = "Specified which language tagging the audio and subtitle tracks and language specific format options should have. \
|
help = "Specified which language tagging the audio and subtitle tracks and language specific format options should have. \
|
||||||
Valid options are: 'default' (how Crunchyroll uses it internally), 'ietf' (according to the IETF standard)"
|
Valid options are: 'default' (how Crunchyroll uses it internally), 'ietf' (according to the IETF standard)"
|
||||||
)]
|
)]
|
||||||
|
|
@ -114,6 +123,7 @@ pub struct Archive {
|
||||||
long_help = "Specified which language tagging the audio and subtitle tracks and language specific format options should have. \
|
long_help = "Specified which language tagging the audio and subtitle tracks and language specific format options should have. \
|
||||||
Valid options are: 'default' (how Crunchyroll uses it internally), 'ietf' (according to the IETF standard; you might run in issues as there are multiple locales which resolve to the same IETF language code, e.g. 'es-LA' and 'es-ES' are both resolving to 'es')"
|
Valid options are: 'default' (how Crunchyroll uses it internally), 'ietf' (according to the IETF standard; you might run in issues as there are multiple locales which resolve to the same IETF language code, e.g. 'es-LA' and 'es-ES' are both resolving to 'es')"
|
||||||
)]
|
)]
|
||||||
|
#[arg(long)]
|
||||||
#[arg(value_parser = LanguageTagging::parse)]
|
#[arg(value_parser = LanguageTagging::parse)]
|
||||||
pub(crate) language_tagging: Option<LanguageTagging>,
|
pub(crate) language_tagging: Option<LanguageTagging>,
|
||||||
|
|
||||||
|
|
@ -216,17 +226,15 @@ impl Execute for Archive {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if self.include_chapters && !matches!(self.merge, MergeBehavior::Audio) {
|
if self.include_chapters
|
||||||
bail!("`--include-chapters` can only be used if `--merge` is set to 'audio'")
|
&& !matches!(self.merge, MergeBehavior::Sync)
|
||||||
|
&& !matches!(self.merge, MergeBehavior::Audio)
|
||||||
|
{
|
||||||
|
bail!("`--include-chapters` can only be used if `--merge` is set to 'audio' or 'sync'")
|
||||||
}
|
}
|
||||||
|
|
||||||
if self.output.contains("{resolution}")
|
if !self.skip_existing_method.is_empty() && !self.skip_existing {
|
||||||
|| self
|
warn!("`--skip-existing-method` has no effect if `--skip-existing` is not set")
|
||||||
.output_specials
|
|
||||||
.as_ref()
|
|
||||||
.map_or(false, |os| os.contains("{resolution}"))
|
|
||||||
{
|
|
||||||
warn!("The '{{resolution}}' format option is deprecated and will be removed in a future version. Please use '{{width}}' and '{{height}}' instead")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self.audio = all_locale_in_locales(self.audio.clone());
|
self.audio = all_locale_in_locales(self.audio.clone());
|
||||||
|
|
@ -256,6 +264,10 @@ impl Execute for Archive {
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn execute(self, ctx: Context) -> Result<()> {
|
async fn execute(self, ctx: Context) -> Result<()> {
|
||||||
|
if !ctx.crunchy.premium().await {
|
||||||
|
warn!("You may not be able to download all requested videos when logging in anonymously or using a non-premium account")
|
||||||
|
}
|
||||||
|
|
||||||
let mut parsed_urls = vec![];
|
let mut parsed_urls = vec![];
|
||||||
|
|
||||||
for (i, url) in self.urls.clone().into_iter().enumerate() {
|
for (i, url) in self.urls.clone().into_iter().enumerate() {
|
||||||
|
|
@ -271,8 +283,53 @@ impl Execute for Archive {
|
||||||
|
|
||||||
for (i, (media_collection, url_filter)) in parsed_urls.into_iter().enumerate() {
|
for (i, (media_collection, url_filter)) in parsed_urls.into_iter().enumerate() {
|
||||||
let progress_handler = progress!("Fetching series details");
|
let progress_handler = progress!("Fetching series details");
|
||||||
let single_format_collection =
|
let single_format_collection = Filter::new(
|
||||||
ArchiveFilter::new(url_filter, self.clone(), !self.yes, self.skip_specials)
|
url_filter,
|
||||||
|
self.audio.clone(),
|
||||||
|
self.subtitle.clone(),
|
||||||
|
|scope, locales| {
|
||||||
|
let audios = locales.into_iter().map(|l| l.to_string()).collect::<Vec<String>>().join(", ");
|
||||||
|
match scope {
|
||||||
|
FilterMediaScope::Series(series) => warn!("Series {} is not available with {} audio", series.title, audios),
|
||||||
|
FilterMediaScope::Season(season) => warn!("Season {} is not available with {} audio", season.season_number, audios),
|
||||||
|
FilterMediaScope::Episode(episodes) => {
|
||||||
|
if episodes.len() == 1 {
|
||||||
|
warn!("Episode {} is not available with {} audio", episodes[0].sequence_number, audios)
|
||||||
|
} else if episodes.len() == 2 {
|
||||||
|
warn!("Season {} is only available with {} audio from episode {} to {}", episodes[0].season_number, audios, episodes[0].sequence_number, episodes[1].sequence_number)
|
||||||
|
} else {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(true)
|
||||||
|
},
|
||||||
|
|scope, locales| {
|
||||||
|
let subtitles = locales.into_iter().map(|l| l.to_string()).collect::<Vec<String>>().join(", ");
|
||||||
|
match scope {
|
||||||
|
FilterMediaScope::Series(series) => warn!("Series {} is not available with {} subtitles", series.title, subtitles),
|
||||||
|
FilterMediaScope::Season(season) => warn!("Season {} is not available with {} subtitles", season.season_number, subtitles),
|
||||||
|
FilterMediaScope::Episode(episodes) => {
|
||||||
|
if episodes.len() == 1 {
|
||||||
|
warn!("Episode {} of season {} is not available with {} subtitles", episodes[0].sequence_number, episodes[0].season_title, subtitles)
|
||||||
|
} else if episodes.len() == 2 {
|
||||||
|
warn!("Season {} of season {} is only available with {} subtitles from episode {} to {}", episodes[0].season_number, episodes[0].season_title, subtitles, episodes[0].sequence_number, episodes[1].sequence_number)
|
||||||
|
} else {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(true)
|
||||||
|
},
|
||||||
|
|season| {
|
||||||
|
warn!("Skipping premium episodes in season {season}");
|
||||||
|
Ok(())
|
||||||
|
},
|
||||||
|
Format::has_relative_fmt(&self.output),
|
||||||
|
!self.yes,
|
||||||
|
self.skip_specials,
|
||||||
|
ctx.crunchy.premium().await,
|
||||||
|
)
|
||||||
.visit(media_collection)
|
.visit(media_collection)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
|
|
@ -294,6 +351,14 @@ impl Execute for Archive {
|
||||||
.audio_sort(Some(self.audio.clone()))
|
.audio_sort(Some(self.audio.clone()))
|
||||||
.subtitle_sort(Some(self.subtitle.clone()))
|
.subtitle_sort(Some(self.subtitle.clone()))
|
||||||
.no_closed_caption(self.no_closed_caption)
|
.no_closed_caption(self.no_closed_caption)
|
||||||
|
.merge_sync_tolerance(match self.merge {
|
||||||
|
MergeBehavior::Sync => Some(self.merge_sync_tolerance),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.merge_sync_precision(match self.merge {
|
||||||
|
MergeBehavior::Sync => Some(self.merge_sync_precision),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
.threads(self.threads)
|
.threads(self.threads)
|
||||||
.audio_locale_output_map(
|
.audio_locale_output_map(
|
||||||
zip(self.audio.clone(), self.output_audio_locales.clone()).collect(),
|
zip(self.audio.clone(), self.output_audio_locales.clone()).collect(),
|
||||||
|
|
@ -371,7 +436,7 @@ impl Execute for Archive {
|
||||||
|| (method_subtitle && subtitle_differ)
|
|| (method_subtitle && subtitle_differ)
|
||||||
{
|
{
|
||||||
skip = false;
|
skip = false;
|
||||||
path = formatted_path.clone()
|
path.clone_from(&formatted_path)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -450,7 +515,7 @@ async fn get_format(
|
||||||
for single_format in single_formats {
|
for single_format in single_formats {
|
||||||
let stream = single_format.stream().await?;
|
let stream = single_format.stream().await?;
|
||||||
let Some((video, audio, _)) =
|
let Some((video, audio, _)) =
|
||||||
variant_data_from_stream(&stream, &archive.resolution, None).await?
|
stream_data_from_stream(&stream, &archive.resolution, None).await?
|
||||||
else {
|
else {
|
||||||
if single_format.is_episode() {
|
if single_format.is_episode() {
|
||||||
bail!(
|
bail!(
|
||||||
|
|
@ -475,29 +540,28 @@ async fn get_format(
|
||||||
.subtitle
|
.subtitle
|
||||||
.iter()
|
.iter()
|
||||||
.flat_map(|s| {
|
.flat_map(|s| {
|
||||||
let subtitles = stream
|
let mut subtitles = vec![];
|
||||||
.subtitles
|
if let Some(caption) = stream.captions.get(s) {
|
||||||
.get(s)
|
subtitles.push((caption.clone(), true))
|
||||||
.cloned()
|
}
|
||||||
// the subtitle is probably not cc if the audio is japanese or more than one
|
if let Some(subtitle) = stream.subtitles.get(s) {
|
||||||
// subtitle exists for this stream
|
// the subtitle is probably cc if the audio is not japanese or only one subtitle
|
||||||
.map(|l| {
|
// exists for this stream
|
||||||
(
|
let cc = single_format.audio != Locale::ja_JP && stream.subtitles.len() == 1;
|
||||||
l,
|
// only include the subtitles if no cc subtitle is already present or if it's
|
||||||
single_format.audio == Locale::ja_JP || stream.subtitles.len() > 1,
|
// not cc
|
||||||
)
|
if subtitles.is_empty() || !cc {
|
||||||
});
|
subtitles.push((subtitle.clone(), cc))
|
||||||
let cc = stream.closed_captions.get(s).cloned().map(|l| (l, false));
|
}
|
||||||
|
}
|
||||||
subtitles
|
subtitles
|
||||||
.into_iter()
|
|
||||||
.chain(cc.into_iter())
|
|
||||||
.collect::<Vec<(Subtitle, bool)>>()
|
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
format_pairs.push((single_format, video.clone(), audio, subtitles.clone()));
|
format_pairs.push((single_format, video.clone(), audio, subtitles.clone()));
|
||||||
single_format_to_format_pairs.push((single_format.clone(), video, subtitles))
|
single_format_to_format_pairs.push((single_format.clone(), video, subtitles));
|
||||||
|
|
||||||
|
stream.invalidate().await?
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut download_formats = vec![];
|
let mut download_formats = vec![];
|
||||||
|
|
@ -529,10 +593,14 @@ async fn get_format(
|
||||||
.flat_map(|(_, _, _, subtitles)| subtitles.clone())
|
.flat_map(|(_, _, _, subtitles)| subtitles.clone())
|
||||||
.collect(),
|
.collect(),
|
||||||
metadata: DownloadFormatMetadata {
|
metadata: DownloadFormatMetadata {
|
||||||
skip_events: format_pairs.first().unwrap().0.skip_events().await?,
|
skip_events: if archive.include_chapters {
|
||||||
|
format_pairs.first().unwrap().0.skip_events().await?
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
},
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
MergeBehavior::Auto => {
|
MergeBehavior::Auto | MergeBehavior::Sync => {
|
||||||
let mut d_formats: Vec<(Duration, DownloadFormat)> = vec![];
|
let mut d_formats: Vec<(Duration, DownloadFormat)> = vec![];
|
||||||
|
|
||||||
for (single_format, video, audio, subtitles) in format_pairs {
|
for (single_format, video, audio, subtitles) in format_pairs {
|
||||||
|
|
@ -549,7 +617,7 @@ async fn get_format(
|
||||||
.sub(single_format.duration)
|
.sub(single_format.duration)
|
||||||
.abs()
|
.abs()
|
||||||
.num_milliseconds()
|
.num_milliseconds()
|
||||||
< archive.merge_auto_tolerance.into() =>
|
< archive.merge_time_tolerance.into() =>
|
||||||
{
|
{
|
||||||
// If less than `audio_error` apart, use same audio.
|
// If less than `audio_error` apart, use same audio.
|
||||||
closest_format
|
closest_format
|
||||||
|
|
@ -565,7 +633,13 @@ async fn get_format(
|
||||||
video: (video, single_format.audio.clone()),
|
video: (video, single_format.audio.clone()),
|
||||||
audios: vec![(audio, single_format.audio.clone())],
|
audios: vec![(audio, single_format.audio.clone())],
|
||||||
subtitles,
|
subtitles,
|
||||||
metadata: DownloadFormatMetadata { skip_events: None },
|
metadata: DownloadFormatMetadata {
|
||||||
|
skip_events: if archive.include_chapters {
|
||||||
|
single_format.skip_events().await?
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
},
|
||||||
|
},
|
||||||
},
|
},
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,437 +0,0 @@
|
||||||
use crate::archive::command::Archive;
|
|
||||||
use crate::utils::filter::{real_dedup_vec, Filter};
|
|
||||||
use crate::utils::format::{Format, SingleFormat, SingleFormatCollection};
|
|
||||||
use crate::utils::interactive_select::{check_for_duplicated_seasons, get_duplicated_seasons};
|
|
||||||
use crate::utils::parse::{fract, UrlFilter};
|
|
||||||
use anyhow::Result;
|
|
||||||
use crunchyroll_rs::{Concert, Episode, Locale, Movie, MovieListing, MusicVideo, Season, Series};
|
|
||||||
use log::{info, warn};
|
|
||||||
use std::collections::{BTreeMap, HashMap};
|
|
||||||
|
|
||||||
enum Visited {
|
|
||||||
Series,
|
|
||||||
Season,
|
|
||||||
None,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) struct ArchiveFilter {
|
|
||||||
url_filter: UrlFilter,
|
|
||||||
archive: Archive,
|
|
||||||
interactive_input: bool,
|
|
||||||
skip_special: bool,
|
|
||||||
season_episodes: HashMap<String, Vec<Episode>>,
|
|
||||||
season_subtitles_missing: Vec<u32>,
|
|
||||||
season_sorting: Vec<String>,
|
|
||||||
visited: Visited,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ArchiveFilter {
|
|
||||||
pub(crate) fn new(
|
|
||||||
url_filter: UrlFilter,
|
|
||||||
archive: Archive,
|
|
||||||
interactive_input: bool,
|
|
||||||
skip_special: bool,
|
|
||||||
) -> Self {
|
|
||||||
Self {
|
|
||||||
url_filter,
|
|
||||||
archive,
|
|
||||||
interactive_input,
|
|
||||||
skip_special,
|
|
||||||
season_episodes: HashMap::new(),
|
|
||||||
season_subtitles_missing: vec![],
|
|
||||||
season_sorting: vec![],
|
|
||||||
visited: Visited::None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Filter for ArchiveFilter {
|
|
||||||
type T = Vec<SingleFormat>;
|
|
||||||
type Output = SingleFormatCollection;
|
|
||||||
|
|
||||||
async fn visit_series(&mut self, series: Series) -> Result<Vec<Season>> {
|
|
||||||
// `series.audio_locales` isn't always populated b/c of crunchyrolls api. so check if the
|
|
||||||
// audio is matching only if the field is populated
|
|
||||||
if !series.audio_locales.is_empty() {
|
|
||||||
let missing_audio = missing_locales(&series.audio_locales, &self.archive.audio);
|
|
||||||
if !missing_audio.is_empty() {
|
|
||||||
warn!(
|
|
||||||
"Series {} is not available with {} audio",
|
|
||||||
series.title,
|
|
||||||
missing_audio
|
|
||||||
.into_iter()
|
|
||||||
.map(|l| l.to_string())
|
|
||||||
.collect::<Vec<String>>()
|
|
||||||
.join(", ")
|
|
||||||
)
|
|
||||||
}
|
|
||||||
let missing_subtitle =
|
|
||||||
missing_locales(&series.subtitle_locales, &self.archive.subtitle);
|
|
||||||
if !missing_subtitle.is_empty() {
|
|
||||||
warn!(
|
|
||||||
"Series {} is not available with {} subtitles",
|
|
||||||
series.title,
|
|
||||||
missing_subtitle
|
|
||||||
.into_iter()
|
|
||||||
.map(|l| l.to_string())
|
|
||||||
.collect::<Vec<String>>()
|
|
||||||
.join(", ")
|
|
||||||
)
|
|
||||||
}
|
|
||||||
self.visited = Visited::Series
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut seasons = series.seasons().await?;
|
|
||||||
let mut remove_ids = vec![];
|
|
||||||
for season in seasons.iter_mut() {
|
|
||||||
if !self.url_filter.is_season_valid(season.season_number)
|
|
||||||
|| (!season
|
|
||||||
.audio_locales
|
|
||||||
.iter()
|
|
||||||
.any(|l| self.archive.audio.contains(l))
|
|
||||||
&& !season
|
|
||||||
.available_versions()
|
|
||||||
.await?
|
|
||||||
.iter()
|
|
||||||
.any(|l| self.archive.audio.contains(l)))
|
|
||||||
{
|
|
||||||
remove_ids.push(season.id.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
seasons.retain(|s| !remove_ids.contains(&s.id));
|
|
||||||
|
|
||||||
let duplicated_seasons = get_duplicated_seasons(&seasons);
|
|
||||||
if !duplicated_seasons.is_empty() {
|
|
||||||
if self.interactive_input {
|
|
||||||
check_for_duplicated_seasons(&mut seasons);
|
|
||||||
} else {
|
|
||||||
info!(
|
|
||||||
"Found duplicated seasons: {}",
|
|
||||||
duplicated_seasons
|
|
||||||
.iter()
|
|
||||||
.map(|d| d.to_string())
|
|
||||||
.collect::<Vec<String>>()
|
|
||||||
.join(", ")
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(seasons)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn visit_season(&mut self, mut season: Season) -> Result<Vec<Episode>> {
|
|
||||||
if !self.url_filter.is_season_valid(season.season_number) {
|
|
||||||
return Ok(vec![]);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut seasons = season.version(self.archive.audio.clone()).await?;
|
|
||||||
if self
|
|
||||||
.archive
|
|
||||||
.audio
|
|
||||||
.iter()
|
|
||||||
.any(|l| season.audio_locales.contains(l))
|
|
||||||
{
|
|
||||||
seasons.insert(0, season.clone());
|
|
||||||
}
|
|
||||||
|
|
||||||
if !matches!(self.visited, Visited::Series) {
|
|
||||||
let mut audio_locales: Vec<Locale> = seasons
|
|
||||||
.iter()
|
|
||||||
.flat_map(|s| s.audio_locales.clone())
|
|
||||||
.collect();
|
|
||||||
real_dedup_vec(&mut audio_locales);
|
|
||||||
let missing_audio = missing_locales(&audio_locales, &self.archive.audio);
|
|
||||||
if !missing_audio.is_empty() {
|
|
||||||
warn!(
|
|
||||||
"Season {} is not available with {} audio",
|
|
||||||
season.season_number,
|
|
||||||
missing_audio
|
|
||||||
.into_iter()
|
|
||||||
.map(|l| l.to_string())
|
|
||||||
.collect::<Vec<String>>()
|
|
||||||
.join(", ")
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
let subtitle_locales: Vec<Locale> = seasons
|
|
||||||
.iter()
|
|
||||||
.flat_map(|s| s.subtitle_locales.clone())
|
|
||||||
.collect();
|
|
||||||
let missing_subtitle = missing_locales(&subtitle_locales, &self.archive.subtitle);
|
|
||||||
if !missing_subtitle.is_empty() {
|
|
||||||
warn!(
|
|
||||||
"Season {} is not available with {} subtitles",
|
|
||||||
season.season_number,
|
|
||||||
missing_subtitle
|
|
||||||
.into_iter()
|
|
||||||
.map(|l| l.to_string())
|
|
||||||
.collect::<Vec<String>>()
|
|
||||||
.join(", ")
|
|
||||||
)
|
|
||||||
}
|
|
||||||
self.visited = Visited::Season
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut episodes = vec![];
|
|
||||||
for season in seasons {
|
|
||||||
self.season_sorting.push(season.id.clone());
|
|
||||||
let season_locale = if season.audio_locales.len() < 2 {
|
|
||||||
Some(
|
|
||||||
season
|
|
||||||
.audio_locales
|
|
||||||
.first()
|
|
||||||
.cloned()
|
|
||||||
.unwrap_or(Locale::ja_JP),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
let mut eps = season.episodes().await?;
|
|
||||||
let before_len = eps.len();
|
|
||||||
|
|
||||||
for mut ep in eps.clone() {
|
|
||||||
if let Some(l) = &season_locale {
|
|
||||||
if &ep.audio_locale == l {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
eps.remove(eps.iter().position(|p| p.id == ep.id).unwrap());
|
|
||||||
} else {
|
|
||||||
let mut requested_locales = self.archive.audio.clone();
|
|
||||||
if let Some(idx) = requested_locales.iter().position(|p| p == &ep.audio_locale)
|
|
||||||
{
|
|
||||||
requested_locales.remove(idx);
|
|
||||||
} else {
|
|
||||||
eps.remove(eps.iter().position(|p| p.id == ep.id).unwrap());
|
|
||||||
}
|
|
||||||
eps.extend(ep.version(self.archive.audio.clone()).await?);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if eps.len() < before_len {
|
|
||||||
if eps.is_empty() {
|
|
||||||
if matches!(self.visited, Visited::Series) {
|
|
||||||
warn!(
|
|
||||||
"Season {} is not available with {} audio",
|
|
||||||
season.season_number,
|
|
||||||
season_locale.unwrap_or(Locale::ja_JP)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
let last_episode = eps.last().unwrap();
|
|
||||||
warn!(
|
|
||||||
"Season {} is only available with {} audio until episode {} ({})",
|
|
||||||
season.season_number,
|
|
||||||
season_locale.unwrap_or(Locale::ja_JP),
|
|
||||||
last_episode.sequence_number,
|
|
||||||
last_episode.title
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
episodes.extend(eps)
|
|
||||||
}
|
|
||||||
|
|
||||||
if Format::has_relative_fmt(&self.archive.output) {
|
|
||||||
for episode in episodes.iter() {
|
|
||||||
self.season_episodes
|
|
||||||
.entry(episode.season_id.clone())
|
|
||||||
.or_default()
|
|
||||||
.push(episode.clone())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(episodes)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn visit_episode(&mut self, mut episode: Episode) -> Result<Option<Self::T>> {
|
|
||||||
if !self
|
|
||||||
.url_filter
|
|
||||||
.is_episode_valid(episode.sequence_number, episode.season_number)
|
|
||||||
{
|
|
||||||
return Ok(None);
|
|
||||||
}
|
|
||||||
|
|
||||||
// skip the episode if it's a special
|
|
||||||
if self.skip_special
|
|
||||||
&& (episode.sequence_number == 0.0 || episode.sequence_number.fract() != 0.0)
|
|
||||||
{
|
|
||||||
return Ok(None);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut episodes = vec![];
|
|
||||||
if !matches!(self.visited, Visited::Series) && !matches!(self.visited, Visited::Season) {
|
|
||||||
if self.archive.audio.contains(&episode.audio_locale) {
|
|
||||||
episodes.push((episode.clone(), episode.subtitle_locales.clone()))
|
|
||||||
}
|
|
||||||
episodes.extend(
|
|
||||||
episode
|
|
||||||
.version(self.archive.audio.clone())
|
|
||||||
.await?
|
|
||||||
.into_iter()
|
|
||||||
.map(|e| (e.clone(), e.subtitle_locales.clone())),
|
|
||||||
);
|
|
||||||
let audio_locales: Vec<Locale> = episodes
|
|
||||||
.iter()
|
|
||||||
.map(|(e, _)| e.audio_locale.clone())
|
|
||||||
.collect();
|
|
||||||
let missing_audio = missing_locales(&audio_locales, &self.archive.audio);
|
|
||||||
if !missing_audio.is_empty() {
|
|
||||||
warn!(
|
|
||||||
"Episode {} is not available with {} audio",
|
|
||||||
episode.sequence_number,
|
|
||||||
missing_audio
|
|
||||||
.into_iter()
|
|
||||||
.map(|l| l.to_string())
|
|
||||||
.collect::<Vec<String>>()
|
|
||||||
.join(", ")
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut subtitle_locales: Vec<Locale> =
|
|
||||||
episodes.iter().flat_map(|(_, s)| s.clone()).collect();
|
|
||||||
real_dedup_vec(&mut subtitle_locales);
|
|
||||||
let missing_subtitles = missing_locales(&subtitle_locales, &self.archive.subtitle);
|
|
||||||
if !missing_subtitles.is_empty()
|
|
||||||
&& !self
|
|
||||||
.season_subtitles_missing
|
|
||||||
.contains(&episode.season_number)
|
|
||||||
{
|
|
||||||
warn!(
|
|
||||||
"Episode {} is not available with {} subtitles",
|
|
||||||
episode.sequence_number,
|
|
||||||
missing_subtitles
|
|
||||||
.into_iter()
|
|
||||||
.map(|l| l.to_string())
|
|
||||||
.collect::<Vec<String>>()
|
|
||||||
.join(", ")
|
|
||||||
);
|
|
||||||
self.season_subtitles_missing.push(episode.season_number)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
episodes.push((episode.clone(), episode.subtitle_locales.clone()))
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut relative_episode_number = None;
|
|
||||||
let mut relative_sequence_number = None;
|
|
||||||
// get the relative episode number. only done if the output string has the pattern to include
|
|
||||||
// the relative episode number as this requires some extra fetching
|
|
||||||
if Format::has_relative_fmt(&self.archive.output) {
|
|
||||||
let season_eps = match self.season_episodes.get(&episode.season_id) {
|
|
||||||
Some(eps) => eps,
|
|
||||||
None => {
|
|
||||||
self.season_episodes.insert(
|
|
||||||
episode.season_id.clone(),
|
|
||||||
episode.season().await?.episodes().await?,
|
|
||||||
);
|
|
||||||
self.season_episodes.get(&episode.season_id).unwrap()
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let mut non_integer_sequence_number_count = 0;
|
|
||||||
for (i, ep) in season_eps.iter().enumerate() {
|
|
||||||
if ep.sequence_number.fract() != 0.0 || ep.sequence_number == 0.0 {
|
|
||||||
non_integer_sequence_number_count += 1;
|
|
||||||
}
|
|
||||||
if ep.id == episode.id {
|
|
||||||
relative_episode_number = Some(i + 1);
|
|
||||||
relative_sequence_number = Some(
|
|
||||||
(i + 1 - non_integer_sequence_number_count) as f32
|
|
||||||
+ fract(ep.sequence_number),
|
|
||||||
);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if relative_episode_number.is_none() || relative_sequence_number.is_none() {
|
|
||||||
warn!(
|
|
||||||
"Failed to get relative episode number for episode {} ({}) of {} season {}",
|
|
||||||
episode.sequence_number,
|
|
||||||
episode.title,
|
|
||||||
episode.series_title,
|
|
||||||
episode.season_number,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Some(
|
|
||||||
episodes
|
|
||||||
.into_iter()
|
|
||||||
.map(|(e, s)| {
|
|
||||||
SingleFormat::new_from_episode(
|
|
||||||
e,
|
|
||||||
s,
|
|
||||||
relative_episode_number.map(|n| n as u32),
|
|
||||||
relative_sequence_number,
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn visit_movie_listing(&mut self, movie_listing: MovieListing) -> Result<Vec<Movie>> {
|
|
||||||
Ok(movie_listing.movies().await?)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn visit_movie(&mut self, movie: Movie) -> Result<Option<Self::T>> {
|
|
||||||
Ok(Some(vec![SingleFormat::new_from_movie(movie, vec![])]))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn visit_music_video(&mut self, music_video: MusicVideo) -> Result<Option<Self::T>> {
|
|
||||||
Ok(Some(vec![SingleFormat::new_from_music_video(music_video)]))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn visit_concert(&mut self, concert: Concert) -> Result<Option<Self::T>> {
|
|
||||||
Ok(Some(vec![SingleFormat::new_from_concert(concert)]))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn finish(self, input: Vec<Self::T>) -> Result<Self::Output> {
|
|
||||||
let flatten_input: Self::T = input.into_iter().flatten().collect();
|
|
||||||
|
|
||||||
let mut single_format_collection = SingleFormatCollection::new();
|
|
||||||
|
|
||||||
let mut pre_sorted: BTreeMap<String, Self::T> = BTreeMap::new();
|
|
||||||
for data in flatten_input {
|
|
||||||
pre_sorted
|
|
||||||
.entry(data.identifier.clone())
|
|
||||||
.or_insert(vec![])
|
|
||||||
.push(data)
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut sorted: Vec<(String, Self::T)> = pre_sorted.into_iter().collect();
|
|
||||||
sorted.sort_by(|(_, a), (_, b)| {
|
|
||||||
self.season_sorting
|
|
||||||
.iter()
|
|
||||||
.position(|p| p == &a.first().unwrap().season_id)
|
|
||||||
.unwrap()
|
|
||||||
.cmp(
|
|
||||||
&self
|
|
||||||
.season_sorting
|
|
||||||
.iter()
|
|
||||||
.position(|p| p == &b.first().unwrap().season_id)
|
|
||||||
.unwrap(),
|
|
||||||
)
|
|
||||||
});
|
|
||||||
|
|
||||||
for (_, mut data) in sorted {
|
|
||||||
data.sort_by(|a, b| {
|
|
||||||
self.archive
|
|
||||||
.audio
|
|
||||||
.iter()
|
|
||||||
.position(|p| p == &a.audio)
|
|
||||||
.unwrap_or(usize::MAX)
|
|
||||||
.cmp(
|
|
||||||
&self
|
|
||||||
.archive
|
|
||||||
.audio
|
|
||||||
.iter()
|
|
||||||
.position(|p| p == &b.audio)
|
|
||||||
.unwrap_or(usize::MAX),
|
|
||||||
)
|
|
||||||
});
|
|
||||||
single_format_collection.add_single_formats(data)
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(single_format_collection)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn missing_locales<'a>(available: &[Locale], searched: &'a [Locale]) -> Vec<&'a Locale> {
|
|
||||||
searched.iter().filter(|p| !available.contains(p)).collect()
|
|
||||||
}
|
|
||||||
|
|
@ -1,4 +1,3 @@
|
||||||
mod command;
|
mod command;
|
||||||
mod filter;
|
|
||||||
|
|
||||||
pub use command::Archive;
|
pub use command::Archive;
|
||||||
|
|
|
||||||
|
|
@ -1,20 +1,19 @@
|
||||||
use crate::download::filter::DownloadFilter;
|
|
||||||
use crate::utils::context::Context;
|
use crate::utils::context::Context;
|
||||||
use crate::utils::download::{DownloadBuilder, DownloadFormat, DownloadFormatMetadata};
|
use crate::utils::download::{DownloadBuilder, DownloadFormat, DownloadFormatMetadata};
|
||||||
use crate::utils::ffmpeg::{FFmpegPreset, SOFTSUB_CONTAINERS};
|
use crate::utils::ffmpeg::{FFmpegPreset, SOFTSUB_CONTAINERS};
|
||||||
use crate::utils::filter::Filter;
|
use crate::utils::filter::{Filter, FilterMediaScope};
|
||||||
use crate::utils::format::{Format, SingleFormat};
|
use crate::utils::format::{Format, SingleFormat};
|
||||||
use crate::utils::locale::{resolve_locales, LanguageTagging};
|
use crate::utils::locale::{resolve_locales, LanguageTagging};
|
||||||
use crate::utils::log::progress;
|
use crate::utils::log::progress;
|
||||||
use crate::utils::os::{free_file, has_ffmpeg, is_special_file};
|
use crate::utils::os::{free_file, has_ffmpeg, is_special_file};
|
||||||
use crate::utils::parse::parse_url;
|
use crate::utils::parse::parse_url;
|
||||||
use crate::utils::video::variant_data_from_stream;
|
use crate::utils::video::stream_data_from_stream;
|
||||||
use crate::Execute;
|
use crate::Execute;
|
||||||
use anyhow::bail;
|
use anyhow::bail;
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use crunchyroll_rs::media::Resolution;
|
use crunchyroll_rs::media::Resolution;
|
||||||
use crunchyroll_rs::Locale;
|
use crunchyroll_rs::Locale;
|
||||||
use log::{debug, warn};
|
use log::{debug, error, warn};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
|
|
@ -187,15 +186,6 @@ impl Execute for Download {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if self.output.contains("{resolution}")
|
|
||||||
|| self
|
|
||||||
.output_specials
|
|
||||||
.as_ref()
|
|
||||||
.map_or(false, |os| os.contains("{resolution}"))
|
|
||||||
{
|
|
||||||
warn!("The '{{resolution}}' format option is deprecated and will be removed in a future version. Please use '{{width}}' and '{{height}}' instead")
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(language_tagging) = &self.language_tagging {
|
if let Some(language_tagging) = &self.language_tagging {
|
||||||
self.audio = resolve_locales(&[self.audio.clone()]).remove(0);
|
self.audio = resolve_locales(&[self.audio.clone()]).remove(0);
|
||||||
self.subtitle = self
|
self.subtitle = self
|
||||||
|
|
@ -221,6 +211,10 @@ impl Execute for Download {
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn execute(self, ctx: Context) -> Result<()> {
|
async fn execute(self, ctx: Context) -> Result<()> {
|
||||||
|
if !ctx.crunchy.premium().await {
|
||||||
|
warn!("You may not be able to download all requested videos when logging in anonymously or using a non-premium account")
|
||||||
|
}
|
||||||
|
|
||||||
let mut parsed_urls = vec![];
|
let mut parsed_urls = vec![];
|
||||||
|
|
||||||
let output_supports_softsubs = SOFTSUB_CONTAINERS.contains(
|
let output_supports_softsubs = SOFTSUB_CONTAINERS.contains(
|
||||||
|
|
@ -255,8 +249,57 @@ impl Execute for Download {
|
||||||
|
|
||||||
for (i, (media_collection, url_filter)) in parsed_urls.into_iter().enumerate() {
|
for (i, (media_collection, url_filter)) in parsed_urls.into_iter().enumerate() {
|
||||||
let progress_handler = progress!("Fetching series details");
|
let progress_handler = progress!("Fetching series details");
|
||||||
let single_format_collection =
|
let single_format_collection = Filter::new(
|
||||||
DownloadFilter::new(url_filter, self.clone(), !self.yes, self.skip_specials)
|
url_filter,
|
||||||
|
vec![self.audio.clone()],
|
||||||
|
self.subtitle.as_ref().map_or(vec![], |s| vec![s.clone()]),
|
||||||
|
|scope, locales| {
|
||||||
|
match scope {
|
||||||
|
FilterMediaScope::Series(series) => bail!("Series {} is not available with {} audio", series.title, locales[0]),
|
||||||
|
FilterMediaScope::Season(season) => {
|
||||||
|
error!("Season {} is not available with {} audio", season.season_number, locales[0]);
|
||||||
|
Ok(false)
|
||||||
|
}
|
||||||
|
FilterMediaScope::Episode(episodes) => {
|
||||||
|
if episodes.len() == 1 {
|
||||||
|
warn!("Episode {} of season {} is not available with {} audio", episodes[0].sequence_number, episodes[0].season_title, locales[0])
|
||||||
|
} else if episodes.len() == 2 {
|
||||||
|
warn!("Season {} is only available with {} audio from episode {} to {}", episodes[0].season_number, locales[0], episodes[0].sequence_number, episodes[1].sequence_number)
|
||||||
|
} else {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
Ok(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|scope, locales| {
|
||||||
|
match scope {
|
||||||
|
FilterMediaScope::Series(series) => bail!("Series {} is not available with {} subtitles", series.title, locales[0]),
|
||||||
|
FilterMediaScope::Season(season) => {
|
||||||
|
warn!("Season {} is not available with {} subtitles", season.season_number, locales[0]);
|
||||||
|
Ok(false)
|
||||||
|
},
|
||||||
|
FilterMediaScope::Episode(episodes) => {
|
||||||
|
if episodes.len() == 1 {
|
||||||
|
warn!("Episode {} of season {} is not available with {} subtitles", episodes[0].sequence_number, episodes[0].season_title, locales[0])
|
||||||
|
} else if episodes.len() == 2 {
|
||||||
|
warn!("Season {} is only available with {} subtitles from episode {} to {}", episodes[0].season_number, locales[0], episodes[0].sequence_number, episodes[1].sequence_number)
|
||||||
|
} else {
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
Ok(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|season| {
|
||||||
|
warn!("Skipping premium episodes in season {season}");
|
||||||
|
Ok(())
|
||||||
|
},
|
||||||
|
Format::has_relative_fmt(&self.output),
|
||||||
|
!self.yes,
|
||||||
|
self.skip_specials,
|
||||||
|
ctx.crunchy.premium().await,
|
||||||
|
)
|
||||||
.visit(media_collection)
|
.visit(media_collection)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
|
|
@ -351,7 +394,7 @@ async fn get_format(
|
||||||
try_peer_hardsubs: bool,
|
try_peer_hardsubs: bool,
|
||||||
) -> Result<(DownloadFormat, Format)> {
|
) -> Result<(DownloadFormat, Format)> {
|
||||||
let stream = single_format.stream().await?;
|
let stream = single_format.stream().await?;
|
||||||
let Some((video, audio, contains_hardsub)) = variant_data_from_stream(
|
let Some((video, audio, contains_hardsub)) = stream_data_from_stream(
|
||||||
&stream,
|
&stream,
|
||||||
&download.resolution,
|
&download.resolution,
|
||||||
if try_peer_hardsubs {
|
if try_peer_hardsubs {
|
||||||
|
|
@ -384,12 +427,20 @@ async fn get_format(
|
||||||
let subtitle = if contains_hardsub {
|
let subtitle = if contains_hardsub {
|
||||||
None
|
None
|
||||||
} else if let Some(subtitle_locale) = &download.subtitle {
|
} else if let Some(subtitle_locale) = &download.subtitle {
|
||||||
|
if download.audio == Locale::ja_JP {
|
||||||
stream
|
stream
|
||||||
.subtitles
|
.subtitles
|
||||||
.get(subtitle_locale)
|
.get(subtitle_locale)
|
||||||
.cloned()
|
|
||||||
// use closed captions as fallback if no actual subtitles are found
|
// use closed captions as fallback if no actual subtitles are found
|
||||||
.or_else(|| stream.closed_captions.get(subtitle_locale).cloned())
|
.or_else(|| stream.captions.get(subtitle_locale))
|
||||||
|
.cloned()
|
||||||
|
} else {
|
||||||
|
stream
|
||||||
|
.captions
|
||||||
|
.get(subtitle_locale)
|
||||||
|
.or_else(|| stream.subtitles.get(subtitle_locale))
|
||||||
|
.cloned()
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
|
@ -400,7 +451,7 @@ async fn get_format(
|
||||||
subtitles: subtitle.clone().map_or(vec![], |s| {
|
subtitles: subtitle.clone().map_or(vec![], |s| {
|
||||||
vec![(
|
vec![(
|
||||||
s,
|
s,
|
||||||
single_format.audio == Locale::ja_JP || stream.subtitles.len() > 1,
|
single_format.audio != Locale::ja_JP && stream.subtitles.len() == 1,
|
||||||
)]
|
)]
|
||||||
}),
|
}),
|
||||||
metadata: DownloadFormatMetadata {
|
metadata: DownloadFormatMetadata {
|
||||||
|
|
@ -417,7 +468,7 @@ async fn get_format(
|
||||||
subtitle.map_or(vec![], |s| {
|
subtitle.map_or(vec![], |s| {
|
||||||
vec![(
|
vec![(
|
||||||
s,
|
s,
|
||||||
single_format.audio == Locale::ja_JP || stream.subtitles.len() > 1,
|
single_format.audio != Locale::ja_JP && stream.subtitles.len() == 1,
|
||||||
)]
|
)]
|
||||||
}),
|
}),
|
||||||
)]);
|
)]);
|
||||||
|
|
@ -426,5 +477,7 @@ async fn get_format(
|
||||||
subs.push(download.subtitle.clone().unwrap())
|
subs.push(download.subtitle.clone().unwrap())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
stream.invalidate().await?;
|
||||||
|
|
||||||
Ok((download_format, format))
|
Ok((download_format, format))
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,283 +0,0 @@
|
||||||
use crate::download::Download;
|
|
||||||
use crate::utils::filter::Filter;
|
|
||||||
use crate::utils::format::{Format, SingleFormat, SingleFormatCollection};
|
|
||||||
use crate::utils::interactive_select::{check_for_duplicated_seasons, get_duplicated_seasons};
|
|
||||||
use crate::utils::parse::{fract, UrlFilter};
|
|
||||||
use anyhow::{bail, Result};
|
|
||||||
use crunchyroll_rs::{Concert, Episode, Movie, MovieListing, MusicVideo, Season, Series};
|
|
||||||
use log::{error, info, warn};
|
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
pub(crate) struct DownloadFilter {
|
|
||||||
url_filter: UrlFilter,
|
|
||||||
download: Download,
|
|
||||||
interactive_input: bool,
|
|
||||||
skip_special: bool,
|
|
||||||
season_episodes: HashMap<u32, Vec<Episode>>,
|
|
||||||
season_subtitles_missing: Vec<u32>,
|
|
||||||
season_visited: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DownloadFilter {
|
|
||||||
pub(crate) fn new(
|
|
||||||
url_filter: UrlFilter,
|
|
||||||
download: Download,
|
|
||||||
interactive_input: bool,
|
|
||||||
skip_special: bool,
|
|
||||||
) -> Self {
|
|
||||||
Self {
|
|
||||||
url_filter,
|
|
||||||
download,
|
|
||||||
interactive_input,
|
|
||||||
skip_special,
|
|
||||||
season_episodes: HashMap::new(),
|
|
||||||
season_subtitles_missing: vec![],
|
|
||||||
season_visited: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Filter for DownloadFilter {
|
|
||||||
type T = SingleFormat;
|
|
||||||
type Output = SingleFormatCollection;
|
|
||||||
|
|
||||||
async fn visit_series(&mut self, series: Series) -> Result<Vec<Season>> {
|
|
||||||
// `series.audio_locales` isn't always populated b/c of crunchyrolls api. so check if the
|
|
||||||
// audio is matching only if the field is populated
|
|
||||||
if !series.audio_locales.is_empty() && !series.audio_locales.contains(&self.download.audio)
|
|
||||||
{
|
|
||||||
error!(
|
|
||||||
"Series {} is not available with {} audio",
|
|
||||||
series.title, self.download.audio
|
|
||||||
);
|
|
||||||
return Ok(vec![]);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut seasons = vec![];
|
|
||||||
for mut season in series.seasons().await? {
|
|
||||||
if !self.url_filter.is_season_valid(season.season_number) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if !season
|
|
||||||
.audio_locales
|
|
||||||
.iter()
|
|
||||||
.any(|l| l == &self.download.audio)
|
|
||||||
{
|
|
||||||
if season
|
|
||||||
.available_versions()
|
|
||||||
.await?
|
|
||||||
.iter()
|
|
||||||
.any(|l| l == &self.download.audio)
|
|
||||||
{
|
|
||||||
season = season
|
|
||||||
.version(vec![self.download.audio.clone()])
|
|
||||||
.await?
|
|
||||||
.remove(0)
|
|
||||||
} else {
|
|
||||||
error!(
|
|
||||||
"Season {} - '{}' is not available with {} audio",
|
|
||||||
season.season_number,
|
|
||||||
season.title,
|
|
||||||
self.download.audio.clone(),
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
seasons.push(season)
|
|
||||||
}
|
|
||||||
|
|
||||||
let duplicated_seasons = get_duplicated_seasons(&seasons);
|
|
||||||
if !duplicated_seasons.is_empty() {
|
|
||||||
if self.interactive_input {
|
|
||||||
check_for_duplicated_seasons(&mut seasons);
|
|
||||||
} else {
|
|
||||||
info!(
|
|
||||||
"Found duplicated seasons: {}",
|
|
||||||
duplicated_seasons
|
|
||||||
.iter()
|
|
||||||
.map(|d| d.to_string())
|
|
||||||
.collect::<Vec<String>>()
|
|
||||||
.join(", ")
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(seasons)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn visit_season(&mut self, season: Season) -> Result<Vec<Episode>> {
|
|
||||||
self.season_visited = true;
|
|
||||||
|
|
||||||
let mut episodes = season.episodes().await?;
|
|
||||||
|
|
||||||
if Format::has_relative_fmt(&self.download.output) {
|
|
||||||
for episode in episodes.iter() {
|
|
||||||
self.season_episodes
|
|
||||||
.entry(episode.season_number)
|
|
||||||
.or_default()
|
|
||||||
.push(episode.clone())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
episodes.retain(|e| {
|
|
||||||
self.url_filter
|
|
||||||
.is_episode_valid(e.sequence_number, season.season_number)
|
|
||||||
});
|
|
||||||
|
|
||||||
Ok(episodes)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn visit_episode(&mut self, mut episode: Episode) -> Result<Option<Self::T>> {
|
|
||||||
if !self
|
|
||||||
.url_filter
|
|
||||||
.is_episode_valid(episode.sequence_number, episode.season_number)
|
|
||||||
{
|
|
||||||
return Ok(None);
|
|
||||||
}
|
|
||||||
|
|
||||||
// skip the episode if it's a special
|
|
||||||
if self.skip_special
|
|
||||||
&& (episode.sequence_number == 0.0 || episode.sequence_number.fract() != 0.0)
|
|
||||||
{
|
|
||||||
return Ok(None);
|
|
||||||
}
|
|
||||||
|
|
||||||
// check if the audio locale is correct.
|
|
||||||
// should only be incorrect if the console input was a episode url. otherwise
|
|
||||||
// `DownloadFilter::visit_season` returns the correct episodes with matching audio
|
|
||||||
if episode.audio_locale != self.download.audio {
|
|
||||||
// check if any other version (same episode, other language) of this episode is available
|
|
||||||
// with the requested audio. if not, return an error
|
|
||||||
if !episode
|
|
||||||
.available_versions()
|
|
||||||
.await?
|
|
||||||
.contains(&self.download.audio)
|
|
||||||
{
|
|
||||||
let error_message = format!(
|
|
||||||
"Episode {} ({}) of {} season {} is not available with {} audio",
|
|
||||||
episode.sequence_number,
|
|
||||||
episode.title,
|
|
||||||
episode.series_title,
|
|
||||||
episode.season_number,
|
|
||||||
self.download.audio
|
|
||||||
);
|
|
||||||
// sometimes a series randomly has episode in an other language. if this is the case,
|
|
||||||
// only error if the input url was a episode url
|
|
||||||
if self.season_visited {
|
|
||||||
warn!("{}", error_message);
|
|
||||||
return Ok(None);
|
|
||||||
} else {
|
|
||||||
bail!("{}", error_message)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// overwrite the current episode with the other version episode
|
|
||||||
episode = episode
|
|
||||||
.version(vec![self.download.audio.clone()])
|
|
||||||
.await?
|
|
||||||
.remove(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
// check if the subtitles are supported
|
|
||||||
if let Some(subtitle_locale) = &self.download.subtitle {
|
|
||||||
if !episode.subtitle_locales.contains(subtitle_locale) {
|
|
||||||
// if the episode doesn't have the requested subtitles, print a error. to print this
|
|
||||||
// error only once per season, it's checked if an error got printed before by looking
|
|
||||||
// up if the season id is present in `self.season_subtitles_missing`. if not, print
|
|
||||||
// the error and add the season id to `self.season_subtitles_missing`. if it is
|
|
||||||
// present, skip the error printing
|
|
||||||
if !self
|
|
||||||
.season_subtitles_missing
|
|
||||||
.contains(&episode.season_number)
|
|
||||||
{
|
|
||||||
self.season_subtitles_missing.push(episode.season_number);
|
|
||||||
error!(
|
|
||||||
"{} season {} is not available with {} subtitles",
|
|
||||||
episode.series_title, episode.season_number, subtitle_locale
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return Ok(None);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut relative_episode_number = None;
|
|
||||||
let mut relative_sequence_number = None;
|
|
||||||
// get the relative episode number. only done if the output string has the pattern to include
|
|
||||||
// the relative episode number as this requires some extra fetching
|
|
||||||
if Format::has_relative_fmt(&self.download.output) {
|
|
||||||
let season_eps = match self.season_episodes.get(&episode.season_number) {
|
|
||||||
Some(eps) => eps,
|
|
||||||
None => {
|
|
||||||
self.season_episodes.insert(
|
|
||||||
episode.season_number,
|
|
||||||
episode.season().await?.episodes().await?,
|
|
||||||
);
|
|
||||||
self.season_episodes.get(&episode.season_number).unwrap()
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let mut non_integer_sequence_number_count = 0;
|
|
||||||
for (i, ep) in season_eps.iter().enumerate() {
|
|
||||||
if ep.sequence_number.fract() != 0.0 || ep.sequence_number == 0.0 {
|
|
||||||
non_integer_sequence_number_count += 1;
|
|
||||||
}
|
|
||||||
if ep.id == episode.id {
|
|
||||||
relative_episode_number = Some(i + 1);
|
|
||||||
relative_sequence_number = Some(
|
|
||||||
(i + 1 - non_integer_sequence_number_count) as f32
|
|
||||||
+ fract(ep.sequence_number),
|
|
||||||
);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if relative_episode_number.is_none() || relative_sequence_number.is_none() {
|
|
||||||
warn!(
|
|
||||||
"Failed to get relative episode number for episode {} ({}) of {} season {}",
|
|
||||||
episode.sequence_number,
|
|
||||||
episode.title,
|
|
||||||
episode.series_title,
|
|
||||||
episode.season_number,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Some(SingleFormat::new_from_episode(
|
|
||||||
episode.clone(),
|
|
||||||
self.download.subtitle.clone().map_or(vec![], |s| {
|
|
||||||
if episode.subtitle_locales.contains(&s) {
|
|
||||||
vec![s]
|
|
||||||
} else {
|
|
||||||
vec![]
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
relative_episode_number.map(|n| n as u32),
|
|
||||||
relative_sequence_number,
|
|
||||||
)))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn visit_movie_listing(&mut self, movie_listing: MovieListing) -> Result<Vec<Movie>> {
|
|
||||||
Ok(movie_listing.movies().await?)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn visit_movie(&mut self, movie: Movie) -> Result<Option<Self::T>> {
|
|
||||||
Ok(Some(SingleFormat::new_from_movie(movie, vec![])))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn visit_music_video(&mut self, music_video: MusicVideo) -> Result<Option<Self::T>> {
|
|
||||||
Ok(Some(SingleFormat::new_from_music_video(music_video)))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn visit_concert(&mut self, concert: Concert) -> Result<Option<Self::T>> {
|
|
||||||
Ok(Some(SingleFormat::new_from_concert(concert)))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn finish(self, input: Vec<Self::T>) -> Result<Self::Output> {
|
|
||||||
let mut single_format_collection = SingleFormatCollection::new();
|
|
||||||
|
|
||||||
for data in input {
|
|
||||||
single_format_collection.add_single_formats(vec![data])
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(single_format_collection)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,4 +1,3 @@
|
||||||
mod command;
|
mod command;
|
||||||
mod filter;
|
|
||||||
|
|
||||||
pub use command::Download;
|
pub use command::Download;
|
||||||
|
|
|
||||||
|
|
@ -184,6 +184,7 @@ pub async fn main(args: &[String]) {
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
.starts_with(".crunchy-cli_")
|
.starts_with(".crunchy-cli_")
|
||||||
{
|
{
|
||||||
|
if file.file_type().map_or(true, |ft| ft.is_file()) {
|
||||||
let result = fs::remove_file(file.path());
|
let result = fs::remove_file(file.path());
|
||||||
debug!(
|
debug!(
|
||||||
"Ctrl-c removed temporary file {} {}",
|
"Ctrl-c removed temporary file {} {}",
|
||||||
|
|
@ -194,6 +195,18 @@ pub async fn main(args: &[String]) {
|
||||||
"not successfully"
|
"not successfully"
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
} else {
|
||||||
|
let result = fs::remove_dir_all(file.path());
|
||||||
|
debug!(
|
||||||
|
"Ctrl-c removed temporary directory {} {}",
|
||||||
|
file.path().to_string_lossy(),
|
||||||
|
if result.is_ok() {
|
||||||
|
"successfully"
|
||||||
|
} else {
|
||||||
|
"not successfully"
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -225,8 +238,6 @@ async fn execute_executor(executor: impl Execute, ctx: Context) {
|
||||||
if let Some(crunchy_error) = err.downcast_mut::<Error>() {
|
if let Some(crunchy_error) = err.downcast_mut::<Error>() {
|
||||||
if let Error::Block { message, .. } = crunchy_error {
|
if let Error::Block { message, .. } = crunchy_error {
|
||||||
*message = "Triggered Cloudflare bot protection. Try again later or use a VPN or proxy to spoof your location".to_string()
|
*message = "Triggered Cloudflare bot protection. Try again later or use a VPN or proxy to spoof your location".to_string()
|
||||||
} else if let Error::Request { message, .. } = crunchy_error {
|
|
||||||
*message = "You've probably hit a rate limit. Try again later, generally after 10-20 minutes the rate limit is over and you can continue to use the cli".to_string()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
error!("An error occurred: {}", crunchy_error)
|
error!("An error occurred: {}", crunchy_error)
|
||||||
|
|
@ -315,9 +326,8 @@ async fn crunchyroll_session(
|
||||||
builder = builder.middleware(rate_limiter)
|
builder = builder.middleware(rate_limiter)
|
||||||
}
|
}
|
||||||
|
|
||||||
let root_login_methods_count = cli.login_method.credentials.is_some() as u8
|
let root_login_methods_count =
|
||||||
+ cli.login_method.etp_rt.is_some() as u8
|
cli.login_method.credentials.is_some() as u8 + cli.login_method.anonymous as u8;
|
||||||
+ cli.login_method.anonymous as u8;
|
|
||||||
|
|
||||||
let progress_handler = progress!("Logging in");
|
let progress_handler = progress!("Logging in");
|
||||||
if root_login_methods_count == 0 {
|
if root_login_methods_count == 0 {
|
||||||
|
|
@ -327,18 +337,28 @@ async fn crunchyroll_session(
|
||||||
if let Some((token_type, token)) = session.split_once(':') {
|
if let Some((token_type, token)) = session.split_once(':') {
|
||||||
match token_type {
|
match token_type {
|
||||||
"refresh_token" => {
|
"refresh_token" => {
|
||||||
return Ok(builder.login_with_refresh_token(token).await?)
|
return match builder.login_with_refresh_token(token).await {
|
||||||
|
Ok(crunchy) => Ok(crunchy),
|
||||||
|
Err(e) => {
|
||||||
|
if let Error::Request { message, .. } = &e {
|
||||||
|
if message.starts_with("invalid_grant") {
|
||||||
|
bail!("The stored login is expired, please login again")
|
||||||
}
|
}
|
||||||
"etp_rt" => return Ok(builder.login_with_etp_rt(token).await?),
|
}
|
||||||
|
Err(e.into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"etp_rt" => bail!("The stored login method (etp-rt) isn't supported anymore. Please login again using your credentials"),
|
||||||
_ => (),
|
_ => (),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
bail!("Could not read stored session ('{}')", session)
|
bail!("Could not read stored session ('{}')", session)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
bail!("Please use a login method ('--credentials', '--etp-rt' or '--anonymous')")
|
bail!("Please use a login method ('--credentials' or '--anonymous')")
|
||||||
} else if root_login_methods_count > 1 {
|
} else if root_login_methods_count > 1 {
|
||||||
bail!("Please use only one login method ('--credentials', '--etp-rt' or '--anonymous')")
|
bail!("Please use only one login method ('--credentials' or '--anonymous')")
|
||||||
}
|
}
|
||||||
|
|
||||||
let crunchy = if let Some(credentials) = &cli.login_method.credentials {
|
let crunchy = if let Some(credentials) = &cli.login_method.credentials {
|
||||||
|
|
@ -347,8 +367,6 @@ async fn crunchyroll_session(
|
||||||
} else {
|
} else {
|
||||||
bail!("Invalid credentials format. Please provide your credentials as email:password")
|
bail!("Invalid credentials format. Please provide your credentials as email:password")
|
||||||
}
|
}
|
||||||
} else if let Some(etp_rt) = &cli.login_method.etp_rt {
|
|
||||||
builder.login_with_etp_rt(etp_rt).await?
|
|
||||||
} else if cli.login_method.anonymous {
|
} else if cli.login_method.anonymous {
|
||||||
builder.login_anonymously().await?
|
builder.login_anonymously().await?
|
||||||
} else {
|
} else {
|
||||||
|
|
|
||||||
|
|
@ -25,9 +25,7 @@ impl Execute for Login {
|
||||||
SessionToken::RefreshToken(refresh_token) => {
|
SessionToken::RefreshToken(refresh_token) => {
|
||||||
fs::write(login_file_path, format!("refresh_token:{}", refresh_token))?
|
fs::write(login_file_path, format!("refresh_token:{}", refresh_token))?
|
||||||
}
|
}
|
||||||
SessionToken::EtpRt(etp_rt) => {
|
SessionToken::EtpRt(_) => bail!("Login with etp_rt isn't supported anymore. Please use your credentials to login"),
|
||||||
fs::write(login_file_path, format!("etp_rt:{}", etp_rt))?
|
|
||||||
}
|
|
||||||
SessionToken::Anonymous => bail!("Anonymous login cannot be saved"),
|
SessionToken::Anonymous => bail!("Anonymous login cannot be saved"),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -47,12 +45,6 @@ pub struct LoginMethod {
|
||||||
)]
|
)]
|
||||||
#[arg(global = true, long)]
|
#[arg(global = true, long)]
|
||||||
pub credentials: Option<String>,
|
pub credentials: Option<String>,
|
||||||
#[arg(help = "Login with the etp-rt cookie")]
|
|
||||||
#[arg(
|
|
||||||
long_help = "Login with the etp-rt cookie. This can be obtained when you login on crunchyroll.com and extract it from there"
|
|
||||||
)]
|
|
||||||
#[arg(global = true, long)]
|
|
||||||
pub etp_rt: Option<String>,
|
|
||||||
#[arg(help = "Login anonymously / without an account")]
|
#[arg(help = "Login anonymously / without an account")]
|
||||||
#[arg(global = true, long, default_value_t = false)]
|
#[arg(global = true, long, default_value_t = false)]
|
||||||
pub anonymous: bool,
|
pub anonymous: bool,
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ use crunchyroll_rs::common::StreamExt;
|
||||||
use crunchyroll_rs::search::QueryResults;
|
use crunchyroll_rs::search::QueryResults;
|
||||||
use crunchyroll_rs::{Episode, Locale, MediaCollection, MovieListing, MusicVideo, Series};
|
use crunchyroll_rs::{Episode, Locale, MediaCollection, MovieListing, MusicVideo, Series};
|
||||||
use log::warn;
|
use log::warn;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
#[derive(Debug, clap::Parser)]
|
#[derive(Debug, clap::Parser)]
|
||||||
#[clap(about = "Search in videos")]
|
#[clap(about = "Search in videos")]
|
||||||
|
|
@ -87,13 +88,16 @@ pub struct Search {
|
||||||
/// concert.premium_only → If the concert is only available with Crunchyroll premium
|
/// concert.premium_only → If the concert is only available with Crunchyroll premium
|
||||||
///
|
///
|
||||||
/// stream.locale → Stream locale/language
|
/// stream.locale → Stream locale/language
|
||||||
/// stream.dash_url → Stream url in DASH format
|
/// stream.dash_url → Stream url in DASH format. You need to set the `Authorization` header to `Bearer <account.token>` when requesting this url
|
||||||
/// stream.drm_dash_url → Stream url in DRM protected DASH format
|
/// stream.is_drm → If `stream.dash_url` is DRM encrypted
|
||||||
/// stream.hls_url → Stream url in HLS format
|
|
||||||
/// stream.drm_hls_url → Stream url in DRM protected HLS format
|
|
||||||
///
|
///
|
||||||
/// subtitle.locale → Subtitle locale/language
|
/// subtitle.locale → Subtitle locale/language
|
||||||
/// subtitle.url → Url to the subtitle
|
/// subtitle.url → Url to the subtitle
|
||||||
|
///
|
||||||
|
/// account.token → Access token to make request to restricted endpoints. This token is only valid for a max. of 5 minutes
|
||||||
|
/// account.id → Internal ID of the user account
|
||||||
|
/// account.profile_name → Profile name of the account
|
||||||
|
/// account.email → Email address of the account
|
||||||
#[arg(short, long, verbatim_doc_comment)]
|
#[arg(short, long, verbatim_doc_comment)]
|
||||||
#[arg(default_value = "S{{season.number}}E{{episode.number}} - {{episode.title}}")]
|
#[arg(default_value = "S{{season.number}}E{{episode.number}} - {{episode.title}}")]
|
||||||
output: String,
|
output: String,
|
||||||
|
|
@ -107,6 +111,10 @@ impl Execute for Search {
|
||||||
warn!("Using `search` anonymously or with a non-premium account may return incomplete results")
|
warn!("Using `search` anonymously or with a non-premium account may return incomplete results")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if self.output.contains("{{stream.is_drm}}") {
|
||||||
|
warn!("The `{{{{stream.is_drm}}}}` option is deprecated as it isn't reliable anymore and will be removed soon")
|
||||||
|
}
|
||||||
|
|
||||||
let input = if crunchyroll_rs::parse::parse_url(&self.input).is_some() {
|
let input = if crunchyroll_rs::parse::parse_url(&self.input).is_some() {
|
||||||
match parse_url(&ctx.crunchy, self.input.clone(), true).await {
|
match parse_url(&ctx.crunchy, self.input.clone(), true).await {
|
||||||
Ok(ok) => vec![ok],
|
Ok(ok) => vec![ok],
|
||||||
|
|
@ -145,13 +153,14 @@ impl Execute for Search {
|
||||||
output
|
output
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let crunchy_arc = Arc::new(ctx.crunchy);
|
||||||
for (media_collection, url_filter) in input {
|
for (media_collection, url_filter) in input {
|
||||||
let filter_options = FilterOptions {
|
let filter_options = FilterOptions {
|
||||||
audio: self.audio.clone(),
|
audio: self.audio.clone(),
|
||||||
url_filter,
|
url_filter,
|
||||||
};
|
};
|
||||||
|
|
||||||
let format = Format::new(self.output.clone(), filter_options)?;
|
let format = Format::new(self.output.clone(), filter_options, crunchy_arc.clone())?;
|
||||||
println!("{}", format.parse(media_collection).await?);
|
println!("{}", format.parse(media_collection).await?);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,13 +2,15 @@ use crate::search::filter::FilterOptions;
|
||||||
use anyhow::{bail, Result};
|
use anyhow::{bail, Result};
|
||||||
use crunchyroll_rs::media::{Stream, Subtitle};
|
use crunchyroll_rs::media::{Stream, Subtitle};
|
||||||
use crunchyroll_rs::{
|
use crunchyroll_rs::{
|
||||||
Concert, Episode, Locale, MediaCollection, Movie, MovieListing, MusicVideo, Season, Series,
|
Concert, Crunchyroll, Episode, Locale, MediaCollection, Movie, MovieListing, MusicVideo,
|
||||||
|
Season, Series,
|
||||||
};
|
};
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use serde_json::{Map, Value};
|
use serde_json::{Map, Value};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::ops::Range;
|
use std::ops::Range;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
#[derive(Default, Serialize)]
|
#[derive(Default, Serialize)]
|
||||||
struct FormatSeries {
|
struct FormatSeries {
|
||||||
|
|
@ -163,37 +165,15 @@ impl From<&Concert> for FormatConcert {
|
||||||
struct FormatStream {
|
struct FormatStream {
|
||||||
pub locale: Locale,
|
pub locale: Locale,
|
||||||
pub dash_url: String,
|
pub dash_url: String,
|
||||||
pub drm_dash_url: String,
|
pub is_drm: bool,
|
||||||
pub hls_url: String,
|
|
||||||
pub drm_hls_url: String,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<&Stream> for FormatStream {
|
impl From<&Stream> for FormatStream {
|
||||||
fn from(value: &Stream) -> Self {
|
fn from(value: &Stream) -> Self {
|
||||||
let (dash_url, drm_dash_url, hls_url, drm_hls_url) =
|
|
||||||
value.variants.get(&Locale::Custom("".to_string())).map_or(
|
|
||||||
(
|
|
||||||
"".to_string(),
|
|
||||||
"".to_string(),
|
|
||||||
"".to_string(),
|
|
||||||
"".to_string(),
|
|
||||||
),
|
|
||||||
|v| {
|
|
||||||
(
|
|
||||||
v.adaptive_dash.clone().unwrap_or_default().url,
|
|
||||||
v.drm_adaptive_dash.clone().unwrap_or_default().url,
|
|
||||||
v.adaptive_hls.clone().unwrap_or_default().url,
|
|
||||||
v.drm_adaptive_hls.clone().unwrap_or_default().url,
|
|
||||||
)
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
locale: value.audio_locale.clone(),
|
locale: value.audio_locale.clone(),
|
||||||
dash_url,
|
dash_url: value.url.clone(),
|
||||||
drm_dash_url,
|
is_drm: false,
|
||||||
hls_url,
|
|
||||||
drm_hls_url,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -213,6 +193,27 @@ impl From<&Subtitle> for FormatSubtitle {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Serialize)]
|
||||||
|
struct FormatAccount {
|
||||||
|
pub token: String,
|
||||||
|
pub id: String,
|
||||||
|
pub profile_name: String,
|
||||||
|
pub email: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FormatAccount {
|
||||||
|
pub async fn async_from(value: &Crunchyroll) -> Result<Self> {
|
||||||
|
let account = value.account().await?;
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
token: value.access_token().await,
|
||||||
|
id: account.account_id,
|
||||||
|
profile_name: account.profile_name,
|
||||||
|
email: account.email,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
|
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
|
||||||
enum Scope {
|
enum Scope {
|
||||||
Series,
|
Series,
|
||||||
|
|
@ -224,6 +225,7 @@ enum Scope {
|
||||||
Concert,
|
Concert,
|
||||||
Stream,
|
Stream,
|
||||||
Subtitle,
|
Subtitle,
|
||||||
|
Account,
|
||||||
}
|
}
|
||||||
|
|
||||||
macro_rules! must_match_if_true {
|
macro_rules! must_match_if_true {
|
||||||
|
|
@ -239,23 +241,20 @@ macro_rules! must_match_if_true {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
macro_rules! self_and_versions {
|
|
||||||
($var:expr => $audio:expr) => {{
|
|
||||||
let mut items = vec![$var.clone()];
|
|
||||||
items.extend($var.clone().version($audio).await?);
|
|
||||||
items
|
|
||||||
}};
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Format {
|
pub struct Format {
|
||||||
pattern: Vec<(Range<usize>, Scope, String)>,
|
pattern: Vec<(Range<usize>, Scope, String)>,
|
||||||
pattern_count: HashMap<Scope, u32>,
|
pattern_count: HashMap<Scope, u32>,
|
||||||
input: String,
|
input: String,
|
||||||
filter_options: FilterOptions,
|
filter_options: FilterOptions,
|
||||||
|
crunchyroll: Arc<Crunchyroll>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Format {
|
impl Format {
|
||||||
pub fn new(input: String, filter_options: FilterOptions) -> Result<Self> {
|
pub fn new(
|
||||||
|
input: String,
|
||||||
|
filter_options: FilterOptions,
|
||||||
|
crunchyroll: Arc<Crunchyroll>,
|
||||||
|
) -> Result<Self> {
|
||||||
let scope_regex = Regex::new(r"(?m)\{\{\s*(?P<scope>\w+)\.(?P<field>\w+)\s*}}").unwrap();
|
let scope_regex = Regex::new(r"(?m)\{\{\s*(?P<scope>\w+)\.(?P<field>\w+)\s*}}").unwrap();
|
||||||
let mut pattern = vec![];
|
let mut pattern = vec![];
|
||||||
let mut pattern_count = HashMap::new();
|
let mut pattern_count = HashMap::new();
|
||||||
|
|
@ -282,6 +281,7 @@ impl Format {
|
||||||
Scope::Concert => FormatConcert
|
Scope::Concert => FormatConcert
|
||||||
Scope::Stream => FormatStream
|
Scope::Stream => FormatStream
|
||||||
Scope::Subtitle => FormatSubtitle
|
Scope::Subtitle => FormatSubtitle
|
||||||
|
Scope::Account => FormatAccount
|
||||||
);
|
);
|
||||||
|
|
||||||
for capture in scope_regex.captures_iter(&input) {
|
for capture in scope_regex.captures_iter(&input) {
|
||||||
|
|
@ -299,6 +299,7 @@ impl Format {
|
||||||
"concert" => Scope::Concert,
|
"concert" => Scope::Concert,
|
||||||
"stream" => Scope::Stream,
|
"stream" => Scope::Stream,
|
||||||
"subtitle" => Scope::Subtitle,
|
"subtitle" => Scope::Subtitle,
|
||||||
|
"account" => Scope::Account,
|
||||||
_ => bail!("'{}.{}' is not a valid keyword", scope, field),
|
_ => bail!("'{}.{}' is not a valid keyword", scope, field),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -324,6 +325,7 @@ impl Format {
|
||||||
pattern_count,
|
pattern_count,
|
||||||
input,
|
input,
|
||||||
filter_options,
|
filter_options,
|
||||||
|
crunchyroll,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -338,6 +340,7 @@ impl Format {
|
||||||
Scope::Episode,
|
Scope::Episode,
|
||||||
Scope::Stream,
|
Scope::Stream,
|
||||||
Scope::Subtitle,
|
Scope::Subtitle,
|
||||||
|
Scope::Account,
|
||||||
])?;
|
])?;
|
||||||
|
|
||||||
self.parse_series(media_collection).await
|
self.parse_series(media_collection).await
|
||||||
|
|
@ -348,17 +351,28 @@ impl Format {
|
||||||
Scope::Movie,
|
Scope::Movie,
|
||||||
Scope::Stream,
|
Scope::Stream,
|
||||||
Scope::Subtitle,
|
Scope::Subtitle,
|
||||||
|
Scope::Account,
|
||||||
])?;
|
])?;
|
||||||
|
|
||||||
self.parse_movie_listing(media_collection).await
|
self.parse_movie_listing(media_collection).await
|
||||||
}
|
}
|
||||||
MediaCollection::MusicVideo(_) => {
|
MediaCollection::MusicVideo(_) => {
|
||||||
self.check_scopes(vec![Scope::MusicVideo, Scope::Stream, Scope::Subtitle])?;
|
self.check_scopes(vec![
|
||||||
|
Scope::MusicVideo,
|
||||||
|
Scope::Stream,
|
||||||
|
Scope::Subtitle,
|
||||||
|
Scope::Account,
|
||||||
|
])?;
|
||||||
|
|
||||||
self.parse_music_video(media_collection).await
|
self.parse_music_video(media_collection).await
|
||||||
}
|
}
|
||||||
MediaCollection::Concert(_) => {
|
MediaCollection::Concert(_) => {
|
||||||
self.check_scopes(vec![Scope::Concert, Scope::Stream, Scope::Subtitle])?;
|
self.check_scopes(vec![
|
||||||
|
Scope::Concert,
|
||||||
|
Scope::Stream,
|
||||||
|
Scope::Subtitle,
|
||||||
|
Scope::Account,
|
||||||
|
])?;
|
||||||
|
|
||||||
self.parse_concert(media_collection).await
|
self.parse_concert(media_collection).await
|
||||||
}
|
}
|
||||||
|
|
@ -371,6 +385,7 @@ impl Format {
|
||||||
let episode_empty = self.check_pattern_count_empty(Scope::Episode);
|
let episode_empty = self.check_pattern_count_empty(Scope::Episode);
|
||||||
let stream_empty = self.check_pattern_count_empty(Scope::Stream)
|
let stream_empty = self.check_pattern_count_empty(Scope::Stream)
|
||||||
&& self.check_pattern_count_empty(Scope::Subtitle);
|
&& self.check_pattern_count_empty(Scope::Subtitle);
|
||||||
|
let account_empty = self.check_pattern_count_empty(Scope::Account);
|
||||||
|
|
||||||
#[allow(clippy::type_complexity)]
|
#[allow(clippy::type_complexity)]
|
||||||
let mut tree: Vec<(Season, Vec<(Episode, Vec<Stream>)>)> = vec![];
|
let mut tree: Vec<(Season, Vec<(Episode, Vec<Stream>)>)> = vec![];
|
||||||
|
|
@ -398,7 +413,15 @@ impl Format {
|
||||||
};
|
};
|
||||||
let mut seasons = vec![];
|
let mut seasons = vec![];
|
||||||
for season in tmp_seasons {
|
for season in tmp_seasons {
|
||||||
seasons.extend(self_and_versions!(season => self.filter_options.audio.clone()))
|
seasons.push(season.clone());
|
||||||
|
for version in season.versions {
|
||||||
|
if season.id == version.id {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if self.filter_options.audio.contains(&version.audio_locale) {
|
||||||
|
seasons.push(version.season().await?)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
tree.extend(
|
tree.extend(
|
||||||
self.filter_options
|
self.filter_options
|
||||||
|
|
@ -412,7 +435,15 @@ impl Format {
|
||||||
if !episode_empty || !stream_empty {
|
if !episode_empty || !stream_empty {
|
||||||
match &media_collection {
|
match &media_collection {
|
||||||
MediaCollection::Episode(episode) => {
|
MediaCollection::Episode(episode) => {
|
||||||
let episodes = self_and_versions!(episode => self.filter_options.audio.clone());
|
let mut episodes = vec![episode.clone()];
|
||||||
|
for version in &episode.versions {
|
||||||
|
if episode.id == version.id {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if self.filter_options.audio.contains(&version.audio_locale) {
|
||||||
|
episodes.push(version.episode().await?)
|
||||||
|
}
|
||||||
|
}
|
||||||
tree.push((
|
tree.push((
|
||||||
Season::default(),
|
Season::default(),
|
||||||
episodes
|
episodes
|
||||||
|
|
@ -441,7 +472,9 @@ impl Format {
|
||||||
if !stream_empty {
|
if !stream_empty {
|
||||||
for (_, episodes) in tree.iter_mut() {
|
for (_, episodes) in tree.iter_mut() {
|
||||||
for (episode, streams) in episodes {
|
for (episode, streams) in episodes {
|
||||||
streams.push(episode.stream().await?)
|
let stream = episode.stream_maybe_without_drm().await?;
|
||||||
|
stream.clone().invalidate().await?;
|
||||||
|
streams.push(stream)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -453,6 +486,11 @@ impl Format {
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut output = vec![];
|
let mut output = vec![];
|
||||||
|
let account_map = if !account_empty {
|
||||||
|
self.serializable_to_json_map(FormatAccount::async_from(&self.crunchyroll).await?)
|
||||||
|
} else {
|
||||||
|
Map::default()
|
||||||
|
};
|
||||||
let series_map = self.serializable_to_json_map(FormatSeries::from(&series));
|
let series_map = self.serializable_to_json_map(FormatSeries::from(&series));
|
||||||
for (season, episodes) in tree {
|
for (season, episodes) in tree {
|
||||||
let season_map = self.serializable_to_json_map(FormatSeason::from(&season));
|
let season_map = self.serializable_to_json_map(FormatSeason::from(&season));
|
||||||
|
|
@ -464,6 +502,7 @@ impl Format {
|
||||||
output.push(
|
output.push(
|
||||||
self.replace_all(
|
self.replace_all(
|
||||||
HashMap::from([
|
HashMap::from([
|
||||||
|
(Scope::Account, &account_map),
|
||||||
(Scope::Series, &series_map),
|
(Scope::Series, &series_map),
|
||||||
(Scope::Season, &season_map),
|
(Scope::Season, &season_map),
|
||||||
(Scope::Episode, &episode_map),
|
(Scope::Episode, &episode_map),
|
||||||
|
|
@ -510,7 +549,7 @@ impl Format {
|
||||||
}
|
}
|
||||||
if !stream_empty {
|
if !stream_empty {
|
||||||
for (movie, streams) in tree.iter_mut() {
|
for (movie, streams) in tree.iter_mut() {
|
||||||
streams.push(movie.stream().await?)
|
streams.push(movie.stream_maybe_without_drm().await?)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
for (_, streams) in tree.iter_mut() {
|
for (_, streams) in tree.iter_mut() {
|
||||||
|
|
@ -548,7 +587,7 @@ impl Format {
|
||||||
let stream_empty = self.check_pattern_count_empty(Scope::Stream);
|
let stream_empty = self.check_pattern_count_empty(Scope::Stream);
|
||||||
|
|
||||||
let music_video = must_match_if_true!(!music_video_empty => media_collection|MediaCollection::MusicVideo(music_video) => music_video.clone()).unwrap_or_default();
|
let music_video = must_match_if_true!(!music_video_empty => media_collection|MediaCollection::MusicVideo(music_video) => music_video.clone()).unwrap_or_default();
|
||||||
let stream = must_match_if_true!(!stream_empty => media_collection|MediaCollection::MusicVideo(music_video) => music_video.stream().await?).unwrap_or_default();
|
let stream = must_match_if_true!(!stream_empty => media_collection|MediaCollection::MusicVideo(music_video) => music_video.stream_maybe_without_drm().await?).unwrap_or_default();
|
||||||
|
|
||||||
let music_video_map = self.serializable_to_json_map(FormatMusicVideo::from(&music_video));
|
let music_video_map = self.serializable_to_json_map(FormatMusicVideo::from(&music_video));
|
||||||
let stream_map = self.serializable_to_json_map(FormatStream::from(&stream));
|
let stream_map = self.serializable_to_json_map(FormatStream::from(&stream));
|
||||||
|
|
@ -570,7 +609,7 @@ impl Format {
|
||||||
let stream_empty = self.check_pattern_count_empty(Scope::Stream);
|
let stream_empty = self.check_pattern_count_empty(Scope::Stream);
|
||||||
|
|
||||||
let concert = must_match_if_true!(!concert_empty => media_collection|MediaCollection::Concert(concert) => concert.clone()).unwrap_or_default();
|
let concert = must_match_if_true!(!concert_empty => media_collection|MediaCollection::Concert(concert) => concert.clone()).unwrap_or_default();
|
||||||
let stream = must_match_if_true!(!stream_empty => media_collection|MediaCollection::Concert(concert) => concert.stream().await?).unwrap_or_default();
|
let stream = must_match_if_true!(!stream_empty => media_collection|MediaCollection::Concert(concert) => concert.stream_maybe_without_drm().await?).unwrap_or_default();
|
||||||
|
|
||||||
let concert_map = self.serializable_to_json_map(FormatConcert::from(&concert));
|
let concert_map = self.serializable_to_json_map(FormatConcert::from(&concert));
|
||||||
let stream_map = self.serializable_to_json_map(FormatStream::from(&stream));
|
let stream_map = self.serializable_to_json_map(FormatStream::from(&stream));
|
||||||
|
|
|
||||||
|
|
@ -1,26 +1,31 @@
|
||||||
use crate::utils::ffmpeg::FFmpegPreset;
|
use crate::utils::ffmpeg::FFmpegPreset;
|
||||||
use crate::utils::filter::real_dedup_vec;
|
use crate::utils::filter::real_dedup_vec;
|
||||||
|
use crate::utils::fmt::format_time_delta;
|
||||||
|
use crate::utils::log::progress;
|
||||||
use crate::utils::os::{cache_dir, is_special_file, temp_directory, temp_named_pipe, tempfile};
|
use crate::utils::os::{cache_dir, is_special_file, temp_directory, temp_named_pipe, tempfile};
|
||||||
use crate::utils::rate_limit::RateLimiterService;
|
use crate::utils::rate_limit::RateLimiterService;
|
||||||
|
use crate::utils::sync::{sync_audios, SyncAudio};
|
||||||
use anyhow::{bail, Result};
|
use anyhow::{bail, Result};
|
||||||
use chrono::NaiveTime;
|
use chrono::{NaiveTime, TimeDelta};
|
||||||
use crunchyroll_rs::media::{SkipEvents, SkipEventsEvent, Subtitle, VariantData, VariantSegment};
|
use crunchyroll_rs::media::{SkipEvents, SkipEventsEvent, StreamData, StreamSegment, Subtitle};
|
||||||
use crunchyroll_rs::Locale;
|
use crunchyroll_rs::Locale;
|
||||||
use indicatif::{ProgressBar, ProgressDrawTarget, ProgressFinish, ProgressStyle};
|
use indicatif::{ProgressBar, ProgressDrawTarget, ProgressFinish, ProgressStyle};
|
||||||
use log::{debug, warn, LevelFilter};
|
use log::{debug, warn, LevelFilter};
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
|
use rsubs_lib::{SSA, VTT};
|
||||||
use std::borrow::Borrow;
|
use std::borrow::Borrow;
|
||||||
use std::cmp::Ordering;
|
use std::cmp::Ordering;
|
||||||
use std::collections::{BTreeMap, HashMap};
|
use std::collections::{BTreeMap, HashMap};
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
|
use std::ops::Add;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::process::{Command, Stdio};
|
use std::process::{Command, Stdio};
|
||||||
use std::str::FromStr;
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use std::{env, fs};
|
use std::{env, fs};
|
||||||
use tempfile::TempPath;
|
use tempfile::TempPath;
|
||||||
|
use time::Time;
|
||||||
use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
|
use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
|
||||||
use tokio::select;
|
use tokio::select;
|
||||||
use tokio::sync::mpsc::unbounded_channel;
|
use tokio::sync::mpsc::unbounded_channel;
|
||||||
|
|
@ -34,6 +39,7 @@ pub enum MergeBehavior {
|
||||||
Video,
|
Video,
|
||||||
Audio,
|
Audio,
|
||||||
Auto,
|
Auto,
|
||||||
|
Sync,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MergeBehavior {
|
impl MergeBehavior {
|
||||||
|
|
@ -42,6 +48,7 @@ impl MergeBehavior {
|
||||||
"video" => MergeBehavior::Video,
|
"video" => MergeBehavior::Video,
|
||||||
"audio" => MergeBehavior::Audio,
|
"audio" => MergeBehavior::Audio,
|
||||||
"auto" => MergeBehavior::Auto,
|
"auto" => MergeBehavior::Auto,
|
||||||
|
"sync" => MergeBehavior::Sync,
|
||||||
_ => return Err(format!("'{}' is not a valid merge behavior", s)),
|
_ => return Err(format!("'{}' is not a valid merge behavior", s)),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -59,6 +66,8 @@ pub struct DownloadBuilder {
|
||||||
force_hardsub: bool,
|
force_hardsub: bool,
|
||||||
download_fonts: bool,
|
download_fonts: bool,
|
||||||
no_closed_caption: bool,
|
no_closed_caption: bool,
|
||||||
|
merge_sync_tolerance: Option<u32>,
|
||||||
|
merge_sync_precision: Option<u32>,
|
||||||
threads: usize,
|
threads: usize,
|
||||||
ffmpeg_threads: Option<usize>,
|
ffmpeg_threads: Option<usize>,
|
||||||
audio_locale_output_map: HashMap<Locale, String>,
|
audio_locale_output_map: HashMap<Locale, String>,
|
||||||
|
|
@ -78,6 +87,8 @@ impl DownloadBuilder {
|
||||||
force_hardsub: false,
|
force_hardsub: false,
|
||||||
download_fonts: false,
|
download_fonts: false,
|
||||||
no_closed_caption: false,
|
no_closed_caption: false,
|
||||||
|
merge_sync_tolerance: None,
|
||||||
|
merge_sync_precision: None,
|
||||||
threads: num_cpus::get(),
|
threads: num_cpus::get(),
|
||||||
ffmpeg_threads: None,
|
ffmpeg_threads: None,
|
||||||
audio_locale_output_map: HashMap::new(),
|
audio_locale_output_map: HashMap::new(),
|
||||||
|
|
@ -99,6 +110,9 @@ impl DownloadBuilder {
|
||||||
download_fonts: self.download_fonts,
|
download_fonts: self.download_fonts,
|
||||||
no_closed_caption: self.no_closed_caption,
|
no_closed_caption: self.no_closed_caption,
|
||||||
|
|
||||||
|
merge_sync_tolerance: self.merge_sync_tolerance,
|
||||||
|
merge_sync_precision: self.merge_sync_precision,
|
||||||
|
|
||||||
download_threads: self.threads,
|
download_threads: self.threads,
|
||||||
ffmpeg_threads: self.ffmpeg_threads,
|
ffmpeg_threads: self.ffmpeg_threads,
|
||||||
|
|
||||||
|
|
@ -110,15 +124,30 @@ impl DownloadBuilder {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct FFmpegMeta {
|
struct FFmpegVideoMeta {
|
||||||
path: TempPath,
|
path: TempPath,
|
||||||
language: Locale,
|
length: TimeDelta,
|
||||||
title: String,
|
start_time: Option<TimeDelta>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct FFmpegAudioMeta {
|
||||||
|
path: TempPath,
|
||||||
|
locale: Locale,
|
||||||
|
start_time: Option<TimeDelta>,
|
||||||
|
video_idx: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct FFmpegSubtitleMeta {
|
||||||
|
path: TempPath,
|
||||||
|
locale: Locale,
|
||||||
|
cc: bool,
|
||||||
|
start_time: Option<TimeDelta>,
|
||||||
|
video_idx: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct DownloadFormat {
|
pub struct DownloadFormat {
|
||||||
pub video: (VariantData, Locale),
|
pub video: (StreamData, Locale),
|
||||||
pub audios: Vec<(VariantData, Locale)>,
|
pub audios: Vec<(StreamData, Locale)>,
|
||||||
pub subtitles: Vec<(Subtitle, bool)>,
|
pub subtitles: Vec<(Subtitle, bool)>,
|
||||||
pub metadata: DownloadFormatMetadata,
|
pub metadata: DownloadFormatMetadata,
|
||||||
}
|
}
|
||||||
|
|
@ -141,6 +170,9 @@ pub struct Downloader {
|
||||||
download_fonts: bool,
|
download_fonts: bool,
|
||||||
no_closed_caption: bool,
|
no_closed_caption: bool,
|
||||||
|
|
||||||
|
merge_sync_tolerance: Option<u32>,
|
||||||
|
merge_sync_precision: Option<u32>,
|
||||||
|
|
||||||
download_threads: usize,
|
download_threads: usize,
|
||||||
ffmpeg_threads: Option<usize>,
|
ffmpeg_threads: Option<usize>,
|
||||||
|
|
||||||
|
|
@ -202,13 +234,13 @@ impl Downloader {
|
||||||
if let Some(subtitle_sort) = &self.subtitle_sort {
|
if let Some(subtitle_sort) = &self.subtitle_sort {
|
||||||
format
|
format
|
||||||
.subtitles
|
.subtitles
|
||||||
.sort_by(|(a_subtitle, a_not_cc), (b_subtitle, b_not_cc)| {
|
.sort_by(|(a_subtitle, a_cc), (b_subtitle, b_cc)| {
|
||||||
let ordering = subtitle_sort
|
let ordering = subtitle_sort
|
||||||
.iter()
|
.iter()
|
||||||
.position(|l| l == &a_subtitle.locale)
|
.position(|l| l == &a_subtitle.locale)
|
||||||
.cmp(&subtitle_sort.iter().position(|l| l == &b_subtitle.locale));
|
.cmp(&subtitle_sort.iter().position(|l| l == &b_subtitle.locale));
|
||||||
if matches!(ordering, Ordering::Equal) {
|
if matches!(ordering, Ordering::Equal) {
|
||||||
a_not_cc.cmp(b_not_cc).reverse()
|
a_cc.cmp(b_cc).reverse()
|
||||||
} else {
|
} else {
|
||||||
ordering
|
ordering
|
||||||
}
|
}
|
||||||
|
|
@ -216,13 +248,17 @@ impl Downloader {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let mut video_offset = None;
|
||||||
|
let mut audio_offsets = HashMap::new();
|
||||||
|
let mut subtitle_offsets = HashMap::new();
|
||||||
|
let mut raw_audios = vec![];
|
||||||
let mut videos = vec![];
|
let mut videos = vec![];
|
||||||
let mut audios = vec![];
|
let mut audios = vec![];
|
||||||
let mut subtitles = vec![];
|
let mut subtitles = vec![];
|
||||||
let mut fonts = vec![];
|
let mut fonts = vec![];
|
||||||
let mut chapters = None;
|
let mut chapters = None;
|
||||||
let mut max_len = NaiveTime::MIN;
|
let mut max_len = TimeDelta::min_value();
|
||||||
let mut max_frames = 0f64;
|
let mut max_frames = 0;
|
||||||
let fmt_space = self
|
let fmt_space = self
|
||||||
.formats
|
.formats
|
||||||
.iter()
|
.iter()
|
||||||
|
|
@ -234,41 +270,159 @@ impl Downloader {
|
||||||
.max()
|
.max()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
|
// downloads all audios
|
||||||
for (i, format) in self.formats.iter().enumerate() {
|
for (i, format) in self.formats.iter().enumerate() {
|
||||||
let video_path = self
|
for (stream_data, locale) in &format.audios {
|
||||||
.download_video(
|
let path = self
|
||||||
&format.video.0,
|
|
||||||
format!("{:<1$}", format!("Downloading video #{}", i + 1), fmt_space),
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
for (variant_data, locale) in format.audios.iter() {
|
|
||||||
let audio_path = self
|
|
||||||
.download_audio(
|
.download_audio(
|
||||||
variant_data,
|
stream_data,
|
||||||
format!("{:<1$}", format!("Downloading {} audio", locale), fmt_space),
|
format!("{:<1$}", format!("Downloading {} audio", locale), fmt_space),
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
audios.push(FFmpegMeta {
|
raw_audios.push(SyncAudio {
|
||||||
path: audio_path,
|
format_id: i,
|
||||||
language: locale.clone(),
|
path,
|
||||||
title: if i == 0 {
|
locale: locale.clone(),
|
||||||
locale.to_human_readable()
|
sample_rate: stream_data.sampling_rate().unwrap(),
|
||||||
|
video_idx: i,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.formats.len() > 1 && self.merge_sync_tolerance.is_some() {
|
||||||
|
let _progress_handler =
|
||||||
|
progress!("Syncing video start times (this might take some time)");
|
||||||
|
let mut offsets = sync_audios(
|
||||||
|
&raw_audios,
|
||||||
|
self.merge_sync_tolerance.unwrap(),
|
||||||
|
self.merge_sync_precision.unwrap(),
|
||||||
|
)?;
|
||||||
|
drop(_progress_handler);
|
||||||
|
|
||||||
|
let mut offset_pre_checked = false;
|
||||||
|
if let Some(tmp_offsets) = &offsets {
|
||||||
|
let formats_with_offset: Vec<TimeDelta> = self
|
||||||
|
.formats
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, f)| {
|
||||||
|
len_from_segments(&f.video.0.segments())
|
||||||
|
- tmp_offsets.get(&i).copied().unwrap_or_default()
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let min = formats_with_offset.iter().min().unwrap();
|
||||||
|
let max = formats_with_offset.iter().max().unwrap();
|
||||||
|
|
||||||
|
if max.num_seconds() - min.num_seconds() > 15 {
|
||||||
|
warn!("Found difference of >15 seconds after sync, so the application was skipped");
|
||||||
|
offsets = None;
|
||||||
|
offset_pre_checked = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(offsets) = offsets {
|
||||||
|
let mut root_format_idx = 0;
|
||||||
|
let mut root_format_offset = u64::MAX;
|
||||||
|
|
||||||
|
for (i, format) in self.formats.iter().enumerate() {
|
||||||
|
let offset = offsets.get(&i).copied().unwrap_or_default();
|
||||||
|
let format_offset = offset.num_milliseconds() as u64;
|
||||||
|
if format_offset < root_format_offset {
|
||||||
|
root_format_idx = i;
|
||||||
|
root_format_offset = format_offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
for _ in &format.audios {
|
||||||
|
if let Some(offset) = &offsets.get(&i) {
|
||||||
|
audio_offsets.insert(i, **offset);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _ in &format.subtitles {
|
||||||
|
if let Some(offset) = &offsets.get(&i) {
|
||||||
|
subtitle_offsets.insert(i, **offset);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut root_format = self.formats.remove(root_format_idx);
|
||||||
|
|
||||||
|
let mut audio_prepend = vec![];
|
||||||
|
let mut subtitle_prepend = vec![];
|
||||||
|
let mut audio_append = vec![];
|
||||||
|
let mut subtitle_append = vec![];
|
||||||
|
for (i, format) in self.formats.into_iter().enumerate() {
|
||||||
|
if i < root_format_idx {
|
||||||
|
audio_prepend.extend(format.audios);
|
||||||
|
subtitle_prepend.extend(format.subtitles);
|
||||||
} else {
|
} else {
|
||||||
format!("{} [Video: #{}]", locale.to_human_readable(), i + 1)
|
audio_append.extend(format.audios);
|
||||||
},
|
subtitle_append.extend(format.subtitles);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
root_format.audios.splice(0..0, audio_prepend);
|
||||||
|
root_format.subtitles.splice(0..0, subtitle_prepend);
|
||||||
|
root_format.audios.extend(audio_append);
|
||||||
|
root_format.subtitles.extend(subtitle_append);
|
||||||
|
|
||||||
|
self.formats = vec![root_format];
|
||||||
|
video_offset = offsets.get(&root_format_idx).copied();
|
||||||
|
for raw_audio in raw_audios.iter_mut() {
|
||||||
|
raw_audio.video_idx = root_format_idx;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for format in &mut self.formats {
|
||||||
|
format.metadata.skip_events = None
|
||||||
|
}
|
||||||
|
if !offset_pre_checked {
|
||||||
|
warn!("Couldn't find reliable sync positions")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// add audio metadata
|
||||||
|
for raw_audio in raw_audios {
|
||||||
|
audios.push(FFmpegAudioMeta {
|
||||||
|
path: raw_audio.path,
|
||||||
|
locale: raw_audio.locale,
|
||||||
|
start_time: audio_offsets.get(&raw_audio.format_id).copied(),
|
||||||
|
video_idx: raw_audio.video_idx,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
let (len, fps) = get_video_stats(&video_path)?;
|
// downloads all videos
|
||||||
|
for (i, format) in self.formats.iter().enumerate() {
|
||||||
|
let path = self
|
||||||
|
.download_video(
|
||||||
|
&format.video.0,
|
||||||
|
format!("{:<1$}", format!("Downloading video #{}", i + 1), fmt_space),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let (len, fps) = get_video_stats(&path)?;
|
||||||
if max_len < len {
|
if max_len < len {
|
||||||
max_len = len
|
max_len = len
|
||||||
}
|
}
|
||||||
let frames = len.signed_duration_since(NaiveTime::MIN).num_seconds() as f64 * fps;
|
let frames = ((len.num_milliseconds() as f64
|
||||||
if frames > max_frames {
|
- video_offset.unwrap_or_default().num_milliseconds() as f64)
|
||||||
max_frames = frames;
|
/ 1000.0
|
||||||
|
* fps) as u64;
|
||||||
|
if max_frames < frames {
|
||||||
|
max_frames = frames
|
||||||
|
}
|
||||||
|
|
||||||
|
videos.push(FFmpegVideoMeta {
|
||||||
|
path,
|
||||||
|
length: len,
|
||||||
|
start_time: video_offset,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
for (i, format) in self.formats.iter().enumerate() {
|
||||||
|
if format.subtitles.is_empty() {
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if !format.subtitles.is_empty() {
|
|
||||||
let progress_spinner = if log::max_level() == LevelFilter::Info {
|
let progress_spinner = if log::max_level() == LevelFilter::Info {
|
||||||
let progress_spinner = ProgressBar::new_spinner()
|
let progress_spinner = ProgressBar::new_spinner()
|
||||||
.with_style(
|
.with_style(
|
||||||
|
|
@ -289,8 +443,8 @@ impl Downloader {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
|
||||||
for (subtitle, not_cc) in format.subtitles.iter() {
|
for (j, (subtitle, cc)) in format.subtitles.iter().enumerate() {
|
||||||
if !not_cc && self.no_closed_caption {
|
if *cc && self.no_closed_caption {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -300,49 +454,34 @@ impl Downloader {
|
||||||
progress_message += ", "
|
progress_message += ", "
|
||||||
}
|
}
|
||||||
progress_message += &subtitle.locale.to_string();
|
progress_message += &subtitle.locale.to_string();
|
||||||
if !not_cc {
|
if *cc {
|
||||||
progress_message += " (CC)";
|
progress_message += " (CC)";
|
||||||
}
|
}
|
||||||
if i != 0 {
|
if i.min(videos.len() - 1) != 0 {
|
||||||
progress_message += &format!(" [Video: #{}]", i + 1);
|
progress_message += &format!(" [Video: #{}]", i + 1);
|
||||||
}
|
}
|
||||||
pb.set_message(progress_message)
|
pb.set_message(progress_message)
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut subtitle_title = subtitle.locale.to_human_readable();
|
let path = self
|
||||||
if !not_cc {
|
.download_subtitle(subtitle.clone(), videos[i.min(videos.len() - 1)].length)
|
||||||
subtitle_title += " (CC)"
|
.await?;
|
||||||
}
|
|
||||||
if i != 0 {
|
|
||||||
subtitle_title += &format!(" [Video: #{}]", i + 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
let subtitle_path = self.download_subtitle(subtitle.clone(), len).await?;
|
|
||||||
debug!(
|
debug!(
|
||||||
"Downloaded {} subtitles{}{}",
|
"Downloaded {} subtitles{}",
|
||||||
subtitle.locale,
|
subtitle.locale,
|
||||||
(!not_cc).then_some(" (cc)").unwrap_or_default(),
|
cc.then_some(" (cc)").unwrap_or_default(),
|
||||||
(i != 0)
|
|
||||||
.then_some(format!(" for video {}", i))
|
|
||||||
.unwrap_or_default()
|
|
||||||
);
|
);
|
||||||
subtitles.push(FFmpegMeta {
|
subtitles.push(FFmpegSubtitleMeta {
|
||||||
path: subtitle_path,
|
path,
|
||||||
language: subtitle.locale.clone(),
|
locale: subtitle.locale.clone(),
|
||||||
title: subtitle_title,
|
cc: *cc,
|
||||||
|
start_time: subtitle_offsets.get(&j).cloned(),
|
||||||
|
video_idx: i,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
videos.push(FFmpegMeta {
|
|
||||||
path: video_path,
|
|
||||||
language: format.video.1.clone(),
|
|
||||||
title: if self.formats.len() == 1 {
|
|
||||||
"Default".to_string()
|
|
||||||
} else {
|
|
||||||
format!("#{}", i + 1)
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
|
for format in self.formats.iter() {
|
||||||
if let Some(skip_events) = &format.metadata.skip_events {
|
if let Some(skip_events) = &format.metadata.skip_events {
|
||||||
let (file, path) = tempfile(".chapter")?.into_parts();
|
let (file, path) = tempfile(".chapter")?.into_parts();
|
||||||
chapters = Some((
|
chapters = Some((
|
||||||
|
|
@ -421,17 +560,30 @@ impl Downloader {
|
||||||
let mut metadata = vec![];
|
let mut metadata = vec![];
|
||||||
|
|
||||||
for (i, meta) in videos.iter().enumerate() {
|
for (i, meta) in videos.iter().enumerate() {
|
||||||
|
if let Some(start_time) = meta.start_time {
|
||||||
|
input.extend(["-itsoffset".to_string(), format_time_delta(&start_time)])
|
||||||
|
}
|
||||||
input.extend(["-i".to_string(), meta.path.to_string_lossy().to_string()]);
|
input.extend(["-i".to_string(), meta.path.to_string_lossy().to_string()]);
|
||||||
maps.extend(["-map".to_string(), i.to_string()]);
|
maps.extend(["-map".to_string(), i.to_string()]);
|
||||||
metadata.extend([
|
metadata.extend([
|
||||||
format!("-metadata:s:v:{}", i),
|
format!("-metadata:s:v:{}", i),
|
||||||
format!("title={}", meta.title),
|
format!(
|
||||||
|
"title={}",
|
||||||
|
if videos.len() == 1 {
|
||||||
|
"Default".to_string()
|
||||||
|
} else {
|
||||||
|
format!("#{}", i + 1)
|
||||||
|
}
|
||||||
|
),
|
||||||
]);
|
]);
|
||||||
// the empty language metadata is created to avoid that metadata from the original track
|
// the empty language metadata is created to avoid that metadata from the original track
|
||||||
// is copied
|
// is copied
|
||||||
metadata.extend([format!("-metadata:s:v:{}", i), "language=".to_string()])
|
metadata.extend([format!("-metadata:s:v:{}", i), "language=".to_string()])
|
||||||
}
|
}
|
||||||
for (i, meta) in audios.iter().enumerate() {
|
for (i, meta) in audios.iter().enumerate() {
|
||||||
|
if let Some(start_time) = meta.start_time {
|
||||||
|
input.extend(["-itsoffset".to_string(), format_time_delta(&start_time)])
|
||||||
|
}
|
||||||
input.extend(["-i".to_string(), meta.path.to_string_lossy().to_string()]);
|
input.extend(["-i".to_string(), meta.path.to_string_lossy().to_string()]);
|
||||||
maps.extend(["-map".to_string(), (i + videos.len()).to_string()]);
|
maps.extend(["-map".to_string(), (i + videos.len()).to_string()]);
|
||||||
metadata.extend([
|
metadata.extend([
|
||||||
|
|
@ -439,13 +591,24 @@ impl Downloader {
|
||||||
format!(
|
format!(
|
||||||
"language={}",
|
"language={}",
|
||||||
self.audio_locale_output_map
|
self.audio_locale_output_map
|
||||||
.get(&meta.language)
|
.get(&meta.locale)
|
||||||
.unwrap_or(&meta.language.to_string())
|
.unwrap_or(&meta.locale.to_string())
|
||||||
),
|
),
|
||||||
]);
|
]);
|
||||||
metadata.extend([
|
metadata.extend([
|
||||||
format!("-metadata:s:a:{}", i),
|
format!("-metadata:s:a:{}", i),
|
||||||
format!("title={}", meta.title),
|
format!(
|
||||||
|
"title={}",
|
||||||
|
if videos.len() == 1 {
|
||||||
|
meta.locale.to_human_readable()
|
||||||
|
} else {
|
||||||
|
format!(
|
||||||
|
"{} [Video: #{}]",
|
||||||
|
meta.locale.to_human_readable(),
|
||||||
|
meta.video_idx + 1
|
||||||
|
)
|
||||||
|
}
|
||||||
|
),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -465,6 +628,9 @@ impl Downloader {
|
||||||
|
|
||||||
if container_supports_softsubs {
|
if container_supports_softsubs {
|
||||||
for (i, meta) in subtitles.iter().enumerate() {
|
for (i, meta) in subtitles.iter().enumerate() {
|
||||||
|
if let Some(start_time) = meta.start_time {
|
||||||
|
input.extend(["-itsoffset".to_string(), format_time_delta(&start_time)])
|
||||||
|
}
|
||||||
input.extend(["-i".to_string(), meta.path.to_string_lossy().to_string()]);
|
input.extend(["-i".to_string(), meta.path.to_string_lossy().to_string()]);
|
||||||
maps.extend([
|
maps.extend([
|
||||||
"-map".to_string(),
|
"-map".to_string(),
|
||||||
|
|
@ -475,13 +641,22 @@ impl Downloader {
|
||||||
format!(
|
format!(
|
||||||
"language={}",
|
"language={}",
|
||||||
self.subtitle_locale_output_map
|
self.subtitle_locale_output_map
|
||||||
.get(&meta.language)
|
.get(&meta.locale)
|
||||||
.unwrap_or(&meta.language.to_string())
|
.unwrap_or(&meta.locale.to_string())
|
||||||
),
|
),
|
||||||
]);
|
]);
|
||||||
metadata.extend([
|
metadata.extend([
|
||||||
format!("-metadata:s:s:{}", i),
|
format!("-metadata:s:s:{}", i),
|
||||||
format!("title={}", meta.title),
|
format!("title={}", {
|
||||||
|
let mut title = meta.locale.to_human_readable();
|
||||||
|
if meta.cc {
|
||||||
|
title += " (CC)"
|
||||||
|
}
|
||||||
|
if videos.len() > 1 {
|
||||||
|
title += &format!(" [Video: #{}]", meta.video_idx + 1)
|
||||||
|
}
|
||||||
|
title
|
||||||
|
}),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -523,10 +698,7 @@ impl Downloader {
|
||||||
|
|
||||||
// set default subtitle
|
// set default subtitle
|
||||||
if let Some(default_subtitle) = self.default_subtitle {
|
if let Some(default_subtitle) = self.default_subtitle {
|
||||||
if let Some(position) = subtitles
|
if let Some(position) = subtitles.iter().position(|m| m.locale == default_subtitle) {
|
||||||
.iter()
|
|
||||||
.position(|m| m.language == default_subtitle)
|
|
||||||
{
|
|
||||||
if container_supports_softsubs {
|
if container_supports_softsubs {
|
||||||
match dst.extension().unwrap_or_default().to_str().unwrap() {
|
match dst.extension().unwrap_or_default().to_str().unwrap() {
|
||||||
"mov" | "mp4" => output_presets.extend([
|
"mov" | "mp4" => output_presets.extend([
|
||||||
|
|
@ -550,7 +722,7 @@ impl Downloader {
|
||||||
output_presets.remove(i - remove_count);
|
output_presets.remove(i - remove_count);
|
||||||
remove_count += 1;
|
remove_count += 1;
|
||||||
}
|
}
|
||||||
last = s.clone();
|
last.clone_from(s);
|
||||||
}
|
}
|
||||||
|
|
||||||
output_presets.extend([
|
output_presets.extend([
|
||||||
|
|
@ -585,7 +757,7 @@ impl Downloader {
|
||||||
if container_supports_softsubs {
|
if container_supports_softsubs {
|
||||||
if let Some(position) = subtitles
|
if let Some(position) = subtitles
|
||||||
.iter()
|
.iter()
|
||||||
.position(|meta| meta.language == default_subtitle)
|
.position(|meta| meta.locale == default_subtitle)
|
||||||
{
|
{
|
||||||
command_args.extend([
|
command_args.extend([
|
||||||
format!("-disposition:s:s:{}", position),
|
format!("-disposition:s:s:{}", position),
|
||||||
|
|
@ -597,9 +769,7 @@ impl Downloader {
|
||||||
|
|
||||||
// set the 'forced' flag to CC subtitles
|
// set the 'forced' flag to CC subtitles
|
||||||
for (i, subtitle) in subtitles.iter().enumerate() {
|
for (i, subtitle) in subtitles.iter().enumerate() {
|
||||||
// well, checking if the title contains '(CC)' might not be the best solutions from a
|
if !subtitle.cc {
|
||||||
// performance perspective but easier than adjusting the `FFmpegMeta` struct
|
|
||||||
if !subtitle.title.contains("(CC)") {
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -628,7 +798,7 @@ impl Downloader {
|
||||||
// create parent directory if it does not exist
|
// create parent directory if it does not exist
|
||||||
if let Some(parent) = dst.parent() {
|
if let Some(parent) = dst.parent() {
|
||||||
if !parent.exists() {
|
if !parent.exists() {
|
||||||
std::fs::create_dir_all(parent)?
|
fs::create_dir_all(parent)?
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -646,7 +816,7 @@ impl Downloader {
|
||||||
let ffmpeg_progress_cancellation_token = ffmpeg_progress_cancel.clone();
|
let ffmpeg_progress_cancellation_token = ffmpeg_progress_cancel.clone();
|
||||||
let ffmpeg_progress = tokio::spawn(async move {
|
let ffmpeg_progress = tokio::spawn(async move {
|
||||||
ffmpeg_progress(
|
ffmpeg_progress(
|
||||||
max_frames as u64,
|
max_frames,
|
||||||
fifo,
|
fifo,
|
||||||
format!("{:<1$}", "Generating output file", fmt_space + 1),
|
format!("{:<1$}", "Generating output file", fmt_space + 1),
|
||||||
ffmpeg_progress_cancellation_token,
|
ffmpeg_progress_cancellation_token,
|
||||||
|
|
@ -667,20 +837,17 @@ impl Downloader {
|
||||||
&self,
|
&self,
|
||||||
dst: &Path,
|
dst: &Path,
|
||||||
) -> Result<(Option<(PathBuf, u64)>, Option<(PathBuf, u64)>)> {
|
) -> Result<(Option<(PathBuf, u64)>, Option<(PathBuf, u64)>)> {
|
||||||
let mut all_variant_data = vec![];
|
let mut all_stream_data = vec![];
|
||||||
for format in &self.formats {
|
for format in &self.formats {
|
||||||
all_variant_data.push(&format.video.0);
|
all_stream_data.push(&format.video.0);
|
||||||
all_variant_data.extend(format.audios.iter().map(|(a, _)| a))
|
all_stream_data.extend(format.audios.iter().map(|(a, _)| a))
|
||||||
}
|
}
|
||||||
let mut estimated_required_space: u64 = 0;
|
let mut estimated_required_space: u64 = 0;
|
||||||
for variant_data in all_variant_data {
|
for stream_data in all_stream_data {
|
||||||
// nearly no overhead should be generated with this call(s) as we're using dash as
|
let segments = stream_data.segments();
|
||||||
// stream provider and generating the dash segments does not need any fetching of
|
|
||||||
// additional (http) resources as hls segments would
|
|
||||||
let segments = variant_data.segments().await?;
|
|
||||||
|
|
||||||
// sum the length of all streams up
|
// sum the length of all streams up
|
||||||
estimated_required_space += estimate_variant_file_size(variant_data, &segments);
|
estimated_required_space += estimate_stream_data_file_size(stream_data, &segments);
|
||||||
}
|
}
|
||||||
|
|
||||||
let tmp_stat = fs2::statvfs(temp_directory()).unwrap();
|
let tmp_stat = fs2::statvfs(temp_directory()).unwrap();
|
||||||
|
|
@ -728,27 +895,24 @@ impl Downloader {
|
||||||
|
|
||||||
async fn download_video(
|
async fn download_video(
|
||||||
&self,
|
&self,
|
||||||
variant_data: &VariantData,
|
stream_data: &StreamData,
|
||||||
message: String,
|
message: String,
|
||||||
|
max_segments: Option<usize>,
|
||||||
) -> Result<TempPath> {
|
) -> Result<TempPath> {
|
||||||
let tempfile = tempfile(".mp4")?;
|
let tempfile = tempfile(".mp4")?;
|
||||||
let (mut file, path) = tempfile.into_parts();
|
let (mut file, path) = tempfile.into_parts();
|
||||||
|
|
||||||
self.download_segments(&mut file, message, variant_data)
|
self.download_segments(&mut file, message, stream_data, max_segments)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok(path)
|
Ok(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn download_audio(
|
async fn download_audio(&self, stream_data: &StreamData, message: String) -> Result<TempPath> {
|
||||||
&self,
|
|
||||||
variant_data: &VariantData,
|
|
||||||
message: String,
|
|
||||||
) -> Result<TempPath> {
|
|
||||||
let tempfile = tempfile(".m4a")?;
|
let tempfile = tempfile(".m4a")?;
|
||||||
let (mut file, path) = tempfile.into_parts();
|
let (mut file, path) = tempfile.into_parts();
|
||||||
|
|
||||||
self.download_segments(&mut file, message, variant_data)
|
self.download_segments(&mut file, message, stream_data, None)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
Ok(path)
|
Ok(path)
|
||||||
|
|
@ -757,16 +921,47 @@ impl Downloader {
|
||||||
async fn download_subtitle(
|
async fn download_subtitle(
|
||||||
&self,
|
&self,
|
||||||
subtitle: Subtitle,
|
subtitle: Subtitle,
|
||||||
max_length: NaiveTime,
|
max_length: TimeDelta,
|
||||||
) -> Result<TempPath> {
|
) -> Result<TempPath> {
|
||||||
|
let buf = subtitle.data().await?;
|
||||||
|
let mut ass = match subtitle.format.as_str() {
|
||||||
|
"ass" => SSA::parse(String::from_utf8_lossy(&buf))?,
|
||||||
|
"vtt" => VTT::parse(String::from_utf8_lossy(&buf))?.to_ssa(),
|
||||||
|
_ => bail!("unknown subtitle format: {}", subtitle.format),
|
||||||
|
};
|
||||||
|
// subtitles aren't always correct sorted and video players may have issues with that. to
|
||||||
|
// prevent issues, the subtitles are sorted
|
||||||
|
// (https://github.com/crunchy-labs/crunchy-cli/issues/208)
|
||||||
|
ass.events.sort_by(|a, b| a.start.cmp(&b.start));
|
||||||
|
// it might be the case that the start and/or end time are greater than the actual video
|
||||||
|
// length. this might also result in issues with video players, thus the times are stripped
|
||||||
|
// to be at most as long as `max_length`
|
||||||
|
// (https://github.com/crunchy-labs/crunchy-cli/issues/32)
|
||||||
|
for i in (0..ass.events.len()).rev() {
|
||||||
|
let max_len = Time::from_hms(0, 0, 0)
|
||||||
|
.unwrap()
|
||||||
|
.add(Duration::from_millis(max_length.num_milliseconds() as u64));
|
||||||
|
|
||||||
|
if ass.events[i].start > max_len {
|
||||||
|
if ass.events[i].end > max_len {
|
||||||
|
ass.events[i].start = max_len
|
||||||
|
}
|
||||||
|
ass.events[i].end = max_len
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// without this additional info, subtitle look very messy in some video player
|
||||||
|
// (https://github.com/crunchy-labs/crunchy-cli/issues/66)
|
||||||
|
ass.info
|
||||||
|
.additional_fields
|
||||||
|
.insert("ScaledBorderAndShadow".to_string(), "yes".to_string());
|
||||||
|
|
||||||
let tempfile = tempfile(".ass")?;
|
let tempfile = tempfile(".ass")?;
|
||||||
let (mut file, path) = tempfile.into_parts();
|
let path = tempfile.into_temp_path();
|
||||||
|
|
||||||
let mut buf = vec![];
|
fs::write(&path, ass.to_string())?;
|
||||||
subtitle.write_to(&mut buf).await?;
|
|
||||||
fix_subtitles(&mut buf, max_length);
|
|
||||||
|
|
||||||
file.write_all(buf.as_slice())?;
|
|
||||||
|
|
||||||
Ok(path)
|
Ok(path)
|
||||||
}
|
}
|
||||||
|
|
@ -802,15 +997,21 @@ impl Downloader {
|
||||||
&self,
|
&self,
|
||||||
writer: &mut impl Write,
|
writer: &mut impl Write,
|
||||||
message: String,
|
message: String,
|
||||||
variant_data: &VariantData,
|
stream_data: &StreamData,
|
||||||
|
max_segments: Option<usize>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let segments = variant_data.segments().await?;
|
let mut segments = stream_data.segments();
|
||||||
|
if let Some(max_segments) = max_segments {
|
||||||
|
segments = segments
|
||||||
|
.drain(0..max_segments.min(segments.len() - 1))
|
||||||
|
.collect();
|
||||||
|
}
|
||||||
let total_segments = segments.len();
|
let total_segments = segments.len();
|
||||||
|
|
||||||
let count = Arc::new(Mutex::new(0));
|
let count = Arc::new(Mutex::new(0));
|
||||||
|
|
||||||
let progress = if log::max_level() == LevelFilter::Info {
|
let progress = if log::max_level() == LevelFilter::Info {
|
||||||
let estimated_file_size = estimate_variant_file_size(variant_data, &segments);
|
let estimated_file_size = estimate_stream_data_file_size(stream_data, &segments);
|
||||||
|
|
||||||
let progress = ProgressBar::new(estimated_file_size)
|
let progress = ProgressBar::new(estimated_file_size)
|
||||||
.with_style(
|
.with_style(
|
||||||
|
|
@ -827,8 +1028,8 @@ impl Downloader {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
|
||||||
let cpus = self.download_threads;
|
let cpus = self.download_threads.min(segments.len());
|
||||||
let mut segs: Vec<Vec<VariantSegment>> = Vec::with_capacity(cpus);
|
let mut segs: Vec<Vec<StreamSegment>> = Vec::with_capacity(cpus);
|
||||||
for _ in 0..cpus {
|
for _ in 0..cpus {
|
||||||
segs.push(vec![])
|
segs.push(vec![])
|
||||||
}
|
}
|
||||||
|
|
@ -854,7 +1055,7 @@ impl Downloader {
|
||||||
let download = || async move {
|
let download = || async move {
|
||||||
for (i, segment) in thread_segments.into_iter().enumerate() {
|
for (i, segment) in thread_segments.into_iter().enumerate() {
|
||||||
let mut retry_count = 0;
|
let mut retry_count = 0;
|
||||||
let mut buf = loop {
|
let buf = loop {
|
||||||
let request = thread_client
|
let request = thread_client
|
||||||
.get(&segment.url)
|
.get(&segment.url)
|
||||||
.timeout(Duration::from_secs(60));
|
.timeout(Duration::from_secs(60));
|
||||||
|
|
@ -880,11 +1081,9 @@ impl Downloader {
|
||||||
retry_count += 1;
|
retry_count += 1;
|
||||||
};
|
};
|
||||||
|
|
||||||
buf = VariantSegment::decrypt(&mut buf, segment.key)?.to_vec();
|
|
||||||
|
|
||||||
let mut c = thread_count.lock().await;
|
let mut c = thread_count.lock().await;
|
||||||
debug!(
|
debug!(
|
||||||
"Downloaded and decrypted segment [{}/{} {:.2}%] {}",
|
"Downloaded segment [{}/{} {:.2}%] {}",
|
||||||
num + (i * cpus) + 1,
|
num + (i * cpus) + 1,
|
||||||
total_segments,
|
total_segments,
|
||||||
((*c + 1) as f64 / total_segments as f64) * 100f64,
|
((*c + 1) as f64 / total_segments as f64) * 100f64,
|
||||||
|
|
@ -924,7 +1123,7 @@ impl Downloader {
|
||||||
|
|
||||||
if let Some(p) = &progress {
|
if let Some(p) = &progress {
|
||||||
let progress_len = p.length().unwrap();
|
let progress_len = p.length().unwrap();
|
||||||
let estimated_segment_len = (variant_data.bandwidth / 8)
|
let estimated_segment_len = (stream_data.bandwidth / 8)
|
||||||
* segments.get(pos as usize).unwrap().length.as_secs();
|
* segments.get(pos as usize).unwrap().length.as_secs();
|
||||||
let bytes_len = bytes.len() as u64;
|
let bytes_len = bytes.len() as u64;
|
||||||
|
|
||||||
|
|
@ -973,12 +1172,12 @@ impl Downloader {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn estimate_variant_file_size(variant_data: &VariantData, segments: &[VariantSegment]) -> u64 {
|
fn estimate_stream_data_file_size(stream_data: &StreamData, segments: &[StreamSegment]) -> u64 {
|
||||||
(variant_data.bandwidth / 8) * segments.iter().map(|s| s.length.as_secs()).sum::<u64>()
|
(stream_data.bandwidth / 8) * segments.iter().map(|s| s.length.as_secs()).sum::<u64>()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the length and fps of a video.
|
/// Get the length and fps of a video.
|
||||||
fn get_video_stats(path: &Path) -> Result<(NaiveTime, f64)> {
|
fn get_video_stats(path: &Path) -> Result<(TimeDelta, f64)> {
|
||||||
let video_length = Regex::new(r"Duration:\s(?P<time>\d+:\d+:\d+\.\d+),")?;
|
let video_length = Regex::new(r"Duration:\s(?P<time>\d+:\d+:\d+\.\d+),")?;
|
||||||
let video_fps = Regex::new(r"(?P<fps>[\d/.]+)\sfps")?;
|
let video_fps = Regex::new(r"(?P<fps>[\d/.]+)\sfps")?;
|
||||||
|
|
||||||
|
|
@ -1005,13 +1204,14 @@ fn get_video_stats(path: &Path) -> Result<(NaiveTime, f64)> {
|
||||||
|
|
||||||
Ok((
|
Ok((
|
||||||
NaiveTime::parse_from_str(length_caps.name("time").unwrap().as_str(), "%H:%M:%S%.f")
|
NaiveTime::parse_from_str(length_caps.name("time").unwrap().as_str(), "%H:%M:%S%.f")
|
||||||
.unwrap(),
|
.unwrap()
|
||||||
|
.signed_duration_since(NaiveTime::MIN),
|
||||||
fps_caps.name("fps").unwrap().as_str().parse().unwrap(),
|
fps_caps.name("fps").unwrap().as_str().parse().unwrap(),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
// all subtitle fonts (extracted from javascript)
|
// all subtitle fonts (extracted from javascript)
|
||||||
const FONTS: [(&str, &str); 66] = [
|
const FONTS: [(&str, &str); 68] = [
|
||||||
("Adobe Arabic", "AdobeArabic-Bold.woff2"),
|
("Adobe Arabic", "AdobeArabic-Bold.woff2"),
|
||||||
("Andale Mono", "andalemo.woff2"),
|
("Andale Mono", "andalemo.woff2"),
|
||||||
("Arial", "arial.woff2"),
|
("Arial", "arial.woff2"),
|
||||||
|
|
@ -1069,6 +1269,8 @@ const FONTS: [(&str, &str); 66] = [
|
||||||
("Impact", "impact.woff2"),
|
("Impact", "impact.woff2"),
|
||||||
("Mangal", "MANGAL.woff2"),
|
("Mangal", "MANGAL.woff2"),
|
||||||
("Meera Inimai", "MeeraInimai-Regular.woff2"),
|
("Meera Inimai", "MeeraInimai-Regular.woff2"),
|
||||||
|
("Noto Sans Tamil", "NotoSansTamil.woff2"),
|
||||||
|
("Noto Sans Telugu", "NotoSansTelegu.woff2"),
|
||||||
("Noto Sans Thai", "NotoSansThai.woff2"),
|
("Noto Sans Thai", "NotoSansThai.woff2"),
|
||||||
("Rubik", "Rubik-Regular.woff2"),
|
("Rubik", "Rubik-Regular.woff2"),
|
||||||
("Rubik Black", "Rubik-Black.woff2"),
|
("Rubik Black", "Rubik-Black.woff2"),
|
||||||
|
|
@ -1098,7 +1300,7 @@ const FONTS: [(&str, &str); 66] = [
|
||||||
("Webdings", "webdings.woff2"),
|
("Webdings", "webdings.woff2"),
|
||||||
];
|
];
|
||||||
lazy_static::lazy_static! {
|
lazy_static::lazy_static! {
|
||||||
static ref FONT_REGEX: Regex = Regex::new(r"(?m)^Style:\s.+?,(?P<font>.+?),").unwrap();
|
static ref FONT_REGEX: Regex = Regex::new(r"(?m)^(?:Style:\s.+?,(?P<font>.+?),|(?:Dialogue:\s(?:.+?,)+,\{(?:\\.*)?\\fn(?P<overrideFont>[\w\s]+)(?:\\.*)?)\})").unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get the fonts used in the subtitle.
|
/// Get the fonts used in the subtitle.
|
||||||
|
|
@ -1112,150 +1314,60 @@ fn get_subtitle_stats(path: &Path) -> Result<Vec<String>> {
|
||||||
fonts.push(font_string)
|
fonts.push(font_string)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if let Some(override_font) = capture.name("overrideFont") {
|
||||||
|
let font_string = override_font.as_str().to_string();
|
||||||
|
if !fonts.contains(&font_string) {
|
||||||
|
fonts.push(font_string)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(fonts)
|
Ok(fonts)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fix the subtitles in multiple ways as Crunchyroll sometimes delivers them malformed.
|
|
||||||
///
|
|
||||||
/// Look and feel fix: Add `ScaledBorderAndShadows: yes` to subtitles; without it they look very
|
|
||||||
/// messy on some video players. See
|
|
||||||
/// [crunchy-labs/crunchy-cli#66](https://github.com/crunchy-labs/crunchy-cli/issues/66) for more
|
|
||||||
/// information.
|
|
||||||
/// Length fix: Sometimes subtitles have an unnecessary long entry which exceeds the video length,
|
|
||||||
/// some video players can't handle this correctly. To prevent this, the subtitles must be checked
|
|
||||||
/// if any entry is longer than the video length and if so the entry ending must be hard set to not
|
|
||||||
/// exceed the video length. See [crunchy-labs/crunchy-cli#32](https://github.com/crunchy-labs/crunchy-cli/issues/32)
|
|
||||||
/// for more information.
|
|
||||||
/// Sort fix: Sometimes subtitle entries aren't sorted correctly by time which confuses some video
|
|
||||||
/// players. To prevent this, the subtitle entries must be manually sorted. See
|
|
||||||
/// [crunchy-labs/crunchy-cli#208](https://github.com/crunchy-labs/crunchy-cli/issues/208) for more
|
|
||||||
/// information.
|
|
||||||
fn fix_subtitles(raw: &mut Vec<u8>, max_length: NaiveTime) {
|
|
||||||
let re = Regex::new(
|
|
||||||
r"^Dialogue:\s(?P<layer>\d+),(?P<start>\d+:\d+:\d+\.\d+),(?P<end>\d+:\d+:\d+\.\d+),",
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
// chrono panics if we try to format NaiveTime with `%2f` and the nano seconds has more than 2
|
|
||||||
// digits so them have to be reduced manually to avoid the panic
|
|
||||||
fn format_naive_time(native_time: NaiveTime) -> String {
|
|
||||||
let formatted_time = native_time.format("%f").to_string();
|
|
||||||
format!(
|
|
||||||
"{}.{}",
|
|
||||||
native_time.format("%T"),
|
|
||||||
if formatted_time.len() <= 2 {
|
|
||||||
native_time.format("%2f").to_string()
|
|
||||||
} else {
|
|
||||||
formatted_time.split_at(2).0.parse().unwrap()
|
|
||||||
}
|
|
||||||
)
|
|
||||||
.split_off(1) // <- in the ASS spec, the hour has only one digit
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut entries = (vec![], vec![]);
|
|
||||||
|
|
||||||
let mut as_lines: Vec<String> = String::from_utf8_lossy(raw.as_slice())
|
|
||||||
.split('\n')
|
|
||||||
.map(|s| s.to_string())
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
for (i, line) in as_lines.iter_mut().enumerate() {
|
|
||||||
if line.trim() == "[Script Info]" {
|
|
||||||
line.push_str("\nScaledBorderAndShadow: yes")
|
|
||||||
} else if let Some(capture) = re.captures(line) {
|
|
||||||
let mut start = capture.name("start").map_or(NaiveTime::default(), |s| {
|
|
||||||
NaiveTime::parse_from_str(s.as_str(), "%H:%M:%S.%f").unwrap()
|
|
||||||
});
|
|
||||||
let mut end = capture.name("end").map_or(NaiveTime::default(), |e| {
|
|
||||||
NaiveTime::parse_from_str(e.as_str(), "%H:%M:%S.%f").unwrap()
|
|
||||||
});
|
|
||||||
|
|
||||||
if start > max_length || end > max_length {
|
|
||||||
let layer = capture
|
|
||||||
.name("layer")
|
|
||||||
.map_or(0, |l| i32::from_str(l.as_str()).unwrap());
|
|
||||||
|
|
||||||
if start > max_length {
|
|
||||||
start = max_length;
|
|
||||||
}
|
|
||||||
if start > max_length || end > max_length {
|
|
||||||
end = max_length;
|
|
||||||
}
|
|
||||||
|
|
||||||
*line = re
|
|
||||||
.replace(
|
|
||||||
line,
|
|
||||||
format!(
|
|
||||||
"Dialogue: {},{},{},",
|
|
||||||
layer,
|
|
||||||
format_naive_time(start),
|
|
||||||
format_naive_time(end)
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.to_string()
|
|
||||||
}
|
|
||||||
entries.0.push((start, i));
|
|
||||||
entries.1.push(i)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
entries.0.sort_by(|(a, _), (b, _)| a.cmp(b));
|
|
||||||
for i in 0..entries.0.len() {
|
|
||||||
let (_, original_position) = entries.0[i];
|
|
||||||
let new_position = entries.1[i];
|
|
||||||
|
|
||||||
if original_position != new_position {
|
|
||||||
as_lines.swap(original_position, new_position)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
*raw = as_lines.join("\n").into_bytes()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn write_ffmpeg_chapters(
|
fn write_ffmpeg_chapters(
|
||||||
file: &mut fs::File,
|
file: &mut fs::File,
|
||||||
video_len: NaiveTime,
|
video_len: TimeDelta,
|
||||||
events: &mut Vec<(&str, &SkipEventsEvent)>,
|
events: &mut Vec<(&str, &SkipEventsEvent)>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let video_len = video_len
|
let video_len = video_len.num_milliseconds() as f32 / 1000.0;
|
||||||
.signed_duration_since(NaiveTime::MIN)
|
events.sort_by(|(_, event_a), (_, event_b)| event_a.start.total_cmp(&event_b.start));
|
||||||
.num_seconds() as u32;
|
|
||||||
events.sort_by(|(_, event_a), (_, event_b)| event_a.start.cmp(&event_b.start));
|
|
||||||
|
|
||||||
writeln!(file, ";FFMETADATA1")?;
|
writeln!(file, ";FFMETADATA1")?;
|
||||||
|
|
||||||
let mut last_end_time = 0;
|
let mut last_end_time = 0.0;
|
||||||
for (name, event) in events {
|
for (name, event) in events {
|
||||||
// include an extra 'Episode' chapter if the start of the current chapter is more than 10
|
/*
|
||||||
// seconds later than the end of the last chapter.
|
- Convert from seconds to milliseconds for the correct timescale
|
||||||
// this is done before writing the actual chapter of this loop to keep the chapter
|
- Include an extra 'Episode' chapter if the start of the current chapter is more than 10
|
||||||
// chronologically in order
|
seconds later than the end of the last chapter.
|
||||||
if event.start as i32 - last_end_time as i32 > 10 {
|
This is done before writing the actual chapter of this loop to keep the chapter
|
||||||
|
chronologically in order
|
||||||
|
*/
|
||||||
|
if event.start - last_end_time > 10.0 {
|
||||||
writeln!(file, "[CHAPTER]")?;
|
writeln!(file, "[CHAPTER]")?;
|
||||||
writeln!(file, "TIMEBASE=1/1")?;
|
writeln!(file, "TIMEBASE=1/1000")?;
|
||||||
writeln!(file, "START={}", last_end_time)?;
|
writeln!(file, "START={}", (last_end_time * 1000.0) as u32)?;
|
||||||
writeln!(file, "END={}", event.start)?;
|
writeln!(file, "END={}", (event.start * 1000.0) as u32)?;
|
||||||
writeln!(file, "title=Episode")?;
|
writeln!(file, "title=Episode")?;
|
||||||
}
|
}
|
||||||
|
|
||||||
writeln!(file, "[CHAPTER]")?;
|
writeln!(file, "[CHAPTER]")?;
|
||||||
writeln!(file, "TIMEBASE=1/1")?;
|
writeln!(file, "TIMEBASE=1/1000")?;
|
||||||
writeln!(file, "START={}", event.start)?;
|
writeln!(file, "START={}", (event.start * 1000.0) as u32)?;
|
||||||
writeln!(file, "END={}", event.end)?;
|
writeln!(file, "END={}", (event.end * 1000.0) as u32)?;
|
||||||
writeln!(file, "title={}", name)?;
|
writeln!(file, "title={}", name)?;
|
||||||
|
|
||||||
last_end_time = event.end;
|
last_end_time = event.end;
|
||||||
}
|
}
|
||||||
|
|
||||||
// only add a traling chapter if the gab between the end of the last chapter and the total video
|
// only add a trailing chapter if the gap between the end of the last chapter and the total video
|
||||||
// length is greater than 10 seconds
|
// length is greater than 10 seconds
|
||||||
if video_len as i32 - last_end_time as i32 > 10 {
|
if video_len - last_end_time > 10.0 {
|
||||||
writeln!(file, "[CHAPTER]")?;
|
writeln!(file, "[CHAPTER]")?;
|
||||||
writeln!(file, "TIMEBASE=1/1")?;
|
writeln!(file, "TIMEBASE=1/1000")?;
|
||||||
writeln!(file, "START={}", last_end_time)?;
|
writeln!(file, "START={}", (last_end_time * 1000.0) as u32)?;
|
||||||
writeln!(file, "END={}", video_len)?;
|
writeln!(file, "END={}", (video_len * 1000.0) as u32)?;
|
||||||
writeln!(file, "title=Episode")?;
|
writeln!(file, "title=Episode")?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1288,21 +1400,11 @@ async fn ffmpeg_progress<R: AsyncReadExt + Unpin>(
|
||||||
|
|
||||||
let reader = BufReader::new(stats);
|
let reader = BufReader::new(stats);
|
||||||
let mut lines = reader.lines();
|
let mut lines = reader.lines();
|
||||||
|
let mut frame = 0;
|
||||||
loop {
|
loop {
|
||||||
select! {
|
select! {
|
||||||
// when gracefully canceling this future, set the progress to 100% (finished). sometimes
|
|
||||||
// ffmpeg is too fast or already finished when the reading process of 'stats' starts
|
|
||||||
// which causes the progress to be stuck at 0%
|
|
||||||
_ = cancellation_token.cancelled() => {
|
_ = cancellation_token.cancelled() => {
|
||||||
if let Some(p) = &progress {
|
break
|
||||||
p.set_position(total_frames)
|
|
||||||
}
|
|
||||||
debug!(
|
|
||||||
"Processed frame [{}/{} 100%]",
|
|
||||||
total_frames,
|
|
||||||
total_frames
|
|
||||||
);
|
|
||||||
return Ok(())
|
|
||||||
}
|
}
|
||||||
line = lines.next_line() => {
|
line = lines.next_line() => {
|
||||||
let Some(line) = line? else {
|
let Some(line) = line? else {
|
||||||
|
|
@ -1317,7 +1419,7 @@ async fn ffmpeg_progress<R: AsyncReadExt + Unpin>(
|
||||||
let Some(frame_str) = frame_cap.name("frame") else {
|
let Some(frame_str) = frame_cap.name("frame") else {
|
||||||
break
|
break
|
||||||
};
|
};
|
||||||
let frame: u64 = frame_str.as_str().parse()?;
|
frame = frame_str.as_str().parse()?;
|
||||||
|
|
||||||
if let Some(p) = &progress {
|
if let Some(p) = &progress {
|
||||||
p.set_position(frame)
|
p.set_position(frame)
|
||||||
|
|
@ -1333,5 +1435,19 @@ async fn ffmpeg_progress<R: AsyncReadExt + Unpin>(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// when this future is gracefully cancelled or if ffmpeg is too fast or already finished when
|
||||||
|
// reading process of 'stats' starts (which causes the progress to be stuck at 0%), the progress
|
||||||
|
// is manually set to 100% here
|
||||||
|
if frame < total_frames {
|
||||||
|
if let Some(p) = &progress {
|
||||||
|
p.set_position(total_frames)
|
||||||
|
}
|
||||||
|
debug!("Processed frame [{}/{} 100%]", total_frames, total_frames);
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn len_from_segments(segments: &[StreamSegment]) -> TimeDelta {
|
||||||
|
TimeDelta::milliseconds(segments.iter().map(|s| s.length.as_millis()).sum::<u128>() as i64)
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
use lazy_static::lazy_static;
|
use lazy_static::lazy_static;
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
|
use std::fmt;
|
||||||
|
use std::fmt::Formatter;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
|
||||||
pub const SOFTSUB_CONTAINERS: [&str; 3] = ["mkv", "mov", "mp4"];
|
pub const SOFTSUB_CONTAINERS: [&str; 3] = ["mkv", "mov", "mp4"];
|
||||||
|
|
@ -33,11 +35,11 @@ macro_rules! ffmpeg_enum {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ToString for $name {
|
impl fmt::Display for $name {
|
||||||
fn to_string(&self) -> String {
|
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
$(
|
$(
|
||||||
&$name::$field => stringify!($field).to_string().to_lowercase()
|
&$name::$field => write!(f, "{}", stringify!($field).to_string().to_lowercase())
|
||||||
),*
|
),*
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -135,23 +137,16 @@ impl FFmpegPreset {
|
||||||
for (codec, hwaccel, quality) in FFmpegPreset::available_matches() {
|
for (codec, hwaccel, quality) in FFmpegPreset::available_matches() {
|
||||||
let mut description_details = vec![];
|
let mut description_details = vec![];
|
||||||
if let Some(h) = &hwaccel {
|
if let Some(h) = &hwaccel {
|
||||||
description_details.push(format!("{} hardware acceleration", h.to_string()))
|
description_details.push(format!("{h} hardware acceleration"))
|
||||||
}
|
}
|
||||||
if let Some(q) = &quality {
|
if let Some(q) = &quality {
|
||||||
description_details.push(format!("{} video quality/compression", q.to_string()))
|
description_details.push(format!("{q} video quality/compression"))
|
||||||
}
|
}
|
||||||
|
|
||||||
let description = if description_details.is_empty() {
|
let description = if description_details.is_empty() {
|
||||||
format!(
|
format!("{codec} encoded with default video quality/compression",)
|
||||||
"{} encoded with default video quality/compression",
|
|
||||||
codec.to_string()
|
|
||||||
)
|
|
||||||
} else if description_details.len() == 1 {
|
} else if description_details.len() == 1 {
|
||||||
format!(
|
format!("{} encoded with {}", codec, description_details[0])
|
||||||
"{} encoded with {}",
|
|
||||||
codec.to_string(),
|
|
||||||
description_details[0]
|
|
||||||
)
|
|
||||||
} else {
|
} else {
|
||||||
let first = description_details.remove(0);
|
let first = description_details.remove(0);
|
||||||
let last = description_details.remove(description_details.len() - 1);
|
let last = description_details.remove(description_details.len() - 1);
|
||||||
|
|
@ -161,13 +156,7 @@ impl FFmpegPreset {
|
||||||
"".to_string()
|
"".to_string()
|
||||||
};
|
};
|
||||||
|
|
||||||
format!(
|
format!("{codec} encoded with {first}{mid} and {last}",)
|
||||||
"{} encoded with {}{} and {}",
|
|
||||||
codec.to_string(),
|
|
||||||
first,
|
|
||||||
mid,
|
|
||||||
last
|
|
||||||
)
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return_values.push(format!(
|
return_values.push(format!(
|
||||||
|
|
@ -201,11 +190,7 @@ impl FFmpegPreset {
|
||||||
.find(|p| p.to_string() == token.to_lowercase())
|
.find(|p| p.to_string() == token.to_lowercase())
|
||||||
{
|
{
|
||||||
if let Some(cc) = codec {
|
if let Some(cc) = codec {
|
||||||
return Err(format!(
|
return Err(format!("cannot use multiple codecs (found {cc} and {c})",));
|
||||||
"cannot use multiple codecs (found {} and {})",
|
|
||||||
cc.to_string(),
|
|
||||||
c.to_string()
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
codec = Some(c)
|
codec = Some(c)
|
||||||
} else if let Some(h) = FFmpegHwAccel::all()
|
} else if let Some(h) = FFmpegHwAccel::all()
|
||||||
|
|
@ -214,9 +199,7 @@ impl FFmpegPreset {
|
||||||
{
|
{
|
||||||
if let Some(hh) = hwaccel {
|
if let Some(hh) = hwaccel {
|
||||||
return Err(format!(
|
return Err(format!(
|
||||||
"cannot use multiple hardware accelerations (found {} and {})",
|
"cannot use multiple hardware accelerations (found {hh} and {h})",
|
||||||
hh.to_string(),
|
|
||||||
h.to_string()
|
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
hwaccel = Some(h)
|
hwaccel = Some(h)
|
||||||
|
|
@ -226,9 +209,7 @@ impl FFmpegPreset {
|
||||||
{
|
{
|
||||||
if let Some(qq) = quality {
|
if let Some(qq) = quality {
|
||||||
return Err(format!(
|
return Err(format!(
|
||||||
"cannot use multiple ffmpeg preset qualities (found {} and {})",
|
"cannot use multiple ffmpeg preset qualities (found {qq} and {q})",
|
||||||
qq.to_string(),
|
|
||||||
q.to_string()
|
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
quality = Some(q)
|
quality = Some(q)
|
||||||
|
|
|
||||||
|
|
@ -1,24 +1,407 @@
|
||||||
|
use crate::utils::format::{SingleFormat, SingleFormatCollection};
|
||||||
|
use crate::utils::interactive_select::{check_for_duplicated_seasons, get_duplicated_seasons};
|
||||||
|
use crate::utils::parse::{fract, UrlFilter};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use crunchyroll_rs::{
|
use crunchyroll_rs::{
|
||||||
Concert, Episode, MediaCollection, Movie, MovieListing, MusicVideo, Season, Series,
|
Concert, Episode, Locale, MediaCollection, Movie, MovieListing, MusicVideo, Season, Series,
|
||||||
};
|
};
|
||||||
|
use log::{info, warn};
|
||||||
|
use std::collections::{BTreeMap, HashMap};
|
||||||
|
use std::ops::Not;
|
||||||
|
|
||||||
pub trait Filter {
|
pub(crate) enum FilterMediaScope<'a> {
|
||||||
type T: Send + Sized;
|
Series(&'a Series),
|
||||||
type Output: Send + Sized;
|
Season(&'a Season),
|
||||||
|
/// Always contains 1 or 2 episodes.
|
||||||
|
/// - 1: The episode's audio is completely missing
|
||||||
|
/// - 2: The requested audio is only available from first entry to last entry
|
||||||
|
Episode(Vec<&'a Episode>),
|
||||||
|
}
|
||||||
|
|
||||||
async fn visit_series(&mut self, series: Series) -> Result<Vec<Season>>;
|
pub(crate) struct Filter {
|
||||||
async fn visit_season(&mut self, season: Season) -> Result<Vec<Episode>>;
|
url_filter: UrlFilter,
|
||||||
async fn visit_episode(&mut self, episode: Episode) -> Result<Option<Self::T>>;
|
|
||||||
async fn visit_movie_listing(&mut self, movie_listing: MovieListing) -> Result<Vec<Movie>>;
|
|
||||||
async fn visit_movie(&mut self, movie: Movie) -> Result<Option<Self::T>>;
|
|
||||||
async fn visit_music_video(&mut self, music_video: MusicVideo) -> Result<Option<Self::T>>;
|
|
||||||
async fn visit_concert(&mut self, concert: Concert) -> Result<Option<Self::T>>;
|
|
||||||
|
|
||||||
async fn visit(mut self, media_collection: MediaCollection) -> Result<Self::Output>
|
skip_specials: bool,
|
||||||
where
|
interactive_input: bool,
|
||||||
Self: Send + Sized,
|
|
||||||
|
relative_episode_number: bool,
|
||||||
|
|
||||||
|
audio_locales: Vec<Locale>,
|
||||||
|
subtitle_locales: Vec<Locale>,
|
||||||
|
|
||||||
|
audios_missing: fn(FilterMediaScope, Vec<&Locale>) -> Result<bool>,
|
||||||
|
subtitles_missing: fn(FilterMediaScope, Vec<&Locale>) -> Result<bool>,
|
||||||
|
no_premium: fn(u32) -> Result<()>,
|
||||||
|
|
||||||
|
is_premium: bool,
|
||||||
|
|
||||||
|
series_visited: bool,
|
||||||
|
season_episodes: HashMap<String, Vec<Episode>>,
|
||||||
|
season_with_premium: Option<Vec<u32>>,
|
||||||
|
season_sorting: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Filter {
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub(crate) fn new(
|
||||||
|
url_filter: UrlFilter,
|
||||||
|
audio_locales: Vec<Locale>,
|
||||||
|
subtitle_locales: Vec<Locale>,
|
||||||
|
audios_missing: fn(FilterMediaScope, Vec<&Locale>) -> Result<bool>,
|
||||||
|
subtitles_missing: fn(FilterMediaScope, Vec<&Locale>) -> Result<bool>,
|
||||||
|
no_premium: fn(u32) -> Result<()>,
|
||||||
|
relative_episode_number: bool,
|
||||||
|
interactive_input: bool,
|
||||||
|
skip_specials: bool,
|
||||||
|
is_premium: bool,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
url_filter,
|
||||||
|
audio_locales,
|
||||||
|
subtitle_locales,
|
||||||
|
relative_episode_number,
|
||||||
|
interactive_input,
|
||||||
|
audios_missing,
|
||||||
|
subtitles_missing,
|
||||||
|
no_premium,
|
||||||
|
is_premium,
|
||||||
|
series_visited: false,
|
||||||
|
season_episodes: HashMap::new(),
|
||||||
|
skip_specials,
|
||||||
|
season_with_premium: is_premium.not().then_some(vec![]),
|
||||||
|
season_sorting: vec![],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn visit_series(&mut self, series: Series) -> Result<Vec<Season>> {
|
||||||
|
// the audio locales field isn't always populated
|
||||||
|
if !series.audio_locales.is_empty() {
|
||||||
|
let missing_audios = missing_locales(&series.audio_locales, &self.audio_locales);
|
||||||
|
if !missing_audios.is_empty()
|
||||||
|
&& !(self.audios_missing)(FilterMediaScope::Series(&series), missing_audios)?
|
||||||
{
|
{
|
||||||
|
return Ok(vec![]);
|
||||||
|
}
|
||||||
|
let missing_subtitles =
|
||||||
|
missing_locales(&series.subtitle_locales, &self.subtitle_locales);
|
||||||
|
if !missing_subtitles.is_empty()
|
||||||
|
&& !(self.subtitles_missing)(FilterMediaScope::Series(&series), missing_subtitles)?
|
||||||
|
{
|
||||||
|
return Ok(vec![]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut seasons = vec![];
|
||||||
|
for season in series.seasons().await? {
|
||||||
|
if !self.url_filter.is_season_valid(season.season_number) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let missing_audios = missing_locales(
|
||||||
|
&season
|
||||||
|
.versions
|
||||||
|
.iter()
|
||||||
|
.map(|l| l.audio_locale.clone())
|
||||||
|
.collect::<Vec<Locale>>(),
|
||||||
|
&self.audio_locales,
|
||||||
|
);
|
||||||
|
if !missing_audios.is_empty()
|
||||||
|
&& !(self.audios_missing)(FilterMediaScope::Season(&season), missing_audios)?
|
||||||
|
{
|
||||||
|
return Ok(vec![]);
|
||||||
|
}
|
||||||
|
seasons.push(season)
|
||||||
|
}
|
||||||
|
|
||||||
|
let duplicated_seasons = get_duplicated_seasons(&seasons);
|
||||||
|
if !duplicated_seasons.is_empty() {
|
||||||
|
if self.interactive_input {
|
||||||
|
check_for_duplicated_seasons(&mut seasons)
|
||||||
|
} else {
|
||||||
|
info!(
|
||||||
|
"Found duplicated seasons: {}",
|
||||||
|
duplicated_seasons
|
||||||
|
.iter()
|
||||||
|
.map(|d| d.to_string())
|
||||||
|
.collect::<Vec<String>>()
|
||||||
|
.join(", ")
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.series_visited = true;
|
||||||
|
|
||||||
|
Ok(seasons)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn visit_season(&mut self, season: Season) -> Result<Vec<Episode>> {
|
||||||
|
if !self.url_filter.is_season_valid(season.season_number) {
|
||||||
|
return Ok(vec![]);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut seasons = vec![];
|
||||||
|
if self
|
||||||
|
.audio_locales
|
||||||
|
.iter()
|
||||||
|
.any(|l| season.audio_locales.contains(l))
|
||||||
|
{
|
||||||
|
seasons.push(season.clone())
|
||||||
|
}
|
||||||
|
for version in season.versions {
|
||||||
|
if season.id == version.id {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if self.audio_locales.contains(&version.audio_locale) {
|
||||||
|
seasons.push(version.season().await?)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut episodes = vec![];
|
||||||
|
for season in seasons {
|
||||||
|
self.season_sorting.push(season.id.clone());
|
||||||
|
let mut eps = season.episodes().await?;
|
||||||
|
|
||||||
|
// removes any episode that does not have the audio locale of the season. yes, this is
|
||||||
|
// the case sometimes
|
||||||
|
if season.audio_locales.len() < 2 {
|
||||||
|
let season_locale = season
|
||||||
|
.audio_locales
|
||||||
|
.first()
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or(Locale::ja_JP);
|
||||||
|
eps.retain(|e| e.audio_locale == season_locale)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::if_same_then_else)]
|
||||||
|
if eps.len() < season.number_of_episodes as usize {
|
||||||
|
if eps.is_empty()
|
||||||
|
&& !(self.audios_missing)(
|
||||||
|
FilterMediaScope::Season(&season),
|
||||||
|
season.audio_locales.iter().collect(),
|
||||||
|
)?
|
||||||
|
{
|
||||||
|
return Ok(vec![]);
|
||||||
|
} else if !eps.is_empty()
|
||||||
|
&& !(self.audios_missing)(
|
||||||
|
FilterMediaScope::Episode(vec![eps.first().unwrap(), eps.last().unwrap()]),
|
||||||
|
vec![&eps.first().unwrap().audio_locale],
|
||||||
|
)?
|
||||||
|
{
|
||||||
|
return Ok(vec![]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
episodes.extend(eps)
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.relative_episode_number {
|
||||||
|
for episode in &episodes {
|
||||||
|
self.season_episodes
|
||||||
|
.entry(episode.season_id.clone())
|
||||||
|
.or_default()
|
||||||
|
.push(episode.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(episodes)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn visit_episode(&mut self, episode: Episode) -> Result<Vec<SingleFormat>> {
|
||||||
|
if !self
|
||||||
|
.url_filter
|
||||||
|
.is_episode_valid(episode.sequence_number, episode.season_number)
|
||||||
|
{
|
||||||
|
return Ok(vec![]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// skip the episode if it's a special
|
||||||
|
if self.skip_specials
|
||||||
|
&& (episode.sequence_number == 0.0 || episode.sequence_number.fract() != 0.0)
|
||||||
|
{
|
||||||
|
return Ok(vec![]);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut episodes = vec![];
|
||||||
|
if !self.series_visited {
|
||||||
|
if self.audio_locales.contains(&episode.audio_locale) {
|
||||||
|
episodes.push(episode.clone())
|
||||||
|
}
|
||||||
|
for version in &episode.versions {
|
||||||
|
// `episode` is also a version of itself. the if block above already adds the
|
||||||
|
// episode if it matches the requested audio, so it doesn't need to be requested
|
||||||
|
// here again
|
||||||
|
if version.id == episode.id {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if self.audio_locales.contains(&version.audio_locale) {
|
||||||
|
episodes.push(version.episode().await?)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let audio_locales: Vec<Locale> =
|
||||||
|
episodes.iter().map(|e| e.audio_locale.clone()).collect();
|
||||||
|
let missing_audios = missing_locales(&audio_locales, &self.audio_locales);
|
||||||
|
if !missing_audios.is_empty()
|
||||||
|
&& !(self.audios_missing)(
|
||||||
|
FilterMediaScope::Episode(vec![&episode]),
|
||||||
|
missing_audios,
|
||||||
|
)?
|
||||||
|
{
|
||||||
|
return Ok(vec![]);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut subtitle_locales: Vec<Locale> = episodes
|
||||||
|
.iter()
|
||||||
|
.flat_map(|e| e.subtitle_locales.clone())
|
||||||
|
.collect();
|
||||||
|
subtitle_locales.sort();
|
||||||
|
subtitle_locales.dedup();
|
||||||
|
let missing_subtitles = missing_locales(&subtitle_locales, &self.subtitle_locales);
|
||||||
|
if !missing_subtitles.is_empty()
|
||||||
|
&& !(self.subtitles_missing)(
|
||||||
|
FilterMediaScope::Episode(vec![&episode]),
|
||||||
|
missing_subtitles,
|
||||||
|
)?
|
||||||
|
{
|
||||||
|
return Ok(vec![]);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
episodes.push(episode.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(seasons_with_premium) = &mut self.season_with_premium {
|
||||||
|
let episodes_len_before = episodes.len();
|
||||||
|
episodes.retain(|e| !e.is_premium_only && !self.is_premium);
|
||||||
|
if episodes_len_before < episodes.len()
|
||||||
|
&& !seasons_with_premium.contains(&episode.season_number)
|
||||||
|
{
|
||||||
|
(self.no_premium)(episode.season_number)?;
|
||||||
|
seasons_with_premium.push(episode.season_number)
|
||||||
|
}
|
||||||
|
|
||||||
|
if episodes.is_empty() {
|
||||||
|
return Ok(vec![]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut relative_episode_number = None;
|
||||||
|
let mut relative_sequence_number = None;
|
||||||
|
if self.relative_episode_number {
|
||||||
|
let season_eps = match self.season_episodes.get(&episode.season_id) {
|
||||||
|
Some(eps) => eps,
|
||||||
|
None => {
|
||||||
|
self.season_episodes.insert(
|
||||||
|
episode.season_id.clone(),
|
||||||
|
episode.season().await?.episodes().await?,
|
||||||
|
);
|
||||||
|
self.season_episodes.get(&episode.season_id).unwrap()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut non_integer_sequence_number_count = 0;
|
||||||
|
for (i, ep) in season_eps.iter().enumerate() {
|
||||||
|
if ep.sequence_number != 0.0 || ep.sequence_number.fract() == 0.0 {
|
||||||
|
non_integer_sequence_number_count += 1
|
||||||
|
}
|
||||||
|
if ep.id == episode.id {
|
||||||
|
relative_episode_number = Some(i + 1);
|
||||||
|
relative_sequence_number = Some(
|
||||||
|
(i + 1 - non_integer_sequence_number_count) as f32
|
||||||
|
+ fract(ep.sequence_number),
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if relative_episode_number.is_none() || relative_sequence_number.is_none() {
|
||||||
|
warn!(
|
||||||
|
"Failed to get relative episode number for episode {} ({}) of {} season {}",
|
||||||
|
episode.sequence_number,
|
||||||
|
episode.title,
|
||||||
|
episode.series_title,
|
||||||
|
episode.season_number,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(episodes
|
||||||
|
.into_iter()
|
||||||
|
.map(|e| {
|
||||||
|
SingleFormat::new_from_episode(
|
||||||
|
e.clone(),
|
||||||
|
e.subtitle_locales,
|
||||||
|
relative_episode_number.map(|n| n as u32),
|
||||||
|
relative_sequence_number,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn visit_movie_listing(&mut self, movie_listing: MovieListing) -> Result<Vec<Movie>> {
|
||||||
|
Ok(movie_listing.movies().await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn visit_movie(&mut self, movie: Movie) -> Result<Vec<SingleFormat>> {
|
||||||
|
Ok(vec![SingleFormat::new_from_movie(movie, vec![])])
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn visit_music_video(&mut self, music_video: MusicVideo) -> Result<Vec<SingleFormat>> {
|
||||||
|
Ok(vec![SingleFormat::new_from_music_video(music_video)])
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn visit_concert(&mut self, concert: Concert) -> Result<Vec<SingleFormat>> {
|
||||||
|
Ok(vec![SingleFormat::new_from_concert(concert)])
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn finish(self, input: Vec<Vec<SingleFormat>>) -> Result<SingleFormatCollection> {
|
||||||
|
let flatten_input: Vec<SingleFormat> = input.into_iter().flatten().collect();
|
||||||
|
|
||||||
|
let mut single_format_collection = SingleFormatCollection::new();
|
||||||
|
|
||||||
|
let mut pre_sorted: BTreeMap<String, Vec<SingleFormat>> = BTreeMap::new();
|
||||||
|
for data in flatten_input {
|
||||||
|
pre_sorted
|
||||||
|
.entry(data.identifier.clone())
|
||||||
|
.or_default()
|
||||||
|
.push(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut sorted: Vec<(String, Vec<SingleFormat>)> = pre_sorted.into_iter().collect();
|
||||||
|
sorted.sort_by(|(_, a), (_, b)| {
|
||||||
|
self.season_sorting
|
||||||
|
.iter()
|
||||||
|
.position(|p| p == &a.first().unwrap().season_id)
|
||||||
|
.unwrap()
|
||||||
|
.cmp(
|
||||||
|
&self
|
||||||
|
.season_sorting
|
||||||
|
.iter()
|
||||||
|
.position(|p| p == &b.first().unwrap().season_id)
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
for (_, mut data) in sorted {
|
||||||
|
data.sort_by(|a, b| {
|
||||||
|
self.audio_locales
|
||||||
|
.iter()
|
||||||
|
.position(|p| p == &a.audio)
|
||||||
|
.unwrap_or(usize::MAX)
|
||||||
|
.cmp(
|
||||||
|
&self
|
||||||
|
.audio_locales
|
||||||
|
.iter()
|
||||||
|
.position(|p| p == &b.audio)
|
||||||
|
.unwrap_or(usize::MAX),
|
||||||
|
)
|
||||||
|
});
|
||||||
|
single_format_collection.add_single_formats(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(single_format_collection)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn visit(
|
||||||
|
mut self,
|
||||||
|
media_collection: MediaCollection,
|
||||||
|
) -> Result<SingleFormatCollection> {
|
||||||
let mut items = vec![media_collection];
|
let mut items = vec![media_collection];
|
||||||
let mut result = vec![];
|
let mut result = vec![];
|
||||||
|
|
||||||
|
|
@ -42,9 +425,7 @@ pub trait Filter {
|
||||||
.collect::<Vec<MediaCollection>>(),
|
.collect::<Vec<MediaCollection>>(),
|
||||||
),
|
),
|
||||||
MediaCollection::Episode(episode) => {
|
MediaCollection::Episode(episode) => {
|
||||||
if let Some(t) = self.visit_episode(episode).await? {
|
result.push(self.visit_episode(episode).await?)
|
||||||
result.push(t)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
MediaCollection::MovieListing(movie_listing) => new_items.extend(
|
MediaCollection::MovieListing(movie_listing) => new_items.extend(
|
||||||
self.visit_movie_listing(movie_listing)
|
self.visit_movie_listing(movie_listing)
|
||||||
|
|
@ -53,20 +434,12 @@ pub trait Filter {
|
||||||
.map(|m| m.into())
|
.map(|m| m.into())
|
||||||
.collect::<Vec<MediaCollection>>(),
|
.collect::<Vec<MediaCollection>>(),
|
||||||
),
|
),
|
||||||
MediaCollection::Movie(movie) => {
|
MediaCollection::Movie(movie) => result.push(self.visit_movie(movie).await?),
|
||||||
if let Some(t) = self.visit_movie(movie).await? {
|
|
||||||
result.push(t)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
MediaCollection::MusicVideo(music_video) => {
|
MediaCollection::MusicVideo(music_video) => {
|
||||||
if let Some(t) = self.visit_music_video(music_video).await? {
|
result.push(self.visit_music_video(music_video).await?)
|
||||||
result.push(t)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
MediaCollection::Concert(concert) => {
|
MediaCollection::Concert(concert) => {
|
||||||
if let Some(t) = self.visit_concert(concert).await? {
|
result.push(self.visit_concert(concert).await?)
|
||||||
result.push(t)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -76,8 +449,10 @@ pub trait Filter {
|
||||||
|
|
||||||
self.finish(result).await
|
self.finish(result).await
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async fn finish(self, input: Vec<Self::T>) -> Result<Self::Output>;
|
fn missing_locales<'a>(available: &[Locale], searched: &'a [Locale]) -> Vec<&'a Locale> {
|
||||||
|
searched.iter().filter(|p| !available.contains(p)).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Remove all duplicates from a [`Vec`].
|
/// Remove all duplicates from a [`Vec`].
|
||||||
|
|
|
||||||
19
crunchy-cli-core/src/utils/fmt.rs
Normal file
19
crunchy-cli-core/src/utils/fmt.rs
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
use chrono::TimeDelta;
|
||||||
|
|
||||||
|
pub fn format_time_delta(time_delta: &TimeDelta) -> String {
|
||||||
|
let negative = *time_delta < TimeDelta::zero();
|
||||||
|
let time_delta = time_delta.abs();
|
||||||
|
let hours = time_delta.num_hours();
|
||||||
|
let minutes = time_delta.num_minutes() - time_delta.num_hours() * 60;
|
||||||
|
let seconds = time_delta.num_seconds() - time_delta.num_minutes() * 60;
|
||||||
|
let milliseconds = time_delta.num_milliseconds() - time_delta.num_seconds() * 1000;
|
||||||
|
|
||||||
|
format!(
|
||||||
|
"{}{}:{:0>2}:{:0>2}.{:0>3}",
|
||||||
|
if negative { "-" } else { "" },
|
||||||
|
hours,
|
||||||
|
minutes,
|
||||||
|
seconds,
|
||||||
|
milliseconds
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -2,9 +2,9 @@ use crate::utils::filter::real_dedup_vec;
|
||||||
use crate::utils::locale::LanguageTagging;
|
use crate::utils::locale::LanguageTagging;
|
||||||
use crate::utils::log::tab_info;
|
use crate::utils::log::tab_info;
|
||||||
use crate::utils::os::{is_special_file, sanitize};
|
use crate::utils::os::{is_special_file, sanitize};
|
||||||
use anyhow::Result;
|
use anyhow::{bail, Result};
|
||||||
use chrono::{Datelike, Duration};
|
use chrono::{Datelike, Duration};
|
||||||
use crunchyroll_rs::media::{Resolution, SkipEvents, Stream, Subtitle, VariantData};
|
use crunchyroll_rs::media::{SkipEvents, Stream, StreamData, Subtitle};
|
||||||
use crunchyroll_rs::{Concert, Episode, Locale, MediaCollection, Movie, MusicVideo};
|
use crunchyroll_rs::{Concert, Episode, Locale, MediaCollection, Movie, MusicVideo};
|
||||||
use log::{debug, info};
|
use log::{debug, info};
|
||||||
use std::cmp::Ordering;
|
use std::cmp::Ordering;
|
||||||
|
|
@ -12,6 +12,7 @@ use std::collections::BTreeMap;
|
||||||
use std::env;
|
use std::env;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct SingleFormat {
|
pub struct SingleFormat {
|
||||||
pub identifier: String,
|
pub identifier: String,
|
||||||
|
|
@ -167,13 +168,19 @@ impl SingleFormat {
|
||||||
|
|
||||||
pub async fn stream(&self) -> Result<Stream> {
|
pub async fn stream(&self) -> Result<Stream> {
|
||||||
let stream = match &self.source {
|
let stream = match &self.source {
|
||||||
MediaCollection::Episode(e) => e.stream().await?,
|
MediaCollection::Episode(e) => e.stream_maybe_without_drm().await,
|
||||||
MediaCollection::Movie(m) => m.stream().await?,
|
MediaCollection::Movie(m) => m.stream_maybe_without_drm().await,
|
||||||
MediaCollection::MusicVideo(mv) => mv.stream().await?,
|
MediaCollection::MusicVideo(mv) => mv.stream_maybe_without_drm().await,
|
||||||
MediaCollection::Concert(c) => c.stream().await?,
|
MediaCollection::Concert(c) => c.stream_maybe_without_drm().await,
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
};
|
};
|
||||||
Ok(stream)
|
|
||||||
|
if let Err(crunchyroll_rs::error::Error::Request { message, .. }) = &stream {
|
||||||
|
if message.starts_with("TOO_MANY_ACTIVE_STREAMS") {
|
||||||
|
bail!("Too many active/parallel streams. Please close at least one stream you're watching and try again")
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok(stream?)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn skip_events(&self) -> Result<Option<SkipEvents>> {
|
pub async fn skip_events(&self) -> Result<Option<SkipEvents>> {
|
||||||
|
|
@ -331,9 +338,7 @@ impl Iterator for SingleFormatCollectionIterator {
|
||||||
type Item = Vec<SingleFormat>;
|
type Item = Vec<SingleFormat>;
|
||||||
|
|
||||||
fn next(&mut self) -> Option<Self::Item> {
|
fn next(&mut self) -> Option<Self::Item> {
|
||||||
let Some((_, episodes)) = self.0 .0.iter_mut().next() else {
|
let (_, episodes) = self.0 .0.iter_mut().next()?;
|
||||||
return None;
|
|
||||||
};
|
|
||||||
|
|
||||||
let value = episodes.pop_first().unwrap().1;
|
let value = episodes.pop_first().unwrap().1;
|
||||||
if episodes.is_empty() {
|
if episodes.is_empty() {
|
||||||
|
|
@ -343,6 +348,7 @@ impl Iterator for SingleFormatCollectionIterator {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Format {
|
pub struct Format {
|
||||||
pub title: String,
|
pub title: String,
|
||||||
|
|
@ -350,8 +356,6 @@ pub struct Format {
|
||||||
|
|
||||||
pub locales: Vec<(Locale, Vec<Locale>)>,
|
pub locales: Vec<(Locale, Vec<Locale>)>,
|
||||||
|
|
||||||
// deprecated
|
|
||||||
pub resolution: Resolution,
|
|
||||||
pub width: u64,
|
pub width: u64,
|
||||||
pub height: u64,
|
pub height: u64,
|
||||||
pub fps: f64,
|
pub fps: f64,
|
||||||
|
|
@ -377,7 +381,7 @@ pub struct Format {
|
||||||
impl Format {
|
impl Format {
|
||||||
#[allow(clippy::type_complexity)]
|
#[allow(clippy::type_complexity)]
|
||||||
pub fn from_single_formats(
|
pub fn from_single_formats(
|
||||||
mut single_formats: Vec<(SingleFormat, VariantData, Vec<(Subtitle, bool)>)>,
|
mut single_formats: Vec<(SingleFormat, StreamData, Vec<(Subtitle, bool)>)>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let locales: Vec<(Locale, Vec<Locale>)> = single_formats
|
let locales: Vec<(Locale, Vec<Locale>)> = single_formats
|
||||||
.iter()
|
.iter()
|
||||||
|
|
@ -397,10 +401,9 @@ impl Format {
|
||||||
title: first_format.title,
|
title: first_format.title,
|
||||||
description: first_format.description,
|
description: first_format.description,
|
||||||
locales,
|
locales,
|
||||||
resolution: first_stream.resolution.clone(),
|
width: first_stream.resolution().unwrap().width,
|
||||||
width: first_stream.resolution.width,
|
height: first_stream.resolution().unwrap().height,
|
||||||
height: first_stream.resolution.height,
|
fps: first_stream.fps().unwrap(),
|
||||||
fps: first_stream.fps,
|
|
||||||
release_year: first_format.release_year,
|
release_year: first_format.release_year,
|
||||||
release_month: first_format.release_month,
|
release_month: first_format.release_month,
|
||||||
release_day: first_format.release_day,
|
release_day: first_format.release_day,
|
||||||
|
|
@ -443,17 +446,13 @@ impl Format {
|
||||||
universal,
|
universal,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.replace(
|
|
||||||
"{resolution}",
|
|
||||||
&sanitize(self.resolution.to_string(), true, universal),
|
|
||||||
)
|
|
||||||
.replace(
|
.replace(
|
||||||
"{width}",
|
"{width}",
|
||||||
&sanitize(self.resolution.width.to_string(), true, universal),
|
&sanitize(self.width.to_string(), true, universal),
|
||||||
)
|
)
|
||||||
.replace(
|
.replace(
|
||||||
"{height}",
|
"{height}",
|
||||||
&sanitize(self.resolution.height.to_string(), true, universal),
|
&sanitize(self.height.to_string(), true, universal),
|
||||||
)
|
)
|
||||||
.replace("{series_id}", &sanitize(&self.series_id, true, universal))
|
.replace("{series_id}", &sanitize(&self.series_id, true, universal))
|
||||||
.replace(
|
.replace(
|
||||||
|
|
@ -527,7 +526,33 @@ impl Format {
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
PathBuf::from(path)
|
let mut path = PathBuf::from(path);
|
||||||
|
|
||||||
|
// make sure that every path section has a maximum of 255 characters
|
||||||
|
if path.file_name().unwrap_or_default().to_string_lossy().len() > 255 {
|
||||||
|
let name = path
|
||||||
|
.file_stem()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.to_string_lossy()
|
||||||
|
.to_string();
|
||||||
|
let ext = path
|
||||||
|
.extension()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.to_string_lossy()
|
||||||
|
.to_string();
|
||||||
|
if ext != name {
|
||||||
|
path.set_file_name(format!("{}.{}", &name[..(255 - ext.len() - 1)], ext))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
path.iter()
|
||||||
|
.map(|s| {
|
||||||
|
if s.len() > 255 {
|
||||||
|
s.to_string_lossy()[..255].to_string()
|
||||||
|
} else {
|
||||||
|
s.to_string_lossy().to_string()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn visual_output(&self, dst: &Path) {
|
pub fn visual_output(&self, dst: &Path) {
|
||||||
|
|
@ -563,7 +588,7 @@ impl Format {
|
||||||
.collect::<Vec<String>>()
|
.collect::<Vec<String>>()
|
||||||
.join(", ")
|
.join(", ")
|
||||||
);
|
);
|
||||||
tab_info!("Resolution: {}", self.resolution);
|
tab_info!("Resolution: {}x{}", self.height, self.width);
|
||||||
tab_info!("FPS: {:.2}", self.fps)
|
tab_info!("FPS: {:.2}", self.fps)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ pub mod context;
|
||||||
pub mod download;
|
pub mod download;
|
||||||
pub mod ffmpeg;
|
pub mod ffmpeg;
|
||||||
pub mod filter;
|
pub mod filter;
|
||||||
|
pub mod fmt;
|
||||||
pub mod format;
|
pub mod format;
|
||||||
pub mod interactive_select;
|
pub mod interactive_select;
|
||||||
pub mod locale;
|
pub mod locale;
|
||||||
|
|
@ -10,4 +11,5 @@ pub mod log;
|
||||||
pub mod os;
|
pub mod os;
|
||||||
pub mod parse;
|
pub mod parse;
|
||||||
pub mod rate_limit;
|
pub mod rate_limit;
|
||||||
|
pub mod sync;
|
||||||
pub mod video;
|
pub mod video;
|
||||||
|
|
|
||||||
|
|
@ -31,7 +31,7 @@ pub fn temp_directory() -> PathBuf {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Any tempfile should be created with this function. The prefix and directory of every file
|
/// Any tempfile should be created with this function. The prefix and directory of every file
|
||||||
/// created with this method stays the same which is helpful to query all existing tempfiles and
|
/// created with this function stays the same which is helpful to query all existing tempfiles and
|
||||||
/// e.g. remove them in a case of ctrl-c. Having one function also good to prevent mistakes like
|
/// e.g. remove them in a case of ctrl-c. Having one function also good to prevent mistakes like
|
||||||
/// setting the wrong prefix if done manually.
|
/// setting the wrong prefix if done manually.
|
||||||
pub fn tempfile<S: AsRef<str>>(suffix: S) -> io::Result<NamedTempFile> {
|
pub fn tempfile<S: AsRef<str>>(suffix: S) -> io::Result<NamedTempFile> {
|
||||||
|
|
|
||||||
432
crunchy-cli-core/src/utils/sync.rs
Normal file
432
crunchy-cli-core/src/utils/sync.rs
Normal file
|
|
@ -0,0 +1,432 @@
|
||||||
|
use std::io::Read;
|
||||||
|
use std::process::Stdio;
|
||||||
|
use std::{
|
||||||
|
cmp,
|
||||||
|
collections::{HashMap, HashSet},
|
||||||
|
mem,
|
||||||
|
ops::Not,
|
||||||
|
path::Path,
|
||||||
|
process::Command,
|
||||||
|
};
|
||||||
|
|
||||||
|
use chrono::TimeDelta;
|
||||||
|
use crunchyroll_rs::Locale;
|
||||||
|
use log::debug;
|
||||||
|
use tempfile::TempPath;
|
||||||
|
|
||||||
|
use anyhow::{bail, Result};
|
||||||
|
use rusty_chromaprint::{Configuration, Fingerprinter};
|
||||||
|
|
||||||
|
use super::fmt::format_time_delta;
|
||||||
|
|
||||||
|
pub struct SyncAudio {
|
||||||
|
pub format_id: usize,
|
||||||
|
pub path: TempPath,
|
||||||
|
pub locale: Locale,
|
||||||
|
pub sample_rate: u32,
|
||||||
|
pub video_idx: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
struct TimeRange {
|
||||||
|
start: f64,
|
||||||
|
end: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sync_audios(
|
||||||
|
available_audios: &Vec<SyncAudio>,
|
||||||
|
sync_tolerance: u32,
|
||||||
|
sync_precision: u32,
|
||||||
|
) -> Result<Option<HashMap<usize, TimeDelta>>> {
|
||||||
|
let mut result: HashMap<usize, TimeDelta> = HashMap::new();
|
||||||
|
|
||||||
|
let mut sync_audios = vec![];
|
||||||
|
let mut chromaprints = HashMap::new();
|
||||||
|
let mut formats = HashSet::new();
|
||||||
|
for audio in available_audios {
|
||||||
|
if formats.contains(&audio.format_id) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
formats.insert(audio.format_id);
|
||||||
|
sync_audios.push((audio.format_id, &audio.path, audio.sample_rate));
|
||||||
|
chromaprints.insert(
|
||||||
|
audio.format_id,
|
||||||
|
generate_chromaprint(
|
||||||
|
&audio.path,
|
||||||
|
audio.sample_rate,
|
||||||
|
&TimeDelta::zero(),
|
||||||
|
&TimeDelta::zero(),
|
||||||
|
&TimeDelta::zero(),
|
||||||
|
)?,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
sync_audios.sort_by_key(|sync_audio| chromaprints.get(&sync_audio.0).unwrap().len());
|
||||||
|
|
||||||
|
let base_audio = sync_audios.remove(0);
|
||||||
|
|
||||||
|
let mut start = f64::MAX;
|
||||||
|
let mut end = f64::MIN;
|
||||||
|
let mut initial_offsets = HashMap::new();
|
||||||
|
for audio in &sync_audios {
|
||||||
|
debug!(
|
||||||
|
"Initial comparison of format {} to {}",
|
||||||
|
audio.0, &base_audio.0
|
||||||
|
);
|
||||||
|
|
||||||
|
let (lhs_ranges, rhs_ranges) = compare_chromaprints(
|
||||||
|
chromaprints.get(&base_audio.0).unwrap(),
|
||||||
|
chromaprints.get(&audio.0).unwrap(),
|
||||||
|
sync_tolerance,
|
||||||
|
);
|
||||||
|
if lhs_ranges.is_empty() || rhs_ranges.is_empty() {
|
||||||
|
bail!(
|
||||||
|
"Failed to sync videos, couldn't find matching audio parts between format {} and {}",
|
||||||
|
base_audio.0 + 1,
|
||||||
|
audio.0 + 1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let lhs_range = lhs_ranges[0];
|
||||||
|
let rhs_range = rhs_ranges[0];
|
||||||
|
start = start.min(lhs_range.start);
|
||||||
|
end = end.max(lhs_range.end);
|
||||||
|
start = start.min(rhs_range.start);
|
||||||
|
end = end.max(rhs_range.end);
|
||||||
|
let offset = TimeDelta::milliseconds(((rhs_range.start - lhs_range.start) * 1000.0) as i64);
|
||||||
|
initial_offsets.insert(audio.0, TimeDelta::zero().checked_sub(&offset).unwrap());
|
||||||
|
debug!(
|
||||||
|
"Found initial offset of {}ms ({} - {} {}s) ({} - {} {}s) for format {} to {}",
|
||||||
|
offset.num_milliseconds(),
|
||||||
|
lhs_range.start,
|
||||||
|
lhs_range.end,
|
||||||
|
lhs_range.end - lhs_range.start,
|
||||||
|
rhs_range.start,
|
||||||
|
rhs_range.end,
|
||||||
|
rhs_range.end - rhs_range.start,
|
||||||
|
audio.0,
|
||||||
|
base_audio.0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
debug!(
|
||||||
|
"Found matching audio parts at {} - {}, narrowing search",
|
||||||
|
start, end
|
||||||
|
);
|
||||||
|
|
||||||
|
let start = TimeDelta::milliseconds((start * 1000.0) as i64 - 20000);
|
||||||
|
let end = TimeDelta::milliseconds((end * 1000.0) as i64 + 20000);
|
||||||
|
|
||||||
|
for sync_audio in &sync_audios {
|
||||||
|
let chromaprint = generate_chromaprint(
|
||||||
|
sync_audio.1,
|
||||||
|
sync_audio.2,
|
||||||
|
&start,
|
||||||
|
&end,
|
||||||
|
initial_offsets.get(&sync_audio.0).unwrap(),
|
||||||
|
)?;
|
||||||
|
chromaprints.insert(sync_audio.0, chromaprint);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut runs: HashMap<usize, i64> = HashMap::new();
|
||||||
|
let iterator_range_limits: i64 = 2 ^ sync_precision as i64;
|
||||||
|
for i in -iterator_range_limits..=iterator_range_limits {
|
||||||
|
let base_offset = TimeDelta::milliseconds(
|
||||||
|
((0.128 / iterator_range_limits as f64 * i as f64) * 1000.0) as i64,
|
||||||
|
);
|
||||||
|
chromaprints.insert(
|
||||||
|
base_audio.0,
|
||||||
|
generate_chromaprint(base_audio.1, base_audio.2, &start, &end, &base_offset)?,
|
||||||
|
);
|
||||||
|
for audio in &sync_audios {
|
||||||
|
let initial_offset = initial_offsets.get(&audio.0).copied().unwrap();
|
||||||
|
let offset = find_offset(
|
||||||
|
(&base_audio.0, chromaprints.get(&base_audio.0).unwrap()),
|
||||||
|
&base_offset,
|
||||||
|
(&audio.0, chromaprints.get(&audio.0).unwrap()),
|
||||||
|
&initial_offset,
|
||||||
|
&start,
|
||||||
|
sync_tolerance,
|
||||||
|
);
|
||||||
|
if offset.is_none() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let offset = offset.unwrap();
|
||||||
|
|
||||||
|
result.insert(
|
||||||
|
audio.0,
|
||||||
|
result
|
||||||
|
.get(&audio.0)
|
||||||
|
.copied()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.checked_add(&offset)
|
||||||
|
.unwrap(),
|
||||||
|
);
|
||||||
|
runs.insert(audio.0, runs.get(&audio.0).copied().unwrap_or_default() + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut result: HashMap<usize, TimeDelta> = result
|
||||||
|
.iter()
|
||||||
|
.map(|(format_id, offset)| {
|
||||||
|
(
|
||||||
|
*format_id,
|
||||||
|
TimeDelta::milliseconds(
|
||||||
|
offset.num_milliseconds() / runs.get(format_id).copied().unwrap(),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
result.insert(base_audio.0, TimeDelta::milliseconds(0));
|
||||||
|
|
||||||
|
Ok(Some(result))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_offset(
|
||||||
|
lhs: (&usize, &Vec<u32>),
|
||||||
|
lhs_shift: &TimeDelta,
|
||||||
|
rhs: (&usize, &Vec<u32>),
|
||||||
|
rhs_shift: &TimeDelta,
|
||||||
|
start: &TimeDelta,
|
||||||
|
sync_tolerance: u32,
|
||||||
|
) -> Option<TimeDelta> {
|
||||||
|
let (lhs_ranges, rhs_ranges) = compare_chromaprints(lhs.1, rhs.1, sync_tolerance);
|
||||||
|
if lhs_ranges.is_empty() || rhs_ranges.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let lhs_range = lhs_ranges[0];
|
||||||
|
let rhs_range = rhs_ranges[0];
|
||||||
|
let offset = rhs_range.end - lhs_range.end;
|
||||||
|
let offset = TimeDelta::milliseconds((offset * 1000.0) as i64)
|
||||||
|
.checked_add(lhs_shift)?
|
||||||
|
.checked_sub(rhs_shift)?;
|
||||||
|
debug!(
|
||||||
|
"Found offset of {}ms ({} - {} {}s) ({} - {} {}s) for format {} to {}",
|
||||||
|
offset.num_milliseconds(),
|
||||||
|
lhs_range.start + start.num_milliseconds() as f64 / 1000.0,
|
||||||
|
lhs_range.end + start.num_milliseconds() as f64 / 1000.0,
|
||||||
|
lhs_range.end - lhs_range.start,
|
||||||
|
rhs_range.start + start.num_milliseconds() as f64 / 1000.0,
|
||||||
|
rhs_range.end + start.num_milliseconds() as f64 / 1000.0,
|
||||||
|
rhs_range.end - rhs_range.start,
|
||||||
|
rhs.0,
|
||||||
|
lhs.0
|
||||||
|
);
|
||||||
|
Some(offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn generate_chromaprint(
|
||||||
|
input_file: &Path,
|
||||||
|
sample_rate: u32,
|
||||||
|
start: &TimeDelta,
|
||||||
|
end: &TimeDelta,
|
||||||
|
offset: &TimeDelta,
|
||||||
|
) -> Result<Vec<u32>> {
|
||||||
|
let mut ss_argument: &TimeDelta = &start.checked_sub(offset).unwrap();
|
||||||
|
let mut offset_argument = &TimeDelta::zero();
|
||||||
|
if *offset < TimeDelta::zero() {
|
||||||
|
ss_argument = start;
|
||||||
|
offset_argument = offset;
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut printer = Fingerprinter::new(&Configuration::preset_test1());
|
||||||
|
printer.start(sample_rate, 2)?;
|
||||||
|
|
||||||
|
let mut command = Command::new("ffmpeg");
|
||||||
|
command
|
||||||
|
.arg("-hide_banner")
|
||||||
|
.arg("-y")
|
||||||
|
.args(["-ss", format_time_delta(ss_argument).as_str()]);
|
||||||
|
|
||||||
|
if end.is_zero().not() {
|
||||||
|
command.args(["-to", format_time_delta(end).as_str()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
command
|
||||||
|
.args(["-itsoffset", format_time_delta(offset_argument).as_str()])
|
||||||
|
.args(["-i", input_file.to_string_lossy().to_string().as_str()])
|
||||||
|
.args(["-ac", "2"])
|
||||||
|
.args([
|
||||||
|
"-f",
|
||||||
|
if cfg!(target_endian = "big") {
|
||||||
|
"s16be"
|
||||||
|
} else {
|
||||||
|
"s16le"
|
||||||
|
},
|
||||||
|
])
|
||||||
|
.arg("-");
|
||||||
|
|
||||||
|
let mut handle = command
|
||||||
|
.stdout(Stdio::piped())
|
||||||
|
.stderr(Stdio::piped())
|
||||||
|
.spawn()?;
|
||||||
|
|
||||||
|
// the stdout is read in chunks because keeping all the raw audio data in memory would take up
|
||||||
|
// a significant amount of space
|
||||||
|
let mut stdout = handle.stdout.take().unwrap();
|
||||||
|
let mut buf: [u8; 128_000] = [0; 128_000];
|
||||||
|
while handle.try_wait()?.is_none() {
|
||||||
|
loop {
|
||||||
|
let read_bytes = stdout.read(&mut buf)?;
|
||||||
|
if read_bytes == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let data: [i16; 64_000] = unsafe { mem::transmute(buf) };
|
||||||
|
printer.consume(&data[0..(read_bytes / 2)])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !handle.wait()?.success() {
|
||||||
|
bail!("{}", std::io::read_to_string(handle.stderr.unwrap())?)
|
||||||
|
}
|
||||||
|
|
||||||
|
printer.finish();
|
||||||
|
return Ok(printer.fingerprint().into());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn compare_chromaprints(
|
||||||
|
lhs_chromaprint: &Vec<u32>,
|
||||||
|
rhs_chromaprint: &Vec<u32>,
|
||||||
|
sync_tolerance: u32,
|
||||||
|
) -> (Vec<TimeRange>, Vec<TimeRange>) {
|
||||||
|
let lhs_inverse_index = create_inverse_index(lhs_chromaprint);
|
||||||
|
let rhs_inverse_index = create_inverse_index(rhs_chromaprint);
|
||||||
|
|
||||||
|
let mut possible_shifts = HashSet::new();
|
||||||
|
for lhs_pair in lhs_inverse_index {
|
||||||
|
let original_point = lhs_pair.0;
|
||||||
|
for i in -2..=2 {
|
||||||
|
let modified_point = (original_point as i32 + i) as u32;
|
||||||
|
if rhs_inverse_index.contains_key(&modified_point) {
|
||||||
|
let rhs_index = rhs_inverse_index.get(&modified_point).copied().unwrap();
|
||||||
|
possible_shifts.insert(rhs_index as i32 - lhs_pair.1 as i32);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut all_lhs_time_ranges = vec![];
|
||||||
|
let mut all_rhs_time_ranges = vec![];
|
||||||
|
for shift_amount in possible_shifts {
|
||||||
|
let time_range_pair = find_time_ranges(
|
||||||
|
lhs_chromaprint,
|
||||||
|
rhs_chromaprint,
|
||||||
|
shift_amount,
|
||||||
|
sync_tolerance,
|
||||||
|
);
|
||||||
|
if time_range_pair.is_none() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let (mut lhs_time_ranges, mut rhs_time_ranges) = time_range_pair.unwrap();
|
||||||
|
let mut lhs_time_ranges: Vec<TimeRange> = lhs_time_ranges
|
||||||
|
.drain(..)
|
||||||
|
.filter(|time_range| {
|
||||||
|
(20.0 < (time_range.end - time_range.start))
|
||||||
|
&& ((time_range.end - time_range.start) < 180.0)
|
||||||
|
&& time_range.end > 0.0
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
lhs_time_ranges.sort_by(|a, b| (b.end - b.start).total_cmp(&(a.end - a.start)));
|
||||||
|
let mut rhs_time_ranges: Vec<TimeRange> = rhs_time_ranges
|
||||||
|
.drain(..)
|
||||||
|
.filter(|time_range| {
|
||||||
|
(20.0 < (time_range.end - time_range.start))
|
||||||
|
&& ((time_range.end - time_range.start) < 180.0)
|
||||||
|
&& time_range.end > 0.0
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
rhs_time_ranges.sort_by(|a, b| (b.end - b.start).total_cmp(&(a.end - a.start)));
|
||||||
|
if lhs_time_ranges.is_empty() || rhs_time_ranges.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
all_lhs_time_ranges.push(lhs_time_ranges[0]);
|
||||||
|
all_rhs_time_ranges.push(rhs_time_ranges[0]);
|
||||||
|
}
|
||||||
|
all_lhs_time_ranges.sort_by(|a, b| (a.end - a.start).total_cmp(&(b.end - b.start)));
|
||||||
|
all_lhs_time_ranges.reverse();
|
||||||
|
all_rhs_time_ranges.sort_by(|a, b| (a.end - a.start).total_cmp(&(b.end - b.start)));
|
||||||
|
all_rhs_time_ranges.reverse();
|
||||||
|
|
||||||
|
(all_lhs_time_ranges, all_rhs_time_ranges)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_inverse_index(chromaprint: &Vec<u32>) -> HashMap<u32, usize> {
|
||||||
|
let mut inverse_index = HashMap::with_capacity(chromaprint.capacity());
|
||||||
|
for (i, fingerprint) in chromaprint.iter().enumerate().take(chromaprint.capacity()) {
|
||||||
|
inverse_index.insert(*fingerprint, i);
|
||||||
|
}
|
||||||
|
inverse_index
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_time_ranges(
|
||||||
|
lhs_chromaprint: &[u32],
|
||||||
|
rhs_chromaprint: &[u32],
|
||||||
|
shift_amount: i32,
|
||||||
|
sync_tolerance: u32,
|
||||||
|
) -> Option<(Vec<TimeRange>, Vec<TimeRange>)> {
|
||||||
|
let mut lhs_shift: i32 = 0;
|
||||||
|
let mut rhs_shift: i32 = 0;
|
||||||
|
if shift_amount < 0 {
|
||||||
|
lhs_shift -= shift_amount;
|
||||||
|
} else {
|
||||||
|
rhs_shift += shift_amount;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut lhs_matching_timestamps = vec![];
|
||||||
|
let mut rhs_matching_timestamps = vec![];
|
||||||
|
let upper_limit =
|
||||||
|
cmp::min(lhs_chromaprint.len(), rhs_chromaprint.len()) as i32 - shift_amount.abs();
|
||||||
|
|
||||||
|
for i in 0..upper_limit {
|
||||||
|
let lhs_position = i + lhs_shift;
|
||||||
|
let rhs_position = i + rhs_shift;
|
||||||
|
let difference = (lhs_chromaprint[lhs_position as usize]
|
||||||
|
^ rhs_chromaprint[rhs_position as usize])
|
||||||
|
.count_ones();
|
||||||
|
|
||||||
|
if difference > sync_tolerance {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
lhs_matching_timestamps.push(lhs_position as f64 * 0.128);
|
||||||
|
rhs_matching_timestamps.push(rhs_position as f64 * 0.128);
|
||||||
|
}
|
||||||
|
lhs_matching_timestamps.push(f64::MAX);
|
||||||
|
rhs_matching_timestamps.push(f64::MAX);
|
||||||
|
|
||||||
|
let lhs_time_ranges = timestamps_to_ranges(lhs_matching_timestamps);
|
||||||
|
lhs_time_ranges.as_ref()?;
|
||||||
|
let lhs_time_ranges = lhs_time_ranges.unwrap();
|
||||||
|
let rhs_time_ranges = timestamps_to_ranges(rhs_matching_timestamps).unwrap();
|
||||||
|
|
||||||
|
Some((lhs_time_ranges, rhs_time_ranges))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn timestamps_to_ranges(mut timestamps: Vec<f64>) -> Option<Vec<TimeRange>> {
|
||||||
|
if timestamps.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
timestamps.sort_by(|a, b| a.total_cmp(b));
|
||||||
|
|
||||||
|
let mut time_ranges = vec![];
|
||||||
|
let mut current_range = TimeRange {
|
||||||
|
start: timestamps[0],
|
||||||
|
end: timestamps[0],
|
||||||
|
};
|
||||||
|
|
||||||
|
for i in 0..timestamps.len() - 1 {
|
||||||
|
let current = timestamps[i];
|
||||||
|
let next = timestamps[i + 1];
|
||||||
|
if next - current <= 1.0 {
|
||||||
|
current_range.end = next;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
time_ranges.push(current_range);
|
||||||
|
current_range.start = next;
|
||||||
|
current_range.end = next;
|
||||||
|
}
|
||||||
|
if !time_ranges.is_empty() {
|
||||||
|
Some(time_ranges)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,67 +1,46 @@
|
||||||
use anyhow::{bail, Result};
|
use anyhow::{bail, Result};
|
||||||
use crunchyroll_rs::media::{Resolution, Stream, VariantData};
|
use crunchyroll_rs::media::{Resolution, Stream, StreamData};
|
||||||
use crunchyroll_rs::Locale;
|
use crunchyroll_rs::Locale;
|
||||||
|
|
||||||
pub async fn variant_data_from_stream(
|
pub async fn stream_data_from_stream(
|
||||||
stream: &Stream,
|
stream: &Stream,
|
||||||
resolution: &Resolution,
|
resolution: &Resolution,
|
||||||
subtitle: Option<Locale>,
|
hardsub_subtitle: Option<Locale>,
|
||||||
) -> Result<Option<(VariantData, VariantData, bool)>> {
|
) -> Result<Option<(StreamData, StreamData, bool)>> {
|
||||||
// sometimes Crunchyroll marks episodes without real subtitles that they have subtitles and
|
let (hardsub_locale, mut contains_hardsub) = if hardsub_subtitle.is_some() {
|
||||||
// reports that only hardsub episode are existing. the following lines are trying to prevent
|
(hardsub_subtitle, true)
|
||||||
// potential errors which might get caused by this incorrect reporting
|
|
||||||
// (https://github.com/crunchy-labs/crunchy-cli/issues/231)
|
|
||||||
let mut hardsub_locales = stream.streaming_hardsub_locales();
|
|
||||||
let (hardsub_locale, mut contains_hardsub) = if !hardsub_locales
|
|
||||||
.contains(&Locale::Custom("".to_string()))
|
|
||||||
&& !hardsub_locales.contains(&Locale::Custom(":".to_string()))
|
|
||||||
{
|
|
||||||
// if only one hardsub locale exists, assume that this stream doesn't really contains hardsubs
|
|
||||||
if hardsub_locales.len() == 1 {
|
|
||||||
(Some(hardsub_locales.remove(0)), false)
|
|
||||||
} else {
|
} else {
|
||||||
// fallback to `None`. this should trigger an error message in `stream.dash_streaming_data`
|
|
||||||
// that the requested stream is not available
|
|
||||||
(None, false)
|
(None, false)
|
||||||
}
|
|
||||||
} else {
|
|
||||||
let hardsubs_requested = subtitle.is_some();
|
|
||||||
(subtitle, hardsubs_requested)
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut streaming_data = match stream.dash_streaming_data(hardsub_locale).await {
|
let (mut videos, mut audios) = match stream.stream_data(hardsub_locale).await {
|
||||||
Ok(data) => data,
|
Ok(data) => data,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
// the error variant is only `crunchyroll_rs::error::Error::Input` when the requested
|
// the error variant is only `crunchyroll_rs::error::Error::Input` when the requested
|
||||||
// hardsub is not available
|
// hardsub is not available
|
||||||
if let crunchyroll_rs::error::Error::Input { .. } = e {
|
if let crunchyroll_rs::error::Error::Input { .. } = e {
|
||||||
contains_hardsub = false;
|
contains_hardsub = false;
|
||||||
stream.dash_streaming_data(None).await?
|
stream.stream_data(None).await?
|
||||||
} else {
|
} else {
|
||||||
bail!(e)
|
bail!(e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
streaming_data
|
.unwrap();
|
||||||
.0
|
|
||||||
.sort_by(|a, b| a.bandwidth.cmp(&b.bandwidth).reverse());
|
if videos.iter().any(|v| v.drm.is_some()) || audios.iter().any(|v| v.drm.is_some()) {
|
||||||
streaming_data
|
bail!("Stream is DRM protected")
|
||||||
.1
|
}
|
||||||
.sort_by(|a, b| a.bandwidth.cmp(&b.bandwidth).reverse());
|
|
||||||
|
videos.sort_by(|a, b| a.bandwidth.cmp(&b.bandwidth).reverse());
|
||||||
|
audios.sort_by(|a, b| a.bandwidth.cmp(&b.bandwidth).reverse());
|
||||||
|
|
||||||
let video_variant = match resolution.height {
|
let video_variant = match resolution.height {
|
||||||
u64::MAX => Some(streaming_data.0.into_iter().next().unwrap()),
|
u64::MAX => Some(videos.into_iter().next().unwrap()),
|
||||||
u64::MIN => Some(streaming_data.0.into_iter().last().unwrap()),
|
u64::MIN => Some(videos.into_iter().last().unwrap()),
|
||||||
_ => streaming_data
|
_ => videos
|
||||||
.0
|
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.find(|v| resolution.height == v.resolution.height),
|
.find(|v| resolution.height == v.resolution().unwrap().height),
|
||||||
};
|
};
|
||||||
Ok(video_variant.map(|v| {
|
Ok(video_variant.map(|v| (v, audios.first().unwrap().clone(), contains_hardsub)))
|
||||||
(
|
|
||||||
v,
|
|
||||||
streaming_data.1.first().unwrap().clone(),
|
|
||||||
contains_hardsub,
|
|
||||||
)
|
|
||||||
}))
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
12
flake.lock
generated
12
flake.lock
generated
|
|
@ -2,11 +2,11 @@
|
||||||
"nodes": {
|
"nodes": {
|
||||||
"nixpkgs": {
|
"nixpkgs": {
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1707877513,
|
"lastModified": 1710534455,
|
||||||
"narHash": "sha256-sp0w2apswd3wv0sAEF7StOGHkns3XUQaO5erhWFZWXk=",
|
"narHash": "sha256-huQT4Xs0y4EeFKn2BTBVYgEwJSv8SDlm82uWgMnCMmI=",
|
||||||
"owner": "NixOS",
|
"owner": "NixOS",
|
||||||
"repo": "nixpkgs",
|
"repo": "nixpkgs",
|
||||||
"rev": "89653a03e0915e4a872788d10680e7eec92f8600",
|
"rev": "9af9c1c87ed3e3ed271934cb896e0cdd33dae212",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
|
|
@ -41,11 +41,11 @@
|
||||||
"systems": "systems"
|
"systems": "systems"
|
||||||
},
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1705309234,
|
"lastModified": 1710146030,
|
||||||
"narHash": "sha256-uNRRNRKmJyCRC/8y1RqBkqWBLM034y4qN7EprSdmgyA=",
|
"narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=",
|
||||||
"owner": "numtide",
|
"owner": "numtide",
|
||||||
"repo": "flake-utils",
|
"repo": "flake-utils",
|
||||||
"rev": "1ef2e671c3b0c19053962c07dbda38332dcebf26",
|
"rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
|
|
|
||||||
|
|
@ -26,7 +26,7 @@
|
||||||
};
|
};
|
||||||
|
|
||||||
buildNoDefaultFeatures = true;
|
buildNoDefaultFeatures = true;
|
||||||
buildFeatures = [ "openssl" ];
|
buildFeatures = [ "openssl-tls" ];
|
||||||
|
|
||||||
nativeBuildInputs = [
|
nativeBuildInputs = [
|
||||||
pkgs.pkg-config
|
pkgs.pkg-config
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue