about summary refs log tree commit diff stats
path: root/pkgs
diff options
context:
space:
mode:
authorBenedikt Peetz <benedikt.peetz@b-peetz.de>2024-08-18 17:29:34 +0200
committerBenedikt Peetz <benedikt.peetz@b-peetz.de>2024-08-20 15:39:25 +0200
commit08773e74c8c78b8c342650cbc89677da8f040777 (patch)
treec9250363bc0e0db22952585865e3cd60a9647010 /pkgs
parentfix(home/pkgs/{mpc-beetsrm, mpc-searchadd}): Propagate the overriden beets pa... (diff)
downloadnixos-config-08773e74c8c78b8c342650cbc89677da8f040777.tar.gz
nixos-config-08773e74c8c78b8c342650cbc89677da8f040777.zip
feat(pkgs/yt): Start the rewrite
Diffstat (limited to 'pkgs')
-rw-r--r--pkgs/by-name/yt/yt/.cargo/config.toml6
-rw-r--r--[-rwxr-xr-x]pkgs/by-name/yt/yt/.env4
-rw-r--r--pkgs/by-name/yt/yt/.envrc7
-rw-r--r--pkgs/by-name/yt/yt/.licensure.yml197
-rw-r--r--pkgs/by-name/yt/yt/Cargo.lock1861
-rw-r--r--pkgs/by-name/yt/yt/Cargo.toml42
-rw-r--r--pkgs/by-name/yt/yt/build.rs7
-rw-r--r--pkgs/by-name/yt/yt/flake.lock6
-rw-r--r--pkgs/by-name/yt/yt/flake.nix26
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/.gitignore4
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/CHANGELOG.md27
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/Cargo.toml26
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/LICENSE174
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/README.md23
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/examples/events.rs83
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/examples/opengl.rs129
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/examples/protocol.rs77
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/Cargo.toml11
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/LICENSE174
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/README.md1
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/build.rs26
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/include/client.h2032
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/include/render.h759
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/include/render_gl.h211
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/include/stream_cb.h247
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/src/lib.rs12
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/src/lib.rs96
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/src/mpv.rs610
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/src/mpv/errors.rs100
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/src/mpv/events.rs373
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/src/mpv/protocol.rs251
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/src/mpv/render.rs396
-rw-r--r--pkgs/by-name/yt/yt/libmpv2/src/tests.rs212
-rwxr-xr-xpkgs/by-name/yt/yt/libmpv2/update.sh4
-rwxr-xr-xpkgs/by-name/yt/yt/scripts/mkdb.sh9
-rw-r--r--pkgs/by-name/yt/yt/src/app.rs29
-rw-r--r--pkgs/by-name/yt/yt/src/bin/yt/main.rs91
-rw-r--r--pkgs/by-name/yt/yt/src/bin/ytc/args.rs26
-rw-r--r--pkgs/by-name/yt/yt/src/bin/ytc/main.rs77
-rw-r--r--pkgs/by-name/yt/yt/src/bin/yts/args.rs41
-rw-r--r--pkgs/by-name/yt/yt/src/bin/yts/main.rs91
-rw-r--r--pkgs/by-name/yt/yt/src/cache/mod.rs63
-rw-r--r--pkgs/by-name/yt/yt/src/cli.rs114
-rw-r--r--pkgs/by-name/yt/yt/src/comments/comment.rs53
-rw-r--r--pkgs/by-name/yt/yt/src/comments/display.rs107
-rw-r--r--pkgs/by-name/yt/yt/src/comments/mod.rs187
-rw-r--r--pkgs/by-name/yt/yt/src/constants.rs52
-rw-r--r--pkgs/by-name/yt/yt/src/download/download_options.rs97
-rw-r--r--pkgs/by-name/yt/yt/src/download/mod.rs152
-rw-r--r--pkgs/by-name/yt/yt/src/downloader.rs212
-rw-r--r--pkgs/by-name/yt/yt/src/lib.rs185
-rw-r--r--pkgs/by-name/yt/yt/src/main.rs126
-rw-r--r--pkgs/by-name/yt/yt/src/select/mod.rs122
-rw-r--r--pkgs/by-name/yt/yt/src/select/selection_file/display.rs82
-rw-r--r--pkgs/by-name/yt/yt/src/select/selection_file/duration.rs60
-rw-r--r--pkgs/by-name/yt/yt/src/select/selection_file/help.str (renamed from pkgs/by-name/yt/yt/src/help.str)0
-rw-r--r--pkgs/by-name/yt/yt/src/select/selection_file/mod.rs79
-rw-r--r--pkgs/by-name/yt/yt/src/status/mod.rs50
-rw-r--r--pkgs/by-name/yt/yt/src/storage/mod.rs2
-rw-r--r--pkgs/by-name/yt/yt/src/storage/subscriptions.rs125
-rw-r--r--pkgs/by-name/yt/yt/src/storage/video_database/downloader.rs180
-rw-r--r--pkgs/by-name/yt/yt/src/storage/video_database/extractor_hash.rs106
-rw-r--r--pkgs/by-name/yt/yt/src/storage/video_database/getters.rs176
-rw-r--r--pkgs/by-name/yt/yt/src/storage/video_database/mod.rs115
-rw-r--r--pkgs/by-name/yt/yt/src/storage/video_database/schema.sql17
-rw-r--r--pkgs/by-name/yt/yt/src/storage/video_database/setters.rs127
-rw-r--r--pkgs/by-name/yt/yt/src/subscribe/mod.rs132
-rw-r--r--pkgs/by-name/yt/yt/src/update/mod.rs226
-rw-r--r--pkgs/by-name/yt/yt/src/watch/mod.rs97
-rwxr-xr-xpkgs/by-name/yt/yt/update.sh3
-rw-r--r--pkgs/by-name/yt/yt/yt_dlp/.cargo/config.toml2
-rw-r--r--pkgs/by-name/yt/yt/yt_dlp/.gitignore8
-rw-r--r--pkgs/by-name/yt/yt/yt_dlp/Cargo.lock640
-rw-r--r--pkgs/by-name/yt/yt/yt_dlp/Cargo.toml14
-rw-r--r--pkgs/by-name/yt/yt/yt_dlp/README.md12
-rw-r--r--pkgs/by-name/yt/yt/yt_dlp/cog.toml25
-rw-r--r--pkgs/by-name/yt/yt/yt_dlp/src/duration.rs61
-rw-r--r--pkgs/by-name/yt/yt/yt_dlp/src/lib.rs400
-rw-r--r--pkgs/by-name/yt/yt/yt_dlp/src/logging.rs115
-rw-r--r--pkgs/by-name/yt/yt/yt_dlp/src/main.rs86
-rw-r--r--pkgs/by-name/yt/yt/yt_dlp/src/wrapper/info_json.rs499
-rw-r--r--pkgs/by-name/yt/yt/yt_dlp/src/wrapper/mod.rs2
-rw-r--r--pkgs/by-name/yt/yt/yt_dlp/src/wrapper/yt_dlp_options.rs52
-rwxr-xr-xpkgs/by-name/yt/yt/yt_dlp/update.sh4
84 files changed, 12673 insertions, 872 deletions
diff --git a/pkgs/by-name/yt/yt/.cargo/config.toml b/pkgs/by-name/yt/yt/.cargo/config.toml
new file mode 100644
index 00000000..6c88c6ba
--- /dev/null
+++ b/pkgs/by-name/yt/yt/.cargo/config.toml
@@ -0,0 +1,6 @@
+[env]
+PYO3_PYTHON = "/nix/store/7xzk119acyws2c4ysygdv66l0grxkr39-python3-3.11.9-env/bin/python3"
+
+[build]
+# rustflags = ["-C", "link-args=-fuse-ld=mold,--no-rosegment"]
+rustflags = ["-Clink-arg=-fuse-ld=mold", "-Clink-arg=-Wl,--no-rosegment"]
diff --git a/pkgs/by-name/yt/yt/.env b/pkgs/by-name/yt/yt/.env
index 8018a738..72ec032c 100755..100644
--- a/pkgs/by-name/yt/yt/.env
+++ b/pkgs/by-name/yt/yt/.env
@@ -1,3 +1 @@
-#!/usr/bin/env sh
-
-PATH="$(pwd)/target/release/:$(pwd)/target/debug/:$PATH"
+DATABASE_URL=sqlite://target/database.sqlite
diff --git a/pkgs/by-name/yt/yt/.envrc b/pkgs/by-name/yt/yt/.envrc
index 3550a30f..397e8e50 100644
--- a/pkgs/by-name/yt/yt/.envrc
+++ b/pkgs/by-name/yt/yt/.envrc
@@ -1 +1,8 @@
+#!/usr/bin/env sh
 use flake
+
+PATH_add ./target/debug
+PATH_add ./target/release
+PATH_add ./target/profiling
+
+export PYO3_PYTHON=python3
diff --git a/pkgs/by-name/yt/yt/.licensure.yml b/pkgs/by-name/yt/yt/.licensure.yml
new file mode 100644
index 00000000..d528ee39
--- /dev/null
+++ b/pkgs/by-name/yt/yt/.licensure.yml
@@ -0,0 +1,197 @@
+---
+# Regexes which if matched by a file path will always be excluded from
+# getting a license header
+excludes:
+  - .*lock
+  - \.git/.*
+  - LICENSE.spdx
+  - LICENSE
+  - COPYING
+  - COPYING.LESSER
+  - .*\.(rst|txt|pdf)
+# Definition of the licenses used on this project and to what files
+# they should apply.
+#
+# No default license configuration is provided. This section must be
+# configured by the user.
+licenses:
+  - files: \.tex
+    ident: CC-BY-SA-4.0
+    authors:
+      - name: "Benedikt Peetz"
+        email: "benedikt.peetz@b-peetz.de"
+
+    template: |
+      Yt_py 2024 - [year] (C) by [name of author]
+      SPDX-License-Identifier: CC-BY-SA-4.0
+
+      Yt_py is licensed under a
+      Creative Commons Attribution-ShareAlike 4.0 International License.
+
+      You should have received a copy of the license along with this
+      work.  If not, see <https://creativecommons.org/licenses/by-sa/4.0/>.
+
+    unwrap_text: false
+
+  # Either a regex or the string "any" to determine to what files this
+  # license should apply. It is common for projects to have files
+  # under multiple licenses or with multiple copyright holders. This
+  # provides the ability to automatically license files correctly
+  # based on their file paths.
+  #
+  # If "any" is provided all files will match this license.
+  - files: any
+    #
+    #   The license identifier, a list of common identifiers can be
+    #   found at: https://spdx.org/licenses/ but existence of the ident
+    #   in this list it is not enforced unless auto_template is set to
+    #   true.
+    ident: GPL-3.0-or-later
+    #
+    #   A list of authors who hold copyright over these files
+    authors:
+      # Provide either your full name or company name for copyright purposes
+      - name: "Benedikt Peetz"
+        # Optionally provide email for copyright purposes
+        email: "benedikt.peetz@b-peetz.de"
+
+    #   The template that will be rendered to generate the header before
+    #   comment characters are applied. Available variables are:
+    #    - [year]: substituted with the current year.
+    #    - [name of author]: Substituted with name of the author and email
+    #      if provided. If email is provided the output appears as Full
+    #      Name <email@example.com>. If multiple authors are provided the
+    #      list is concatenated together with commas.
+    template: |
+        Copyright (C) 2024 - [year]:
+        [name of author]
+        SPDX-License-Identifier: GPL-3.0-or-later
+
+        This file is part of Yt_py.
+
+        Yt_py is free software: you can redistribute it and/or modify
+        it under the terms of the Lesser GNU General Public License as
+        published by the Free Software Foundation, either version 3 of
+        the License, or (at your option) any later version.
+
+        This program is distributed in the hope that it will be useful,
+        but WITHOUT ANY WARRANTY; without even the implied warranty of
+        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+        GNU General Public License for more details.
+
+        You should have received a copy of the GNU General Public License
+        along with this program.
+        If not, see <https://www.gnu.org/licenses/>.
+
+
+    #   If auto_template is true then template is ignored and the SPDX
+    #   API will be queried with the ident value to automatically
+    #   determine the license header template. auto_template works best
+    #   with licenses that have a standardLicenseHeader field defined in
+    #   their license info JSON, if it is not then we will use the full
+    #   licenseText to generate the header which works fine for short
+    #   licenses like MIT but can be quite lengthy for other licenses
+    #   like BSD-4-Clause. The above default template is valid for most
+    #   licenses and is recommended for MIT, and BSD licenses. Common
+    #   licenses that work well with the auto_template feature are GPL
+    #   variants, and the Apache 2.0 license.
+    #
+    #   Important Note: this means the ident must be a valid SPDX identifier
+    # auto_template: true
+
+    #   If true try to detect the text wrapping of the template, and unwrap it
+    unwrap_text: false
+
+# Define type of comment characters to apply based on file extensions.
+comments:
+  # The extensions (or singular extension) field defines which file
+  # extensions to apply the commenter to.
+  - extensions:
+      - js
+      - go
+      - pest
+    # The commenter field defines the kind of commenter to
+    # generate. There are two types of commenters: line and block.
+    #
+    # This demonstrates a line commenter configuration. A line
+    # commenter type will apply the comment_char to the beginning of
+    # each line in the license header. It will then apply a number of
+    # empty newlines to the end of the header equal to trailing_lines.
+    #
+    # If trailing_lines is omitted it is assumed to be 0.
+    commenter:
+      type: line
+      comment_char: "//"
+      trailing_lines: 1
+
+  - extensions:
+      - rs
+      - tri
+      - css
+      - cpp
+      - c
+      - h
+    # This demonstrates a block commenter configuration. A block
+    # commenter type will add start_block_char as the first character
+    # in the license header and add end_block_char as the last character
+    # in the license header. If per_line_char is provided each line of
+    # the header between the block start and end characters will be
+    # line commented with the per_line_char
+    #
+    # trailing_lines works the same for both block and line commenter
+    # types
+    commenter:
+      type: block
+      start_block_char: "/*\n"
+      end_block_char: "*/\n"
+      per_line_char: "*"
+      trailing_lines: 1
+
+  - extension:
+      - html
+      - md
+    commenter:
+      type: block
+      start_block_char: "<!--\n"
+      end_block_char: "-->\n"
+      trailing_lines: 1
+
+  - extensions:
+      - el
+      - lisp
+    commenter:
+      type: line
+      comment_char: ";;;"
+      trailing_lines: 1
+
+  - extensions:
+      - tex
+      - bib
+    commenter:
+      type: line
+      comment_char: "%"
+      trailing_lines: 1
+
+  - extensions:
+      - ebnf
+    commenter:
+      type: block
+      start_block_char: "#(*\n"
+      end_block_char: "#*)\n"
+      per_line_char: "#"
+      trailing_lines: 1
+
+
+  # The extension string "any" is special and so will match any file
+  # extensions. Commenter configurations are always checked in the
+  # order they are defined, so if any is used it should be the last
+  # commenter configuration or else it will override all others.
+  #
+  # In this configuration if we can't match the file extension we fall
+  # back to the popular '#' line comment used in most scripting
+  # languages.
+  - extension: any
+    commenter:
+      type: line
+      comment_char: '#'
+      trailing_lines: 1
diff --git a/pkgs/by-name/yt/yt/Cargo.lock b/pkgs/by-name/yt/yt/Cargo.lock
index 885bdaab..1342e29b 100644
--- a/pkgs/by-name/yt/yt/Cargo.lock
+++ b/pkgs/by-name/yt/yt/Cargo.lock
@@ -3,6 +3,49 @@
 version = 3
 
 [[package]]
+name = "addr2line"
+version = "0.22.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e4503c46a5c0c7844e948c9a4d6acd9f50cccb4de1c48eb9e291ea17470c678"
+dependencies = [
+ "gimli",
+]
+
+[[package]]
+name = "adler"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
+
+[[package]]
+name = "ahash"
+version = "0.8.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011"
+dependencies = [
+ "cfg-if",
+ "getrandom",
+ "once_cell",
+ "version_check",
+ "zerocopy 0.7.35",
+]
+
+[[package]]
+name = "aho-corasick"
+version = "1.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "allocator-api2"
+version = "0.2.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f"
+
+[[package]]
 name = "android-tzdata"
 version = "0.1.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -19,9 +62,9 @@ dependencies = [
 
 [[package]]
 name = "anstream"
-version = "0.6.14"
+version = "0.6.15"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "418c75fa768af9c03be99d17643f93f79bbba589895012a80e3452a19ddda15b"
+checksum = "64e15c1ab1f89faffbf04a634d5e1962e9074f2741eef6d97f3c4e322426d526"
 dependencies = [
  "anstyle",
  "anstyle-parse",
@@ -34,36 +77,36 @@ dependencies = [
 
 [[package]]
 name = "anstyle"
-version = "1.0.7"
+version = "1.0.8"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "038dfcf04a5feb68e9c60b21c9625a54c2c0616e79b72b0fd87075a056ae1d1b"
+checksum = "1bec1de6f59aedf83baf9ff929c98f2ad654b97c9510f4e70cf6f661d49fd5b1"
 
 [[package]]
 name = "anstyle-parse"
-version = "0.2.4"
+version = "0.2.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c03a11a9034d92058ceb6ee011ce58af4a9bf61491aa7e1e59ecd24bd40d22d4"
+checksum = "eb47de1e80c2b463c735db5b217a0ddc39d612e7ac9e2e96a5aed1f57616c1cb"
 dependencies = [
  "utf8parse",
 ]
 
 [[package]]
 name = "anstyle-query"
-version = "1.0.3"
+version = "1.1.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a64c907d4e79225ac72e2a354c9ce84d50ebb4586dee56c82b3ee73004f537f5"
+checksum = "6d36fc52c7f6c869915e99412912f22093507da8d9e942ceaf66fe4b7c14422a"
 dependencies = [
- "windows-sys",
+ "windows-sys 0.52.0",
 ]
 
 [[package]]
 name = "anstyle-wincon"
-version = "3.0.3"
+version = "3.0.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "61a38449feb7068f52bb06c12759005cf459ee52bb4adc1d5a7c4322d716fb19"
+checksum = "5bf74e1b6e971609db8ca7a9ce79fd5768ab6ae46441c572e46cf596f59e57f8"
 dependencies = [
  "anstyle",
- "windows-sys",
+ "windows-sys 0.52.0",
 ]
 
 [[package]]
@@ -73,16 +116,118 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "b3d1d046238990b9cf5bcde22a3fb3584ee5cf65fb2765f454ed428c7a0063da"
 
 [[package]]
+name = "arrayref"
+version = "0.3.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d151e35f61089500b617991b791fc8bfd237ae50cd5950803758a179b41e67a"
+
+[[package]]
+name = "arrayvec"
+version = "0.7.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711"
+
+[[package]]
+name = "atoi"
+version = "2.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
 name = "autocfg"
 version = "1.3.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0"
 
 [[package]]
+name = "backtrace"
+version = "0.3.73"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5cc23269a4f8976d0a4d2e7109211a419fe30e8d88d677cd60b6bc79c5732e0a"
+dependencies = [
+ "addr2line",
+ "cc",
+ "cfg-if",
+ "libc",
+ "miniz_oxide",
+ "object",
+ "rustc-demangle",
+]
+
+[[package]]
+name = "base64"
+version = "0.21.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"
+
+[[package]]
+name = "base64ct"
+version = "1.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b"
+
+[[package]]
+name = "bindgen"
+version = "0.69.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a00dc851838a2120612785d195287475a3ac45514741da670b735818822129a0"
+dependencies = [
+ "bitflags 2.6.0",
+ "cexpr",
+ "clang-sys",
+ "itertools",
+ "lazy_static",
+ "lazycell",
+ "log",
+ "prettyplease",
+ "proc-macro2",
+ "quote",
+ "regex",
+ "rustc-hash",
+ "shlex",
+ "syn 2.0.72",
+ "which",
+]
+
+[[package]]
+name = "bitflags"
+version = "1.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
+
+[[package]]
 name = "bitflags"
-version = "2.5.0"
+version = "2.6.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1"
+checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "blake3"
+version = "1.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e9ec96fe9a81b5e365f9db71fe00edc4fe4ca2cc7dcb7861f0603012a7caa210"
+dependencies = [
+ "arrayref",
+ "arrayvec",
+ "cc",
+ "cfg-if",
+ "constant_time_eq",
+]
+
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
 
 [[package]]
 name = "bumpalo"
@@ -91,10 +236,31 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"
 
 [[package]]
+name = "byteorder"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
+
+[[package]]
+name = "bytes"
+version = "1.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fca2be1d5c43812bae364ee3f30b3afcb7877cf59f4aeb94c66f313a41d2fac9"
+
+[[package]]
 name = "cc"
-version = "1.0.98"
+version = "1.1.7"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "41c270e7540d725e65ac7f1b212ac8ce349719624d7bcff99f8e2e488e8cf03f"
+checksum = "26a5c3fd7bfa1ce3897a3a3501d362b2d87b7f2583ebcb4a949ec25911025cbc"
+
+[[package]]
+name = "cexpr"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
+dependencies = [
+ "nom",
+]
 
 [[package]]
 name = "cfg-if"
@@ -113,14 +279,34 @@ dependencies = [
  "js-sys",
  "num-traits",
  "wasm-bindgen",
- "windows-targets",
+ "windows-targets 0.52.6",
+]
+
+[[package]]
+name = "chrono-humanize"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "799627e6b4d27827a814e837b9d8a504832086081806d45b1afa34dc982b023b"
+dependencies = [
+ "chrono",
+]
+
+[[package]]
+name = "clang-sys"
+version = "1.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4"
+dependencies = [
+ "glob",
+ "libc",
+ "libloading",
 ]
 
 [[package]]
 name = "clap"
-version = "4.5.4"
+version = "4.5.13"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "90bc066a67923782aa8515dbaea16946c5bcc5addbd668bb80af688e53e548a0"
+checksum = "0fbb260a053428790f3de475e304ff84cdbc4face759ea7a3e64c1edd938a7fc"
 dependencies = [
  "clap_builder",
  "clap_derive",
@@ -128,9 +314,9 @@ dependencies = [
 
 [[package]]
 name = "clap_builder"
-version = "4.5.2"
+version = "4.5.13"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ae129e2e766ae0ec03484e609954119f123cc1fe650337e155d03b022f24f7b4"
+checksum = "64b17d7ea74e9f833c7dbf2cbe4fb12ff26783eda4782a8975b72f895c9b4d99"
 dependencies = [
  "anstream",
  "anstyle",
@@ -140,39 +326,39 @@ dependencies = [
 
 [[package]]
 name = "clap_derive"
-version = "4.5.4"
+version = "4.5.13"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "528131438037fd55894f62d6e9f068b8f45ac57ffa77517819645d10aed04f64"
+checksum = "501d359d5f3dcaf6ecdeee48833ae73ec6e42723a1e52419c79abf9507eec0a0"
 dependencies = [
- "heck",
+ "heck 0.5.0",
  "proc-macro2",
  "quote",
- "syn",
+ "syn 2.0.72",
 ]
 
 [[package]]
 name = "clap_lex"
-version = "0.7.0"
+version = "0.7.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "98cc8fbded0c607b7ba9dd60cd98df59af97e84d24e49c8557331cfc26d301ce"
+checksum = "1462739cb27611015575c0c11df5df7601141071f07518d56fcc1be504cbec97"
 
 [[package]]
-name = "cli-log"
-version = "2.0.0"
+name = "colorchoice"
+version = "1.0.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3d2ab00dc4c82ec28af25ac085aecc11ffeabf353755715a3113a7aa044ca5cc"
-dependencies = [
- "chrono",
- "file-size",
- "log",
- "proc-status",
-]
+checksum = "d3fd119d74b830634cea2a0f58bbd0d54540518a14397557951e79340abc28c0"
 
 [[package]]
-name = "colorchoice"
-version = "1.0.1"
+name = "const-oid"
+version = "0.9.6"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0b6a852b24ab71dffc585bcb46eaf7959d175cb865a7152e35b348d1b2960422"
+checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
+
+[[package]]
+name = "constant_time_eq"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f7144d30dcf0fafbce74250a3963025d8d52177934239851c917d29f1df280c2"
 
 [[package]]
 name = "core-foundation-sys"
@@ -181,26 +367,141 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
 
 [[package]]
+name = "cpufeatures"
+version = "0.2.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53fe5e26ff1b7aef8bca9c6080520cfb8d9333c7568e1829cef191a9723e5504"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crc"
+version = "3.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69e6e4d7b33a94f0991c26729976b10ebde1d34c3ee82408fb536164fa10d636"
+dependencies = [
+ "crc-catalog",
+]
+
+[[package]]
+name = "crc-catalog"
+version = "2.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5"
+
+[[package]]
+name = "crossbeam-queue"
+version = "0.3.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df0346b5d5e76ac2fe4e327c5fd1118d6be7c51dfb18f9b7922923f287471e35"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80"
+
+[[package]]
+name = "crypto-common"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
+[[package]]
+name = "der"
+version = "0.7.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f55bf8e7b65898637379c1b74eb1551107c8294ed26d855ceb9fd1a09cfc9bc0"
+dependencies = [
+ "const-oid",
+ "pem-rfc7468",
+ "zeroize",
+]
+
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer",
+ "const-oid",
+ "crypto-common",
+ "subtle",
+]
+
+[[package]]
+name = "dotenvy"
+version = "0.15.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b"
+
+[[package]]
+name = "either"
+version = "1.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "equivalent"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5"
+
+[[package]]
 name = "errno"
 version = "0.3.9"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba"
 dependencies = [
  "libc",
- "windows-sys",
+ "windows-sys 0.52.0",
 ]
 
 [[package]]
+name = "etcetera"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943"
+dependencies = [
+ "cfg-if",
+ "home",
+ "windows-sys 0.48.0",
+]
+
+[[package]]
+name = "event-listener"
+version = "2.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0"
+
+[[package]]
 name = "fastrand"
 version = "2.1.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a"
 
 [[package]]
-name = "file-size"
-version = "1.0.3"
+name = "flume"
+version = "0.11.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9544f10105d33957765016b8a9baea7e689bf1f0f2f32c2fa2f568770c38d2b3"
+checksum = "55ac459de2512911e4b674ce33cf20befaba382d05b62b008afc1c8b57cbf181"
+dependencies = [
+ "futures-core",
+ "futures-sink",
+ "spin",
+]
 
 [[package]]
 name = "form_urlencoded"
@@ -212,12 +513,212 @@ dependencies = [
 ]
 
 [[package]]
+name = "futures"
+version = "0.3.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "645c6916888f6cb6350d2550b80fb63e734897a8498abe35cfb732b6487804b0"
+dependencies = [
+ "futures-channel",
+ "futures-core",
+ "futures-executor",
+ "futures-io",
+ "futures-sink",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-channel"
+version = "0.3.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78"
+dependencies = [
+ "futures-core",
+ "futures-sink",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d"
+
+[[package]]
+name = "futures-executor"
+version = "0.3.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a576fc72ae164fca6b9db127eaa9a9dda0d61316034f33a0a0d4eda41f02b01d"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-intrusive"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f"
+dependencies = [
+ "futures-core",
+ "lock_api",
+ "parking_lot",
+]
+
+[[package]]
+name = "futures-io"
+version = "0.3.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1"
+
+[[package]]
+name = "futures-macro"
+version = "0.3.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.72",
+]
+
+[[package]]
+name = "futures-sink"
+version = "0.3.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5"
+
+[[package]]
+name = "futures-task"
+version = "0.3.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004"
+
+[[package]]
+name = "futures-util"
+version = "0.3.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48"
+dependencies = [
+ "futures-channel",
+ "futures-core",
+ "futures-io",
+ "futures-macro",
+ "futures-sink",
+ "futures-task",
+ "memchr",
+ "pin-project-lite",
+ "pin-utils",
+ "slab",
+]
+
+[[package]]
+name = "generic-array"
+version = "0.14.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.2.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "wasi",
+]
+
+[[package]]
+name = "gimli"
+version = "0.29.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "40ecd4077b5ae9fd2e9e169b102c6c330d0605168eb0e8bf79952b256dbefffd"
+
+[[package]]
+name = "glob"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b"
+
+[[package]]
+name = "hashbrown"
+version = "0.14.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
+dependencies = [
+ "ahash",
+ "allocator-api2",
+]
+
+[[package]]
+name = "hashlink"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8094feaf31ff591f651a2664fb9cfd92bba7a60ce3197265e9482ebe753c8f7"
+dependencies = [
+ "hashbrown",
+]
+
+[[package]]
+name = "heck"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
+dependencies = [
+ "unicode-segmentation",
+]
+
+[[package]]
 name = "heck"
 version = "0.5.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
 
 [[package]]
+name = "hermit-abi"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024"
+
+[[package]]
+name = "hex"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+
+[[package]]
+name = "hkdf"
+version = "0.12.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"
+dependencies = [
+ "hmac",
+]
+
+[[package]]
+name = "hmac"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
+dependencies = [
+ "digest",
+]
+
+[[package]]
+name = "home"
+version = "0.5.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3d1354bf6b7235cb4a0576c2619fd4ed18183f689b12b006a0ee7329eeff9a5"
+dependencies = [
+ "windows-sys 0.52.0",
+]
+
+[[package]]
 name = "iana-time-zone"
 version = "0.1.60"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -251,10 +752,46 @@ dependencies = [
 ]
 
 [[package]]
+name = "indexmap"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "de3fc2e30ba82dd1b3911c8de1ffc143c74a914a14e99514d7637e3099df5ea0"
+dependencies = [
+ "equivalent",
+ "hashbrown",
+]
+
+[[package]]
+name = "indoc"
+version = "2.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b248f5224d1d606005e02c97f5aa4e88eeb230488bcc03bc9ca4d7991399f2b5"
+
+[[package]]
+name = "is-terminal"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f23ff5ef2b80d608d61efee834934d862cd92461afc0560dedf493e4c033738b"
+dependencies = [
+ "hermit-abi",
+ "libc",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
 name = "is_terminal_polyfill"
-version = "1.70.0"
+version = "1.70.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f8478577c03552c21db0e2724ffb8986a5ce7af88107e6be5d2ee6e158c12800"
+checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf"
+
+[[package]]
+name = "itertools"
+version = "0.10.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"
+dependencies = [
+ "either",
+]
 
 [[package]]
 name = "itoa"
@@ -272,22 +809,189 @@ dependencies = [
 ]
 
 [[package]]
+name = "lazy_static"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
+dependencies = [
+ "spin",
+]
+
+[[package]]
+name = "lazycell"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55"
+
+[[package]]
 name = "libc"
 version = "0.2.155"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c"
 
 [[package]]
+name = "libloading"
+version = "0.8.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4979f22fdb869068da03c9f7528f8297c6fd2606bc3a4affe42e6a823fdb8da4"
+dependencies = [
+ "cfg-if",
+ "windows-targets 0.52.6",
+]
+
+[[package]]
+name = "libm"
+version = "0.2.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058"
+
+[[package]]
+name = "libmpv2"
+version = "4.0.0"
+dependencies = [
+ "libmpv2-sys",
+ "log",
+ "thiserror",
+]
+
+[[package]]
+name = "libmpv2-sys"
+version = "4.0.0"
+dependencies = [
+ "bindgen",
+]
+
+[[package]]
+name = "libsqlite3-sys"
+version = "0.27.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf4e226dcd58b4be396f7bd3c20da8fdee2911400705297ba7d2d7cc2c30f716"
+dependencies = [
+ "cc",
+ "pkg-config",
+ "vcpkg",
+]
+
+[[package]]
 name = "linux-raw-sys"
 version = "0.4.14"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89"
 
 [[package]]
+name = "lock_api"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17"
+dependencies = [
+ "autocfg",
+ "scopeguard",
+]
+
+[[package]]
 name = "log"
-version = "0.4.21"
+version = "0.4.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24"
+
+[[package]]
+name = "md-5"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
+dependencies = [
+ "cfg-if",
+ "digest",
+]
+
+[[package]]
+name = "memchr"
+version = "2.7.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
+
+[[package]]
+name = "memoffset"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "minimal-lexical"
+version = "0.2.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c"
+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
+
+[[package]]
+name = "miniz_oxide"
+version = "0.7.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8a240ddb74feaf34a79a7add65a741f3167852fba007066dcac1ca548d89c08"
+dependencies = [
+ "adler",
+]
+
+[[package]]
+name = "mio"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4569e456d394deccd22ce1c1913e6ea0e54519f577285001215d33557431afe4"
+dependencies = [
+ "hermit-abi",
+ "libc",
+ "wasi",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "nom"
+version = "7.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
+dependencies = [
+ "memchr",
+ "minimal-lexical",
+]
+
+[[package]]
+name = "num-bigint-dig"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc84195820f291c7697304f3cbdadd1cb7199c0efc917ff5eafd71225c136151"
+dependencies = [
+ "byteorder",
+ "lazy_static",
+ "libm",
+ "num-integer",
+ "num-iter",
+ "num-traits",
+ "rand",
+ "smallvec",
+ "zeroize",
+]
+
+[[package]]
+name = "num-integer"
+version = "0.1.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "num-iter"
+version = "0.1.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf"
+dependencies = [
+ "autocfg",
+ "num-integer",
+ "num-traits",
+]
 
 [[package]]
 name = "num-traits"
@@ -296,6 +1000,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
 dependencies = [
  "autocfg",
+ "libm",
+]
+
+[[package]]
+name = "object"
+version = "0.36.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f203fa8daa7bb185f760ae12bd8e097f63d17041dcdcaf675ac54cdf863170e"
+dependencies = [
+ "memchr",
 ]
 
 [[package]]
@@ -305,27 +1019,183 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
 
 [[package]]
+name = "parking_lot"
+version = "0.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27"
+dependencies = [
+ "lock_api",
+ "parking_lot_core",
+]
+
+[[package]]
+name = "parking_lot_core"
+version = "0.9.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "redox_syscall 0.5.3",
+ "smallvec",
+ "windows-targets 0.52.6",
+]
+
+[[package]]
+name = "paste"
+version = "1.0.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
+
+[[package]]
+name = "pem-rfc7468"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412"
+dependencies = [
+ "base64ct",
+]
+
+[[package]]
 name = "percent-encoding"
 version = "2.3.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e"
 
 [[package]]
+name = "pin-project-lite"
+version = "0.2.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02"
+
+[[package]]
+name = "pin-utils"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
+
+[[package]]
+name = "pkcs1"
+version = "0.7.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f"
+dependencies = [
+ "der",
+ "pkcs8",
+ "spki",
+]
+
+[[package]]
+name = "pkcs8"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
+dependencies = [
+ "der",
+ "spki",
+]
+
+[[package]]
+name = "pkg-config"
+version = "0.3.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec"
+
+[[package]]
+name = "portable-atomic"
+version = "1.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da544ee218f0d287a911e9c99a39a8c9bc8fcad3cb8db5959940044ecfc67265"
+
+[[package]]
+name = "ppv-lite86"
+version = "0.2.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dee4364d9f3b902ef14fab8a1ddffb783a1cb6b4bba3bfc1fa3922732c7de97f"
+dependencies = [
+ "zerocopy 0.6.6",
+]
+
+[[package]]
+name = "prettyplease"
+version = "0.2.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5f12335488a2f3b0a83b14edad48dca9879ce89b2edd10e80237e4e852dd645e"
+dependencies = [
+ "proc-macro2",
+ "syn 2.0.72",
+]
+
+[[package]]
 name = "proc-macro2"
-version = "1.0.83"
+version = "1.0.86"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0b33eb56c327dec362a9e55b3ad14f9d2f0904fb5a5b03b513ab5465399e9f43"
+checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77"
 dependencies = [
  "unicode-ident",
 ]
 
 [[package]]
-name = "proc-status"
-version = "0.1.1"
+name = "pyo3"
+version = "0.21.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f0e0c0ac915e7b76b47850ba4ffc377abde6c6ff9eeace61d0a89623db449712"
+checksum = "a5e00b96a521718e08e03b1a622f01c8a8deb50719335de3f60b3b3950f069d8"
 dependencies = [
- "thiserror",
+ "cfg-if",
+ "indoc",
+ "libc",
+ "memoffset",
+ "parking_lot",
+ "portable-atomic",
+ "pyo3-build-config",
+ "pyo3-ffi",
+ "pyo3-macros",
+ "unindent",
+]
+
+[[package]]
+name = "pyo3-build-config"
+version = "0.21.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7883df5835fafdad87c0d888b266c8ec0f4c9ca48a5bed6bbb592e8dedee1b50"
+dependencies = [
+ "once_cell",
+ "target-lexicon",
+]
+
+[[package]]
+name = "pyo3-ffi"
+version = "0.21.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "01be5843dc60b916ab4dad1dca6d20b9b4e6ddc8e15f50c47fe6d85f1fb97403"
+dependencies = [
+ "libc",
+ "pyo3-build-config",
+]
+
+[[package]]
+name = "pyo3-macros"
+version = "0.21.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77b34069fc0682e11b31dbd10321cbf94808394c56fd996796ce45217dfac53c"
+dependencies = [
+ "proc-macro2",
+ "pyo3-macros-backend",
+ "quote",
+ "syn 2.0.72",
+]
+
+[[package]]
+name = "pyo3-macros-backend"
+version = "0.21.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08260721f32db5e1a5beae69a55553f56b99bd0e1c3e6e0a5e8851a9d0f5a85c"
+dependencies = [
+ "heck 0.4.1",
+ "proc-macro2",
+ "pyo3-build-config",
+ "quote",
+ "syn 2.0.72",
 ]
 
 [[package]]
@@ -338,16 +1208,125 @@ dependencies = [
 ]
 
 [[package]]
+name = "rand"
+version = "0.8.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
+dependencies = [
+ "libc",
+ "rand_chacha",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
+dependencies = [
+ "ppv-lite86",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
+dependencies = [
+ "getrandom",
+]
+
+[[package]]
+name = "redox_syscall"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa"
+dependencies = [
+ "bitflags 1.3.2",
+]
+
+[[package]]
+name = "redox_syscall"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2a908a6e00f1fdd0dfd9c0eb08ce85126f6d8bbda50017e74bc4a4b7d4a926a4"
+dependencies = [
+ "bitflags 2.6.0",
+]
+
+[[package]]
+name = "regex"
+version = "1.10.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b91213439dad192326a0d7c6ee3955910425f441d7038e0d6933b0aec5c4517f"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-automata",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.4.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a66a03ae7c801facd77a29370b4faec201768915ac14a721ba36f20bc9c209b"
+
+[[package]]
+name = "rsa"
+version = "0.9.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d0e5124fcb30e76a7e79bfee683a2746db83784b86289f6251b54b7950a0dfc"
+dependencies = [
+ "const-oid",
+ "digest",
+ "num-bigint-dig",
+ "num-integer",
+ "num-traits",
+ "pkcs1",
+ "pkcs8",
+ "rand_core",
+ "signature",
+ "spki",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "rustc-demangle"
+version = "0.1.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f"
+
+[[package]]
+name = "rustc-hash"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
+
+[[package]]
 name = "rustix"
 version = "0.38.34"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f"
 dependencies = [
- "bitflags",
+ "bitflags 2.6.0",
  "errno",
  "libc",
  "linux-raw-sys",
- "windows-sys",
+ "windows-sys 0.52.0",
 ]
 
 [[package]]
@@ -357,47 +1336,378 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f"
 
 [[package]]
+name = "scopeguard"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+
+[[package]]
 name = "serde"
-version = "1.0.202"
+version = "1.0.204"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "226b61a0d411b2ba5ff6d7f73a476ac4f8bb900373459cd00fab8512828ba395"
+checksum = "bc76f558e0cbb2a839d37354c575f1dc3fdc6546b5be373ba43d95f231bf7c12"
 dependencies = [
  "serde_derive",
 ]
 
 [[package]]
 name = "serde_derive"
-version = "1.0.202"
+version = "1.0.204"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6048858004bcff69094cd972ed40a32500f153bd3be9f716b2eed2e8217c4838"
+checksum = "e0cd7e117be63d3c3678776753929474f3b04a43a080c744d6b0ae2a8c28e222"
 dependencies = [
  "proc-macro2",
  "quote",
- "syn",
+ "syn 2.0.72",
 ]
 
 [[package]]
 name = "serde_json"
-version = "1.0.117"
+version = "1.0.121"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "455182ea6142b14f93f4bc5320a2b31c1f266b66a4a5c858b013302a5d8cbfc3"
+checksum = "4ab380d7d9f22ef3f21ad3e6c1ebe8e4fc7a2000ccba2e4d71fc96f15b2cb609"
 dependencies = [
  "itoa",
+ "memchr",
  "ryu",
  "serde",
 ]
 
 [[package]]
+name = "sha1"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
+[[package]]
+name = "sha2"
+version = "0.10.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
+[[package]]
+name = "shlex"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
+
+[[package]]
+name = "signal-hook-registry"
+version = "1.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "signature"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
+dependencies = [
+ "digest",
+ "rand_core",
+]
+
+[[package]]
+name = "slab"
+version = "0.4.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "smallvec"
+version = "1.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
+
+[[package]]
+name = "socket2"
+version = "0.5.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c"
+dependencies = [
+ "libc",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "spin"
+version = "0.9.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
+dependencies = [
+ "lock_api",
+]
+
+[[package]]
+name = "spki"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
+dependencies = [
+ "base64ct",
+ "der",
+]
+
+[[package]]
+name = "sqlformat"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f895e3734318cc55f1fe66258926c9b910c124d47520339efecbb6c59cec7c1f"
+dependencies = [
+ "nom",
+ "unicode_categories",
+]
+
+[[package]]
+name = "sqlx"
+version = "0.7.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c9a2ccff1a000a5a59cd33da541d9f2fdcd9e6e8229cc200565942bff36d0aaa"
+dependencies = [
+ "sqlx-core",
+ "sqlx-macros",
+ "sqlx-mysql",
+ "sqlx-postgres",
+ "sqlx-sqlite",
+]
+
+[[package]]
+name = "sqlx-core"
+version = "0.7.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24ba59a9342a3d9bab6c56c118be528b27c9b60e490080e9711a04dccac83ef6"
+dependencies = [
+ "ahash",
+ "atoi",
+ "byteorder",
+ "bytes",
+ "crc",
+ "crossbeam-queue",
+ "either",
+ "event-listener",
+ "futures-channel",
+ "futures-core",
+ "futures-intrusive",
+ "futures-io",
+ "futures-util",
+ "hashlink",
+ "hex",
+ "indexmap",
+ "log",
+ "memchr",
+ "once_cell",
+ "paste",
+ "percent-encoding",
+ "serde",
+ "serde_json",
+ "sha2",
+ "smallvec",
+ "sqlformat",
+ "thiserror",
+ "tokio",
+ "tokio-stream",
+ "tracing",
+ "url",
+]
+
+[[package]]
+name = "sqlx-macros"
+version = "0.7.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ea40e2345eb2faa9e1e5e326db8c34711317d2b5e08d0d5741619048a803127"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "sqlx-core",
+ "sqlx-macros-core",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "sqlx-macros-core"
+version = "0.7.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5833ef53aaa16d860e92123292f1f6a3d53c34ba8b1969f152ef1a7bb803f3c8"
+dependencies = [
+ "dotenvy",
+ "either",
+ "heck 0.4.1",
+ "hex",
+ "once_cell",
+ "proc-macro2",
+ "quote",
+ "serde",
+ "serde_json",
+ "sha2",
+ "sqlx-core",
+ "sqlx-mysql",
+ "sqlx-sqlite",
+ "syn 1.0.109",
+ "tempfile",
+ "tokio",
+ "url",
+]
+
+[[package]]
+name = "sqlx-mysql"
+version = "0.7.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ed31390216d20e538e447a7a9b959e06ed9fc51c37b514b46eb758016ecd418"
+dependencies = [
+ "atoi",
+ "base64",
+ "bitflags 2.6.0",
+ "byteorder",
+ "bytes",
+ "crc",
+ "digest",
+ "dotenvy",
+ "either",
+ "futures-channel",
+ "futures-core",
+ "futures-io",
+ "futures-util",
+ "generic-array",
+ "hex",
+ "hkdf",
+ "hmac",
+ "itoa",
+ "log",
+ "md-5",
+ "memchr",
+ "once_cell",
+ "percent-encoding",
+ "rand",
+ "rsa",
+ "serde",
+ "sha1",
+ "sha2",
+ "smallvec",
+ "sqlx-core",
+ "stringprep",
+ "thiserror",
+ "tracing",
+ "whoami",
+]
+
+[[package]]
+name = "sqlx-postgres"
+version = "0.7.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c824eb80b894f926f89a0b9da0c7f435d27cdd35b8c655b114e58223918577e"
+dependencies = [
+ "atoi",
+ "base64",
+ "bitflags 2.6.0",
+ "byteorder",
+ "crc",
+ "dotenvy",
+ "etcetera",
+ "futures-channel",
+ "futures-core",
+ "futures-io",
+ "futures-util",
+ "hex",
+ "hkdf",
+ "hmac",
+ "home",
+ "itoa",
+ "log",
+ "md-5",
+ "memchr",
+ "once_cell",
+ "rand",
+ "serde",
+ "serde_json",
+ "sha2",
+ "smallvec",
+ "sqlx-core",
+ "stringprep",
+ "thiserror",
+ "tracing",
+ "whoami",
+]
+
+[[package]]
+name = "sqlx-sqlite"
+version = "0.7.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b244ef0a8414da0bed4bb1910426e890b19e5e9bccc27ada6b797d05c55ae0aa"
+dependencies = [
+ "atoi",
+ "flume",
+ "futures-channel",
+ "futures-core",
+ "futures-executor",
+ "futures-intrusive",
+ "futures-util",
+ "libsqlite3-sys",
+ "log",
+ "percent-encoding",
+ "serde",
+ "sqlx-core",
+ "tracing",
+ "url",
+ "urlencoding",
+]
+
+[[package]]
+name = "stderrlog"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "61c910772f992ab17d32d6760e167d2353f4130ed50e796752689556af07dc6b"
+dependencies = [
+ "chrono",
+ "is-terminal",
+ "log",
+ "termcolor",
+ "thread_local",
+]
+
+[[package]]
+name = "stringprep"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1"
+dependencies = [
+ "unicode-bidi",
+ "unicode-normalization",
+ "unicode-properties",
+]
+
+[[package]]
 name = "strsim"
 version = "0.11.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
 
 [[package]]
+name = "subtle"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+
+[[package]]
 name = "syn"
-version = "2.0.66"
+version = "1.0.109"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c42f3f41a2de00b01c0aaad383c5a45241efc8b2d1eda5661812fda5f3cdcff5"
+checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
 dependencies = [
  "proc-macro2",
  "quote",
@@ -405,6 +1715,23 @@ dependencies = [
 ]
 
 [[package]]
+name = "syn"
+version = "2.0.72"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc4b9b9bf2add8093d3f2c0204471e951b2285580335de42f9d2534f3ae7a8af"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "target-lexicon"
+version = "0.12.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
+
+[[package]]
 name = "tempfile"
 version = "3.10.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -413,34 +1740,53 @@ dependencies = [
  "cfg-if",
  "fastrand",
  "rustix",
- "windows-sys",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "termcolor"
+version = "1.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755"
+dependencies = [
+ "winapi-util",
 ]
 
 [[package]]
 name = "thiserror"
-version = "1.0.61"
+version = "1.0.63"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c546c80d6be4bc6a00c0f01730c08df82eaa7a7a61f11d656526506112cc1709"
+checksum = "c0342370b38b6a11b6cc11d6a805569958d54cfa061a29969c3b5ce2ea405724"
 dependencies = [
  "thiserror-impl",
 ]
 
 [[package]]
 name = "thiserror-impl"
-version = "1.0.61"
+version = "1.0.63"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "46c3384250002a6d5af4d114f2845d37b57521033f30d5c3f46c4d70e1197533"
+checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261"
 dependencies = [
  "proc-macro2",
  "quote",
- "syn",
+ "syn 2.0.72",
+]
+
+[[package]]
+name = "thread_local"
+version = "1.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c"
+dependencies = [
+ "cfg-if",
+ "once_cell",
 ]
 
 [[package]]
 name = "tinyvec"
-version = "1.6.0"
+version = "1.8.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50"
+checksum = "445e881f4f6d382d5f27c034e25eb92edd7c784ceab92a0937db7f2e9471b938"
 dependencies = [
  "tinyvec_macros",
 ]
@@ -452,6 +1798,83 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
 
 [[package]]
+name = "tokio"
+version = "1.39.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "daa4fb1bc778bd6f04cbfc4bb2d06a7396a8f299dc33ea1900cedaa316f467b1"
+dependencies = [
+ "backtrace",
+ "bytes",
+ "libc",
+ "mio",
+ "pin-project-lite",
+ "signal-hook-registry",
+ "socket2",
+ "tokio-macros",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "tokio-macros"
+version = "2.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.72",
+]
+
+[[package]]
+name = "tokio-stream"
+version = "0.1.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "267ac89e0bec6e691e5813911606935d77c476ff49024f98abcea3e7b15e37af"
+dependencies = [
+ "futures-core",
+ "pin-project-lite",
+ "tokio",
+]
+
+[[package]]
+name = "tracing"
+version = "0.1.40"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef"
+dependencies = [
+ "log",
+ "pin-project-lite",
+ "tracing-attributes",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-attributes"
+version = "0.1.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.72",
+]
+
+[[package]]
+name = "tracing-core"
+version = "0.1.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54"
+dependencies = [
+ "once_cell",
+]
+
+[[package]]
+name = "typenum"
+version = "1.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825"
+
+[[package]]
 name = "unicode-bidi"
 version = "0.3.15"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -473,21 +1896,76 @@ dependencies = [
 ]
 
 [[package]]
+name = "unicode-properties"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e4259d9d4425d9f0661581b804cb85fe66a4c631cadd8f490d1c13a35d5d9291"
+
+[[package]]
+name = "unicode-segmentation"
+version = "1.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4c87d22b6e3f4a18d4d40ef354e97c90fcb14dd91d7dc0aa9d8a1172ebf7202"
+
+[[package]]
+name = "unicode_categories"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e"
+
+[[package]]
+name = "unindent"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7de7d73e1754487cb58364ee906a499937a0dfabd86bcb980fa99ec8c8fa2ce"
+
+[[package]]
 name = "url"
-version = "2.5.0"
+version = "2.5.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "31e6302e3bb753d46e83516cae55ae196fc0c309407cf11ab35cc51a4c2a4633"
+checksum = "22784dbdf76fdde8af1aeda5622b546b422b6fc585325248a2bf9f5e41e94d6c"
 dependencies = [
  "form_urlencoded",
  "idna",
  "percent-encoding",
+ "serde",
 ]
 
 [[package]]
+name = "urlencoding"
+version = "2.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"
+
+[[package]]
 name = "utf8parse"
-version = "0.2.1"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
+
+[[package]]
+name = "vcpkg"
+version = "0.2.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
+
+[[package]]
+name = "version_check"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+
+[[package]]
+name = "wasi"
+version = "0.11.0+wasi-snapshot-preview1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a"
+checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
+
+[[package]]
+name = "wasite"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b"
 
 [[package]]
 name = "wasm-bindgen"
@@ -510,7 +1988,7 @@ dependencies = [
  "once_cell",
  "proc-macro2",
  "quote",
- "syn",
+ "syn 2.0.72",
  "wasm-bindgen-shared",
 ]
 
@@ -532,7 +2010,7 @@ checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7"
 dependencies = [
  "proc-macro2",
  "quote",
- "syn",
+ "syn 2.0.72",
  "wasm-bindgen-backend",
  "wasm-bindgen-shared",
 ]
@@ -544,12 +2022,52 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96"
 
 [[package]]
+name = "which"
+version = "4.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7"
+dependencies = [
+ "either",
+ "home",
+ "once_cell",
+ "rustix",
+]
+
+[[package]]
+name = "whoami"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a44ab49fad634e88f55bf8f9bb3abd2f27d7204172a112c7c9987e01c1c94ea9"
+dependencies = [
+ "redox_syscall 0.4.1",
+ "wasite",
+]
+
+[[package]]
+name = "winapi-util"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4d4cc384e1e73b93bafa6fb4f1df8c41695c8a91cf9c4c64358067d15a7b6c6b"
+dependencies = [
+ "windows-sys 0.52.0",
+]
+
+[[package]]
 name = "windows-core"
 version = "0.52.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9"
 dependencies = [
- "windows-targets",
+ "windows-targets 0.52.6",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.48.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
+dependencies = [
+ "windows-targets 0.48.5",
 ]
 
 [[package]]
@@ -558,83 +2076,214 @@ version = "0.52.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
 dependencies = [
- "windows-targets",
+ "windows-targets 0.52.6",
 ]
 
 [[package]]
 name = "windows-targets"
-version = "0.52.5"
+version = "0.48.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb"
+checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
 dependencies = [
- "windows_aarch64_gnullvm",
- "windows_aarch64_msvc",
- "windows_i686_gnu",
+ "windows_aarch64_gnullvm 0.48.5",
+ "windows_aarch64_msvc 0.48.5",
+ "windows_i686_gnu 0.48.5",
+ "windows_i686_msvc 0.48.5",
+ "windows_x86_64_gnu 0.48.5",
+ "windows_x86_64_gnullvm 0.48.5",
+ "windows_x86_64_msvc 0.48.5",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
+dependencies = [
+ "windows_aarch64_gnullvm 0.52.6",
+ "windows_aarch64_msvc 0.52.6",
+ "windows_i686_gnu 0.52.6",
  "windows_i686_gnullvm",
- "windows_i686_msvc",
- "windows_x86_64_gnu",
- "windows_x86_64_gnullvm",
- "windows_x86_64_msvc",
+ "windows_i686_msvc 0.52.6",
+ "windows_x86_64_gnu 0.52.6",
+ "windows_x86_64_gnullvm 0.52.6",
+ "windows_x86_64_msvc 0.52.6",
 ]
 
 [[package]]
 name = "windows_aarch64_gnullvm"
-version = "0.52.5"
+version = "0.48.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263"
+checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
 
 [[package]]
 name = "windows_aarch64_msvc"
-version = "0.52.5"
+version = "0.52.6"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6"
+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
 
 [[package]]
 name = "windows_i686_gnu"
-version = "0.52.5"
+version = "0.48.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670"
+checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
 
 [[package]]
 name = "windows_i686_gnullvm"
-version = "0.52.5"
+version = "0.52.6"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9"
+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
 
 [[package]]
 name = "windows_i686_msvc"
-version = "0.52.5"
+version = "0.48.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf"
+checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
 
 [[package]]
 name = "windows_x86_64_gnu"
-version = "0.52.5"
+version = "0.48.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.48.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9"
+checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
 
 [[package]]
 name = "windows_x86_64_gnullvm"
-version = "0.52.5"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.48.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596"
+checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
 
 [[package]]
 name = "windows_x86_64_msvc"
-version = "0.52.5"
+version = "0.52.6"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0"
+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+
+[[package]]
+name = "xdg"
+version = "2.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "213b7324336b53d2414b2db8537e56544d981803139155afa84f76eeebb7a546"
 
 [[package]]
 name = "yt"
 version = "0.1.0"
 dependencies = [
  "anyhow",
+ "blake3",
+ "chrono",
+ "chrono-humanize",
  "clap",
- "cli-log",
+ "futures",
+ "libmpv2",
  "log",
+ "regex",
  "serde",
  "serde_json",
+ "sqlx",
+ "stderrlog",
  "tempfile",
+ "tokio",
+ "url",
+ "xdg",
+ "yt_dlp",
+]
+
+[[package]]
+name = "yt_dlp"
+version = "0.1.0"
+dependencies = [
+ "log",
+ "pyo3",
+ "serde",
+ "serde_json",
  "url",
 ]
+
+[[package]]
+name = "zerocopy"
+version = "0.6.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "854e949ac82d619ee9a14c66a1b674ac730422372ccb759ce0c39cabcf2bf8e6"
+dependencies = [
+ "byteorder",
+ "zerocopy-derive 0.6.6",
+]
+
+[[package]]
+name = "zerocopy"
+version = "0.7.35"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0"
+dependencies = [
+ "zerocopy-derive 0.7.35",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.6.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "125139de3f6b9d625c39e2efdd73d41bdac468ccd556556440e322be0e1bbd91"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.72",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.7.35"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.72",
+]
+
+[[package]]
+name = "zeroize"
+version = "1.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde"
diff --git a/pkgs/by-name/yt/yt/Cargo.toml b/pkgs/by-name/yt/yt/Cargo.toml
index 602beec9..d1e40cf0 100644
--- a/pkgs/by-name/yt/yt/Cargo.toml
+++ b/pkgs/by-name/yt/yt/Cargo.toml
@@ -7,29 +7,27 @@ edition = "2021"
 
 [dependencies]
 anyhow = "1.0.86"
-clap = { version = "4.5.4", features = ["derive"] }
-cli-log = "2.0.0"
-log = "0.4.21"
-serde = { version = "1.0.202", features = ["derive"] }
-serde_json = "1.0.117"
+blake3 = "1.5.3"
+chrono = { version = "0.4.38", features = ["now"] }
+chrono-humanize = "0.2.3"
+clap = { version = "4.5.13", features = ["derive"] }
+futures = "0.3.30"
+log = "0.4.22"
+regex = "1.10.5"
+serde = { version = "1.0.204", features = ["derive"] }
+serde_json = "1.0.121"
+sqlx = { version = "0.7.4", features = ["runtime-tokio", "sqlite"] }
+stderrlog = "0.6.0"
 tempfile = "3.10.1"
-url = "2.5.0"
-
-# This is here to be able to tell nix which binary to build
-[features]
-yts = []
-ytc = []
-yt = []
-default = ["yt", "yts", "ytc"]
-
-[[bin]]
-name = "yts"
-required-features = ["yts"]
-
-[[bin]]
-name = "ytc"
-required-features = ["ytc"]
+tokio = { version = "1.39.2", features = ["rt-multi-thread", "macros", "process"] }
+url = { version = "2.5.2", features = ["serde"] }
+xdg = "2.5.2"
+yt_dlp = { path = "./yt_dlp/" }
+libmpv2 = { path = "./libmpv2" }
 
 [[bin]]
 name = "yt"
-required-features = ["yt"]
+
+[profile.profiling]
+inherits = "release"
+debug = true
diff --git a/pkgs/by-name/yt/yt/build.rs b/pkgs/by-name/yt/yt/build.rs
new file mode 100644
index 00000000..978542a3
--- /dev/null
+++ b/pkgs/by-name/yt/yt/build.rs
@@ -0,0 +1,7 @@
+use std::env;
+
+fn main() {
+    let ffmpeg_location = env::var("FFMPEG_LOCATION").expect("Must exist");
+
+    println!("cargo::rustc-env=FFMPEG_LOCATION={}", ffmpeg_location);
+}
diff --git a/pkgs/by-name/yt/yt/flake.lock b/pkgs/by-name/yt/yt/flake.lock
index 8f7612cb..cf99a35f 100644
--- a/pkgs/by-name/yt/yt/flake.lock
+++ b/pkgs/by-name/yt/yt/flake.lock
@@ -20,11 +20,11 @@
     },
     "nixpkgs": {
       "locked": {
-        "lastModified": 1720031269,
-        "narHash": "sha256-rwz8NJZV+387rnWpTYcXaRNvzUSnnF9aHONoJIYmiUQ=",
+        "lastModified": 1722421184,
+        "narHash": "sha256-/DJBI6trCeVnasdjUo9pbnodCLZcFqnVZiLUfqLH4jA=",
         "owner": "NixOS",
         "repo": "nixpkgs",
-        "rev": "9f4128e00b0ae8ec65918efeba59db998750ead6",
+        "rev": "9f918d616c5321ad374ae6cb5ea89c9e04bf3e58",
         "type": "github"
       },
       "original": {
diff --git a/pkgs/by-name/yt/yt/flake.nix b/pkgs/by-name/yt/yt/flake.nix
index 561b1c0d..ea9b0de4 100644
--- a/pkgs/by-name/yt/yt/flake.nix
+++ b/pkgs/by-name/yt/yt/flake.nix
@@ -13,17 +13,43 @@
     flake-utils,
   }: (flake-utils.lib.eachDefaultSystem (system: let
     pkgs = nixpkgs.legacyPackages."${system}";
+
+    yt-dlp = pkgs.python3.withPackages (ps: [ps.yt-dlp]);
+
+    buildInputs = with pkgs; [
+      mpv-unwrapped.dev
+    ];
+
+    nativeBuildInputs = with pkgs; [
+      llvmPackages_latest.clang-unwrapped.lib
+    ];
   in {
     devShells.default = pkgs.mkShell {
+      env = {
+        FFMPEG_LOCATION = "${pkgs.lib.getExe pkgs.ffmpeg}";
+        LIBCLANG_PATH = "${pkgs.llvmPackages_latest.clang-unwrapped.lib}/lib/libclang.so";
+        C_INCLUDE_PATH = "${pkgs.llvmPackages_latest.clang-unwrapped.lib}/lib/clang/18/include";
+      };
+
+      inherit buildInputs nativeBuildInputs;
+
       packages = with pkgs; [
         # rust stuff
         cargo
         clippy
         rustc
         rustfmt
+        mold-wrapped
+
+        sqlx-cli
+        sqlite-interactive
+
+        yt-dlp
+        jq
 
         cargo-edit
         cargo-expand
+        cargo-flamegraph
       ];
     };
   }));
diff --git a/pkgs/by-name/yt/yt/libmpv2/.gitignore b/pkgs/by-name/yt/yt/libmpv2/.gitignore
new file mode 100644
index 00000000..e27f7b13
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/.gitignore
@@ -0,0 +1,4 @@
+/target
+/examples/target
+/libmpv2-sys/target
+Cargo.lock
diff --git a/pkgs/by-name/yt/yt/libmpv2/CHANGELOG.md b/pkgs/by-name/yt/yt/libmpv2/CHANGELOG.md
new file mode 100644
index 00000000..0d8b80a8
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/CHANGELOG.md
@@ -0,0 +1,27 @@
+# Changelog
+
+## Unreleased
+
+## Version 3.0.0
+
+- [breaking] Support libmpv version 2.0 (mpv version 0.35.0). Mpv versions <= 0.34.0 will no longer be supported.
+- Add OpenGL rendering
+
+## Version 2.0.1
+
+- Fix `playlist_previous_*` commands using wrong mpv command ([issue](https://github.com/ParadoxSpiral/libmpv-rs/issues/17))
+- Use local libmpv-sys as dependency except on crates.io
+
+## Version 2.0.0
+
+- Add method `Mpv::with_initializer` to set options before initialization
+- [breaking] Borrow `&mut self` in `wait_event` to disallow using two events where the first points to data freed in the second `wait_event` call
+- [breaking] `PropertyData<'_>` is no longer `Clone` or `PartialEq`, `Event<'_>` is no longer `Clone` to avoid cloning/comparing `MpvNode`
+
+## Version 1.1.0
+
+- Add an `MpvNode` that implements `GetData`, i.a. with `MpvNodeArrayIter` and `MpvNodeMapIter` variants that support e.g. properties `audio-parmas` and `playlist`
+
+## Version 1.0.1
+
+- Use debug formatting in impl of `Display` trait for `Error`
diff --git a/pkgs/by-name/yt/yt/libmpv2/Cargo.toml b/pkgs/by-name/yt/yt/libmpv2/Cargo.toml
new file mode 100644
index 00000000..f1c43f5c
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/Cargo.toml
@@ -0,0 +1,26 @@
+[workspace]
+members = ["libmpv2-sys"]
+
+[package]
+name = "libmpv2"
+version = "4.0.0"
+edition = "2021"
+license = "LGPL-2.1"
+readme = "README.md"
+description = "Libmpv abstraction that's easy to use and can play next to all codecs and containers"
+keywords = ["media", "playback", "mpv", "libmpv"]
+
+
+[dependencies]
+libmpv2-sys = { path = "libmpv2-sys", version = "4.0.0" }
+log = "0.4.22"
+thiserror = "1.0.63"
+
+[dev-dependencies]
+crossbeam = "0.7"
+sdl2 = "0.36.0"
+
+[features]
+default = ["protocols", "render"]
+protocols = [] # Enable custom protocol callbacks
+render = [] # Enable custom rendering
diff --git a/pkgs/by-name/yt/yt/libmpv2/LICENSE b/pkgs/by-name/yt/yt/libmpv2/LICENSE
new file mode 100644
index 00000000..7dd5aab7
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/LICENSE
@@ -0,0 +1,174 @@
+GNU LESSER GENERAL PUBLIC LICENSE
+Version 2.1, February 1999
+
+Copyright (C) 1991, 1999 Free Software Foundation, Inc. 
+51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
+Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.]
+
+Preamble
+
+The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users.
+
+This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below.
+
+When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things.
+
+To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it.
+
+For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights.
+
+We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library.
+
+To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others.
+
+Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license.
+
+Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs.
+
+When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library.
+
+We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances.
+
+For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License.
+
+In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system.
+
+Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library.
+
+The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run.
+
+TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you".
+
+A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables.
+
+The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".)
+
+"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library.
+
+Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does.
+
+1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library.
+
+You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
+
+2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
+
+a) The modified work must itself be a software library.
+
+b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change.
+
+c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License.
+
+d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful.
+
+(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
+
+3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices.
+
+Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy.
+
+This option is useful when you wish to copy part of the code of the Library into a program that is not a library.
+
+4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange.
+
+If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code.
+
+5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License.
+
+However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables.
+
+When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law.
+
+If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.)
+
+Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself.
+
+6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications.
+
+You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things:
+
+a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.)
+
+b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with.
+
+c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution.
+
+d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place.
+
+e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy.
+
+For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
+
+It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute.
+
+7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things:
+
+a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above.
+
+b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
+
+8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
+
+9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it.
+
+10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License.
+
+11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
+
+This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
+
+12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
+
+13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation.
+
+14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
+
+NO WARRANTY
+
+15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+END OF TERMS AND CONDITIONS
+
+How to Apply These Terms to Your New Libraries
+
+If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License).
+
+To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
+
+one line to give the library's name and an idea of what it does. 
+Copyright (C) year name of author
+
+This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names:
+
+Yoyodyne, Inc., hereby disclaims all copyright interest in 
+the library `Frob' (a library for tweaking knobs) written 
+by James Random Hacker.
+
+signature of Ty Coon, 1 April 1990 
+Ty Coon, President of Vice 
+That's all there is to it!
diff --git a/pkgs/by-name/yt/yt/libmpv2/README.md b/pkgs/by-name/yt/yt/libmpv2/README.md
new file mode 100644
index 00000000..2b8c68f3
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/README.md
@@ -0,0 +1,23 @@
+Credits go to @anlumo for the rendering implementation and @sirno for updating the API to support libmpv version 2.0.
+
+# libmpv2-rs
+
+A libmpv abstraction written in rust that's easy to use and provides the ability to read next to all video and audio codecs.
+
+# Dependencies
+
+Rust version >= 1.30. Libmpv version 2.0 (mpv version 0.35.0) is the minimum required version.
+
+For ease of building, you can use the `build_libmpv` feature that is used to link against. Especially useful to cross compile to windows. The `MPV_SOURCE` environment variable needs to be set to a directory containing the mpv source you want to build against. For windows targets this is expected to be already built, with a directory named `MPV_SOURCE/64` or `/32` containing [build artifacts](https://mpv.srsfckn.biz/) for 64-bit and 32-bit targets respectively. On unix this is expected to be a copy of the mpv-build repo.
+
+# Examples
+
+To run an example, execute `cargo run [--release] --example x -- test-data/jellyfish.mp4`, where x is any of:
+
+- `events`: event enumeration
+- `protocol`: implementation of custom `filereader://` protocol that… reads files
+- `opengl`: openGL rendering onto SDL2 window
+
+# Contributing
+
+All pull requests/issues welcome.
diff --git a/pkgs/by-name/yt/yt/libmpv2/examples/events.rs b/pkgs/by-name/yt/yt/libmpv2/examples/events.rs
new file mode 100644
index 00000000..c37eb83e
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/examples/events.rs
@@ -0,0 +1,83 @@
+use libmpv2::{events::*, mpv_node::MpvNode, *};
+
+use std::{collections::HashMap, env, thread, time::Duration};
+
+const VIDEO_URL: &str = "https://www.youtube.com/watch?v=VLnWf1sQkjY";
+
+fn main() -> Result<()> {
+    let path = env::args()
+        .nth(1)
+        .unwrap_or_else(|| String::from(VIDEO_URL));
+
+    // Create an `Mpv` and set some properties.
+    let mpv = Mpv::with_initializer(|init| {
+        init.set_property("vo", "null")?;
+        Ok(())
+    })
+    .unwrap();
+    mpv.set_property("volume", 15)?;
+
+    let mut ev_ctx = EventContext::new(mpv.ctx);
+    ev_ctx.disable_deprecated_events()?;
+    ev_ctx.observe_property("volume", Format::Int64, 0)?;
+    ev_ctx.observe_property("demuxer-cache-state", Format::Node, 0)?;
+
+    crossbeam::scope(|scope| {
+        scope.spawn(|_| {
+            mpv.command("loadfile", &[&path, "append-play"]).unwrap();
+
+            thread::sleep(Duration::from_secs(3));
+
+            mpv.set_property("volume", 25).unwrap();
+
+            thread::sleep(Duration::from_secs(5));
+
+            // Trigger `Event::EndFile`.
+            mpv.command("playlist-next", &["force"]).unwrap();
+        });
+        scope.spawn(move |_| loop {
+            let ev = ev_ctx.wait_event(600.).unwrap_or(Err(Error::Null));
+
+            match ev {
+                Ok(Event::EndFile(r)) => {
+                    println!("Exiting! Reason: {:?}", r);
+                    break;
+                }
+
+                Ok(Event::PropertyChange {
+                    name: "demuxer-cache-state",
+                    change: PropertyData::Node(mpv_node),
+                    ..
+                }) => {
+                    let ranges = seekable_ranges(mpv_node);
+                    println!("Seekable ranges updated: {:?}", ranges);
+                }
+                Ok(e) => println!("Event triggered: {:?}", e),
+                Err(e) => println!("Event errored: {:?}", e),
+            }
+        });
+    })
+    .unwrap();
+    Ok(())
+}
+
+fn seekable_ranges(demuxer_cache_state: MpvNode) -> Vec<(f64, f64)> {
+    let mut res = Vec::new();
+    let props = demuxer_cache_state
+        .map()
+        .unwrap()
+        .collect::<HashMap<_, _>>();
+    let ranges = props
+        .get("seekable-ranges")
+        .unwrap()
+        .clone()
+        .array()
+        .unwrap();
+    for node in ranges {
+        let range = node.map().unwrap().collect::<HashMap<_, _>>();
+        let start = range.get("start").unwrap().f64().unwrap();
+        let end = range.get("end").unwrap().f64().unwrap();
+        res.push((start, end));
+    }
+    res
+}
diff --git a/pkgs/by-name/yt/yt/libmpv2/examples/opengl.rs b/pkgs/by-name/yt/yt/libmpv2/examples/opengl.rs
new file mode 100644
index 00000000..3934a41c
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/examples/opengl.rs
@@ -0,0 +1,129 @@
+use libmpv2::{
+    render::{OpenGLInitParams, RenderContext, RenderParam, RenderParamApiType},
+    Mpv,
+};
+use std::{env, ffi::c_void};
+
+fn get_proc_address(display: &sdl2::VideoSubsystem, name: &str) -> *mut c_void {
+    display.gl_get_proc_address(name) as *mut c_void
+}
+
+const VIDEO_URL: &str = "test-data/jellyfish.mp4";
+
+#[derive(Debug)]
+enum UserEvent {
+    MpvEventAvailable,
+    RedrawRequested,
+}
+
+fn main() {
+    let (window, mut events_loop, event_subsystem, video, _context) = create_sdl2_context();
+
+    let path = env::args()
+        .nth(1)
+        .unwrap_or_else(|| String::from(VIDEO_URL));
+
+    let mut mpv = Mpv::with_initializer(|init| {
+        init.set_property("vo", "libmpv")?;
+        Ok(())
+    })
+    .unwrap();
+    let mut render_context = RenderContext::new(
+        unsafe { mpv.ctx.as_mut() },
+        vec![
+            RenderParam::ApiType(RenderParamApiType::OpenGl),
+            RenderParam::InitParams(OpenGLInitParams {
+                get_proc_address,
+                ctx: video,
+            }),
+        ],
+    )
+    .expect("Failed creating render context");
+
+    event_subsystem
+        .register_custom_event::<UserEvent>()
+        .unwrap();
+
+    mpv.event_context_mut().disable_deprecated_events().unwrap();
+
+    let event_sender = event_subsystem.event_sender();
+    render_context.set_update_callback(move || {
+        event_sender
+            .push_custom_event(UserEvent::RedrawRequested)
+            .unwrap();
+    });
+
+    let event_sender = event_subsystem.event_sender();
+    mpv.event_context_mut().set_wakeup_callback(move || {
+        event_sender
+            .push_custom_event(UserEvent::MpvEventAvailable)
+            .unwrap();
+    });
+    mpv.command("loadfile", &[&path, "replace"]).unwrap();
+
+    'render: loop {
+        for event in events_loop.poll_iter() {
+            use sdl2::event::Event;
+
+            if event.is_user_event() {
+                match event.as_user_event_type::<UserEvent>().unwrap() {
+                    UserEvent::RedrawRequested => {
+                        let (width, height) = window.drawable_size();
+                        render_context
+                            .render::<sdl2::VideoSubsystem>(0, width as _, height as _, true)
+                            .expect("Failed to draw on sdl2 window");
+                        window.gl_swap_window();
+                    }
+                    UserEvent::MpvEventAvailable => loop {
+                        match mpv.event_context_mut().wait_event(0.0) {
+                            Some(Ok(libmpv2::events::Event::EndFile(_))) => {
+                                break 'render;
+                            }
+                            Some(Ok(mpv_event)) => {
+                                eprintln!("MPV event: {:?}", mpv_event);
+                            }
+                            Some(Err(err)) => {
+                                eprintln!("MPV Error: {}", err);
+                                break 'render;
+                            }
+                            None => break,
+                        }
+                    },
+                }
+            }
+
+            match event {
+                Event::Quit { .. } => {
+                    break 'render;
+                }
+                _ => (),
+            }
+        }
+    }
+}
+
+fn create_sdl2_context() -> (
+    sdl2::video::Window,
+    sdl2::EventPump,
+    sdl2::EventSubsystem,
+    sdl2::VideoSubsystem,
+    sdl2::video::GLContext,
+) {
+    let sdl = sdl2::init().unwrap();
+    let video = sdl.video().unwrap();
+    let event_subsystem = sdl.event().unwrap();
+    let gl_attr = video.gl_attr();
+    gl_attr.set_context_profile(sdl2::video::GLProfile::Core);
+    gl_attr.set_context_version(3, 3);
+    gl_attr.set_context_flags().forward_compatible().set();
+    let window = video
+        .window("OpenGL mpv", 960, 540)
+        .opengl()
+        .resizable()
+        .build()
+        .unwrap();
+    let gl_context = window.gl_create_context().unwrap();
+    let event_loop = sdl.event_pump().unwrap();
+
+    (window, event_loop, event_subsystem, video, gl_context)
+}
diff --git a/pkgs/by-name/yt/yt/libmpv2/examples/protocol.rs b/pkgs/by-name/yt/yt/libmpv2/examples/protocol.rs
new file mode 100644
index 00000000..74828f4d
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/examples/protocol.rs
@@ -0,0 +1,77 @@
+use std::{
+    env,
+    fs::File,
+    io::{Read, Seek, SeekFrom},
+    mem, thread,
+    time::Duration,
+};
+
+#[cfg(all(not(test), not(feature = "protocols")))]
+compile_error!("The feature `protocols` needs to be enabled for this example`");
+
+#[cfg(feature = "protocols")]
+fn main() {
+    use libmpv2::{protocol::*, *};
+
+    let path = format!(
+        "filereader://{}",
+        env::args()
+            .nth(1)
+            .expect("Expected path to local media as argument, found nil.")
+    );
+
+    let protocol = unsafe {
+        Protocol::new(
+            "filereader".into(),
+            (),
+            open,
+            close,
+            read,
+            Some(seek),
+            Some(size),
+        )
+    };
+
+    let mpv = Mpv::new().unwrap();
+    mpv.set_property("volume", 25).unwrap();
+
+    let proto_ctx = mpv.create_protocol_context();
+    proto_ctx.register(protocol).unwrap();
+
+    mpv.command("loadfile", &[&path, "append-play"]).unwrap();
+
+    thread::sleep(Duration::from_secs(10));
+
+    mpv.command("seek", &["15"]).unwrap();
+
+    thread::sleep(Duration::from_secs(5));
+}
+
+fn open(_: &mut (), uri: &str) -> File {
+    // Open the file, and strip the `filereader://` part
+    let ret = File::open(&uri[13..]).unwrap();
+
+    println!("Opened file[{}], ready for orders o7", &uri[13..]);
+    ret
+}
+
+fn close(_: Box<File>) {
+    println!("Closing file, bye bye~~");
+}
+
+fn read(cookie: &mut File, buf: &mut [i8]) -> i64 {
+    unsafe {
+        let forbidden_magic = mem::transmute::<&mut [i8], &mut [u8]>(buf);
+
+        cookie.read(forbidden_magic).unwrap() as _
+    }
+}
+
+fn seek(cookie: &mut File, offset: i64) -> i64 {
+    println!("Seeking to byte {}", offset);
+    cookie.seek(SeekFrom::Start(offset as u64)).unwrap() as _
+}
+
+fn size(cookie: &mut File) -> i64 {
+    cookie.metadata().unwrap().len() as _
+}
diff --git a/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/Cargo.toml b/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/Cargo.toml
new file mode 100644
index 00000000..25264a35
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+name = "libmpv2-sys"
+version = "4.0.0"
+edition = "2021"
+license = "LGPL-2.1"
+build = "build.rs"
+description = "Libmpv bindings generated by bindgen"
+keywords = ["media", "playback", "mpv", "libmpv"]
+
+[build-dependencies]
+bindgen = {version = "0.69.4"}
diff --git a/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/LICENSE b/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/LICENSE
new file mode 100644
index 00000000..7dd5aab7
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/LICENSE
@@ -0,0 +1,174 @@
+GNU LESSER GENERAL PUBLIC LICENSE
+Version 2.1, February 1999
+
+Copyright (C) 1991, 1999 Free Software Foundation, Inc. 
+51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
+Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.]
+
+Preamble
+
+The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users.
+
+This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below.
+
+When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things.
+
+To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it.
+
+For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights.
+
+We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library.
+
+To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others.
+
+Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license.
+
+Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs.
+
+When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library.
+
+We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances.
+
+For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License.
+
+In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system.
+
+Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library.
+
+The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run.
+
+TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you".
+
+A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables.
+
+The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".)
+
+"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library.
+
+Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does.
+
+1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library.
+
+You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
+
+2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
+
+a) The modified work must itself be a software library.
+
+b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change.
+
+c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License.
+
+d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful.
+
+(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
+
+3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices.
+
+Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy.
+
+This option is useful when you wish to copy part of the code of the Library into a program that is not a library.
+
+4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange.
+
+If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code.
+
+5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License.
+
+However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables.
+
+When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law.
+
+If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.)
+
+Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself.
+
+6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications.
+
+You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things:
+
+a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.)
+
+b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with.
+
+c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution.
+
+d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place.
+
+e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy.
+
+For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
+
+It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute.
+
+7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things:
+
+a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above.
+
+b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
+
+8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
+
+9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it.
+
+10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License.
+
+11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
+
+This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
+
+12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
+
+13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation.
+
+14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
+
+NO WARRANTY
+
+15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+END OF TERMS AND CONDITIONS
+
+How to Apply These Terms to Your New Libraries
+
+If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License).
+
+To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
+
+one line to give the library's name and an idea of what it does. 
+Copyright (C) year name of author
+
+This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names:
+
+Yoyodyne, Inc., hereby disclaims all copyright interest in 
+the library `Frob' (a library for tweaking knobs) written 
+by James Random Hacker.
+
+signature of Ty Coon, 1 April 1990 
+Ty Coon, President of Vice 
+That's all there is to it!
diff --git a/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/README.md b/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/README.md
new file mode 100644
index 00000000..af8faa51
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/README.md
@@ -0,0 +1 @@
+FFI bindings for libmpv, generated by bindgen at compile time.
diff --git a/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/build.rs b/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/build.rs
new file mode 100644
index 00000000..5361e198
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/build.rs
@@ -0,0 +1,26 @@
+use std::env;
+use std::path::PathBuf;
+
+fn main() {
+    let bindings = bindgen::Builder::default()
+        .formatter(bindgen::Formatter::Prettyplease)
+        .header("include/client.h")
+        .header("include/render.h")
+        .header("include/render_gl.h")
+        .header("include/stream_cb.h")
+        .impl_debug(true)
+        .opaque_type("mpv_handle")
+        .opaque_type("mpv_render_context")
+        .enable_function_attribute_detection()
+        .clang_arg("-fretain-comments-from-system-headers")
+        .generate_comments(true)
+        .generate()
+        .expect("Unable to generate bindings");
+
+    let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
+    bindings
+        .write_to_file(out_path.join("bindings.rs"))
+        .expect("Couldn't write bindings!");
+
+    println!("cargo:rustc-link-lib=mpv");
+}
diff --git a/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/include/client.h b/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/include/client.h
new file mode 100644
index 00000000..8eb5e05a
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/include/client.h
@@ -0,0 +1,2032 @@
+/* Copyright (C) 2017 the mpv developers
+ *
+ * Permission to use, copy, modify, and/or distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+/*
+ * Note: the client API is licensed under ISC (see above) to enable
+ * other wrappers outside of mpv. But keep in mind that the
+ * mpv core is by default still GPLv2+ - unless built with
+ * -Dgpl=false, which makes it LGPLv2+.
+ */
+
+#ifndef MPV_CLIENT_API_H_
+#define MPV_CLIENT_API_H_
+
+#include <stddef.h>
+#include <stdint.h>
+
+#ifdef _WIN32
+#define MPV_EXPORT __declspec(dllexport)
+#define MPV_SELECTANY __declspec(selectany)
+#elif defined(__GNUC__) || defined(__clang__)
+#define MPV_EXPORT __attribute__((visibility("default")))
+#define MPV_SELECTANY
+#else
+#define MPV_EXPORT
+#define MPV_SELECTANY
+#endif
+
+#ifdef __cpp_decltype
+#define MPV_DECLTYPE decltype
+#else
+#define MPV_DECLTYPE __typeof__
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * Mechanisms provided by this API
+ * -------------------------------
+ *
+ * This API provides general control over mpv playback. It does not give you
+ * direct access to individual components of the player, only the whole thing.
+ * It's somewhat equivalent to MPlayer's slave mode. You can send commands,
+ * retrieve or set playback status or settings with properties, and receive
+ * events.
+ *
+ * The API can be used in two ways:
+ * 1) Internally in mpv, to provide additional features to the command line
+ *    player. Lua scripting uses this. (Currently there is no plugin API to
+ *    get a client API handle in external user code. It has to be a fixed
+ *    part of the player at compilation time.)
+ * 2) Using mpv as a library with mpv_create(). This basically allows embedding
+ *    mpv in other applications.
+ *
+ * Documentation
+ * -------------
+ *
+ * The libmpv C API is documented directly in this header. Note that most
+ * actual interaction with this player is done through
+ * options/commands/properties, which can be accessed through this API.
+ * Essentially everything is done with them, including loading a file,
+ * retrieving playback progress, and so on.
+ *
+ * These are documented elsewhere:
+ *      * http://mpv.io/manual/master/#options
+ *      * http://mpv.io/manual/master/#list-of-input-commands
+ *      * http://mpv.io/manual/master/#properties
+ *
+ * You can also look at the examples here:
+ *      * https://github.com/mpv-player/mpv-examples/tree/master/libmpv
+ *
+ * Event loop
+ * ----------
+ *
+ * In general, the API user should run an event loop in order to receive events.
+ * This event loop should call mpv_wait_event(), which will return once a new
+ * mpv client API is available. It is also possible to integrate client API
+ * usage in other event loops (e.g. GUI toolkits) with the
+ * mpv_set_wakeup_callback() function, and then polling for events by calling
+ * mpv_wait_event() with a 0 timeout.
+ *
+ * Note that the event loop is detached from the actual player. Not calling
+ * mpv_wait_event() will not stop playback. It will eventually congest the
+ * event queue of your API handle, though.
+ *
+ * Synchronous vs. asynchronous calls
+ * ----------------------------------
+ *
+ * The API allows both synchronous and asynchronous calls. Synchronous calls
+ * have to wait until the playback core is ready, which currently can take
+ * an unbounded time (e.g. if network is slow or unresponsive). Asynchronous
+ * calls just queue operations as requests, and return the result of the
+ * operation as events.
+ *
+ * Asynchronous calls
+ * ------------------
+ *
+ * The client API includes asynchronous functions. These allow you to send
+ * requests instantly, and get replies as events at a later point. The
+ * requests are made with functions carrying the _async suffix, and replies
+ * are returned by mpv_wait_event() (interleaved with the normal event stream).
+ *
+ * A 64 bit userdata value is used to allow the user to associate requests
+ * with replies. The value is passed as reply_userdata parameter to the request
+ * function. The reply to the request will have the reply
+ * mpv_event->reply_userdata field set to the same value as the
+ * reply_userdata parameter of the corresponding request.
+ *
+ * This userdata value is arbitrary and is never interpreted by the API. Note
+ * that the userdata value 0 is also allowed, but then the client must be
+ * careful not accidentally interpret the mpv_event->reply_userdata if an
+ * event is not a reply. (For non-replies, this field is set to 0.)
+ *
+ * Asynchronous calls may be reordered in arbitrarily with other synchronous
+ * and asynchronous calls. If you want a guaranteed order, you need to wait
+ * until asynchronous calls report completion before doing the next call.
+ *
+ * See also the section "Asynchronous command details" in the manpage.
+ *
+ * Multithreading
+ * --------------
+ *
+ * The client API is generally fully thread-safe, unless otherwise noted.
+ * Currently, there is no real advantage in using more than 1 thread to access
+ * the client API, since everything is serialized through a single lock in the
+ * playback core.
+ *
+ * Basic environment requirements
+ * ------------------------------
+ *
+ * This documents basic requirements on the C environment. This is especially
+ * important if mpv is used as library with mpv_create().
+ *
+ * - The LC_NUMERIC locale category must be set to "C". If your program calls
+ *   setlocale(), be sure not to use LC_ALL, or if you do, reset LC_NUMERIC
+ *   to its sane default: setlocale(LC_NUMERIC, "C").
+ * - If a X11 based VO is used, mpv will set the xlib error handler. This error
+ *   handler is process-wide, and there's no proper way to share it with other
+ *   xlib users within the same process. This might confuse GUI toolkits.
+ * - mpv uses some other libraries that are not library-safe, such as Fribidi
+ *   (used through libass), ALSA, FFmpeg, and possibly more.
+ * - The FPU precision must be set at least to double precision.
+ * - On Windows, mpv will call timeBeginPeriod(1).
+ * - On memory exhaustion, mpv will kill the process.
+ * - In certain cases, mpv may start sub processes (such as with the ytdl
+ *   wrapper script).
+ * - Using UNIX IPC (off by default) will override the SIGPIPE signal handler,
+ *   and set it to SIG_IGN. Some invocations of the "subprocess" command will
+ *   also do that.
+ * - mpv may start sub processes, so overriding SIGCHLD, or waiting on all PIDs
+ *   (such as calling wait()) by the parent process or any other library within
+ *   the process must be avoided. libmpv itself only waits for its own PIDs.
+ * - If anything in the process registers signal handlers, they must set the
+ *   SA_RESTART flag. Otherwise you WILL get random failures on signals.
+ *
+ * Encoding of filenames
+ * ---------------------
+ *
+ * mpv uses UTF-8 everywhere.
+ *
+ * On some platforms (like Linux), filenames actually do not have to be UTF-8;
+ * for this reason libmpv supports non-UTF-8 strings. libmpv uses what the
+ * kernel uses and does not recode filenames. At least on Linux, passing a
+ * string to libmpv is like passing a string to the fopen() function.
+ *
+ * On Windows, filenames are always UTF-8, libmpv converts between UTF-8 and
+ * UTF-16 when using win32 API functions. libmpv never uses or accepts
+ * filenames in the local 8 bit encoding. It does not use fopen() either;
+ * it uses _wfopen().
+ *
+ * On macOS, filenames and other strings taken/returned by libmpv can have
+ * inconsistent unicode normalization. This can sometimes lead to problems.
+ * You have to hope for the best.
+ *
+ * Also see the remarks for MPV_FORMAT_STRING.
+ *
+ * Embedding the video window
+ * --------------------------
+ *
+ * Using the render API (in render.h) is recommended. This API requires
+ * you to create and maintain an OpenGL context, to which you can render
+ * video using a specific API call. This API does not include keyboard or mouse
+ * input directly.
+ *
+ * There is an older way to embed the native mpv window into your own. You have
+ * to get the raw window handle, and set it as "wid" option. This works on X11,
+ * win32, and macOS only. It's much easier to use than the render API, but
+ * also has various problems.
+ *
+ * Also see client API examples and the mpv manpage. There is an extensive
+ * discussion here:
+ * https://github.com/mpv-player/mpv-examples/tree/master/libmpv#methods-of-embedding-the-video-window
+ *
+ * Compatibility
+ * -------------
+ *
+ * mpv development doesn't stand still, and changes to mpv internals as well as
+ * to its interface can cause compatibility issues to client API users.
+ *
+ * The API is versioned (see MPV_CLIENT_API_VERSION), and changes to it are
+ * documented in DOCS/client-api-changes.rst. The C API itself will probably
+ * remain compatible for a long time, but the functionality exposed by it
+ * could change more rapidly. For example, it's possible that options are
+ * renamed, or change the set of allowed values.
+ *
+ * Defensive programming should be used to potentially deal with the fact that
+ * options, commands, and properties could disappear, change their value range,
+ * or change the underlying datatypes. It might be a good idea to prefer
+ * MPV_FORMAT_STRING over other types to decouple your code from potential
+ * mpv changes.
+ *
+ * Also see: DOCS/compatibility.rst
+ *
+ * Future changes
+ * --------------
+ *
+ * This are the planned changes that will most likely be done on the next major
+ * bump of the library:
+ *
+ *  - remove all symbols that are marked as deprecated
+ *  - reassign enum numerical values to remove gaps
+ *  - disabling all events by default
+ */
+
+/**
+ * The version is incremented on each API change. The 16 lower bits form the
+ * minor version number, and the 16 higher bits the major version number. If
+ * the API becomes incompatible to previous versions, the major version
+ * number is incremented. This affects only C part, and not properties and
+ * options.
+ *
+ * Every API bump is described in DOCS/client-api-changes.rst
+ *
+ * You can use MPV_MAKE_VERSION() and compare the result with integer
+ * relational operators (<, >, <=, >=).
+ */
+#define MPV_MAKE_VERSION(major, minor) (((major) << 16) | (minor) | 0UL)
+#define MPV_CLIENT_API_VERSION MPV_MAKE_VERSION(2, 3)
+
+/**
+ * The API user is allowed to "#define MPV_ENABLE_DEPRECATED 0" before
+ * including any libmpv headers. Then deprecated symbols will be excluded
+ * from the headers. (Of course, deprecated properties and commands and
+ * other functionality will still work.)
+ */
+#ifndef MPV_ENABLE_DEPRECATED
+#define MPV_ENABLE_DEPRECATED 1
+#endif
+
+/**
+ * Return the MPV_CLIENT_API_VERSION the mpv source has been compiled with.
+ */
+MPV_EXPORT unsigned long mpv_client_api_version(void);
+
+/**
+ * Client context used by the client API. Every client has its own private
+ * handle.
+ */
+typedef struct mpv_handle mpv_handle;
+
+/**
+ * List of error codes than can be returned by API functions. 0 and positive
+ * return values always mean success, negative values are always errors.
+ */
+typedef enum mpv_error {
+    /**
+     * No error happened (used to signal successful operation).
+     * Keep in mind that many API functions returning error codes can also
+     * return positive values, which also indicate success. API users can
+     * hardcode the fact that ">= 0" means success.
+     */
+    MPV_ERROR_SUCCESS           = 0,
+    /**
+     * The event ringbuffer is full. This means the client is choked, and can't
+     * receive any events. This can happen when too many asynchronous requests
+     * have been made, but not answered. Probably never happens in practice,
+     * unless the mpv core is frozen for some reason, and the client keeps
+     * making asynchronous requests. (Bugs in the client API implementation
+     * could also trigger this, e.g. if events become "lost".)
+     */
+    MPV_ERROR_EVENT_QUEUE_FULL  = -1,
+    /**
+     * Memory allocation failed.
+     */
+    MPV_ERROR_NOMEM             = -2,
+    /**
+     * The mpv core wasn't configured and initialized yet. See the notes in
+     * mpv_create().
+     */
+    MPV_ERROR_UNINITIALIZED     = -3,
+    /**
+     * Generic catch-all error if a parameter is set to an invalid or
+     * unsupported value. This is used if there is no better error code.
+     */
+    MPV_ERROR_INVALID_PARAMETER = -4,
+    /**
+     * Trying to set an option that doesn't exist.
+     */
+    MPV_ERROR_OPTION_NOT_FOUND  = -5,
+    /**
+     * Trying to set an option using an unsupported MPV_FORMAT.
+     */
+    MPV_ERROR_OPTION_FORMAT     = -6,
+    /**
+     * Setting the option failed. Typically this happens if the provided option
+     * value could not be parsed.
+     */
+    MPV_ERROR_OPTION_ERROR      = -7,
+    /**
+     * The accessed property doesn't exist.
+     */
+    MPV_ERROR_PROPERTY_NOT_FOUND = -8,
+    /**
+     * Trying to set or get a property using an unsupported MPV_FORMAT.
+     */
+    MPV_ERROR_PROPERTY_FORMAT   = -9,
+    /**
+     * The property exists, but is not available. This usually happens when the
+     * associated subsystem is not active, e.g. querying audio parameters while
+     * audio is disabled.
+     */
+    MPV_ERROR_PROPERTY_UNAVAILABLE = -10,
+    /**
+     * Error setting or getting a property.
+     */
+    MPV_ERROR_PROPERTY_ERROR    = -11,
+    /**
+     * General error when running a command with mpv_command and similar.
+     */
+    MPV_ERROR_COMMAND           = -12,
+    /**
+     * Generic error on loading (usually used with mpv_event_end_file.error).
+     */
+    MPV_ERROR_LOADING_FAILED    = -13,
+    /**
+     * Initializing the audio output failed.
+     */
+    MPV_ERROR_AO_INIT_FAILED    = -14,
+    /**
+     * Initializing the video output failed.
+     */
+    MPV_ERROR_VO_INIT_FAILED    = -15,
+    /**
+     * There was no audio or video data to play. This also happens if the
+     * file was recognized, but did not contain any audio or video streams,
+     * or no streams were selected.
+     */
+    MPV_ERROR_NOTHING_TO_PLAY   = -16,
+    /**
+     * When trying to load the file, the file format could not be determined,
+     * or the file was too broken to open it.
+     */
+    MPV_ERROR_UNKNOWN_FORMAT    = -17,
+    /**
+     * Generic error for signaling that certain system requirements are not
+     * fulfilled.
+     */
+    MPV_ERROR_UNSUPPORTED       = -18,
+    /**
+     * The API function which was called is a stub only.
+     */
+    MPV_ERROR_NOT_IMPLEMENTED   = -19,
+    /**
+     * Unspecified error.
+     */
+    MPV_ERROR_GENERIC           = -20
+} mpv_error;
+
+/**
+ * Return a string describing the error. For unknown errors, the string
+ * "unknown error" is returned.
+ *
+ * @param error error number, see enum mpv_error
+ * @return A static string describing the error. The string is completely
+ *         static, i.e. doesn't need to be deallocated, and is valid forever.
+ */
+MPV_EXPORT const char *mpv_error_string(int error);
+
+/**
+ * General function to deallocate memory returned by some of the API functions.
+ * Call this only if it's explicitly documented as allowed. Calling this on
+ * mpv memory not owned by the caller will lead to undefined behavior.
+ *
+ * @param data A valid pointer returned by the API, or NULL.
+ */
+MPV_EXPORT void mpv_free(void *data);
+
+/**
+ * Return the name of this client handle. Every client has its own unique
+ * name, which is mostly used for user interface purposes.
+ *
+ * @return The client name. The string is read-only and is valid until the
+ *         mpv_handle is destroyed.
+ */
+MPV_EXPORT const char *mpv_client_name(mpv_handle *ctx);
+
+/**
+ * Return the ID of this client handle. Every client has its own unique ID. This
+ * ID is never reused by the core, even if the mpv_handle at hand gets destroyed
+ * and new handles get allocated.
+ *
+ * IDs are never 0 or negative.
+ *
+ * Some mpv APIs (not necessarily all) accept a name in the form "@<id>" in
+ * addition of the proper mpv_client_name(), where "<id>" is the ID in decimal
+ * form (e.g. "@123"). For example, the "script-message-to" command takes the
+ * client name as first argument, but also accepts the client ID formatted in
+ * this manner.
+ *
+ * @return The client ID.
+ */
+MPV_EXPORT int64_t mpv_client_id(mpv_handle *ctx);
+
+/**
+ * Create a new mpv instance and an associated client API handle to control
+ * the mpv instance. This instance is in a pre-initialized state,
+ * and needs to be initialized to be actually used with most other API
+ * functions.
+ *
+ * Some API functions will return MPV_ERROR_UNINITIALIZED in the uninitialized
+ * state. You can call mpv_set_property() (or mpv_set_property_string() and
+ * other variants, and before mpv 0.21.0 mpv_set_option() etc.) to set initial
+ * options. After this, call mpv_initialize() to start the player, and then use
+ * e.g. mpv_command() to start playback of a file.
+ *
+ * The point of separating handle creation and actual initialization is that
+ * you can configure things which can't be changed during runtime.
+ *
+ * Unlike the command line player, this will have initial settings suitable
+ * for embedding in applications. The following settings are different:
+ * - stdin/stdout/stderr and the terminal will never be accessed. This is
+ *   equivalent to setting the --no-terminal option.
+ *   (Technically, this also suppresses C signal handling.)
+ * - No config files will be loaded. This is roughly equivalent to using
+ *   --config=no. Since libmpv 1.15, you can actually re-enable this option,
+ *   which will make libmpv load config files during mpv_initialize(). If you
+ *   do this, you are strongly encouraged to set the "config-dir" option too.
+ *   (Otherwise it will load the mpv command line player's config.)
+ *   For example:
+ *      mpv_set_option_string(mpv, "config-dir", "/my/path"); // set config root
+ *      mpv_set_option_string(mpv, "config", "yes"); // enable config loading
+ *      (call mpv_initialize() _after_ this)
+ * - Idle mode is enabled, which means the playback core will enter idle mode
+ *   if there are no more files to play on the internal playlist, instead of
+ *   exiting. This is equivalent to the --idle option.
+ * - Disable parts of input handling.
+ * - Most of the different settings can be viewed with the command line player
+ *   by running "mpv --show-profile=libmpv".
+ *
+ * All this assumes that API users want a mpv instance that is strictly
+ * isolated from the command line player's configuration, user settings, and
+ * so on. You can re-enable disabled features by setting the appropriate
+ * options.
+ *
+ * The mpv command line parser is not available through this API, but you can
+ * set individual options with mpv_set_property(). Files for playback must be
+ * loaded with mpv_command() or others.
+ *
+ * Note that you should avoid doing concurrent accesses on the uninitialized
+ * client handle. (Whether concurrent access is definitely allowed or not has
+ * yet to be decided.)
+ *
+ * @return a new mpv client API handle. Returns NULL on error. Currently, this
+ *         can happen in the following situations:
+ *         - out of memory
+ *         - LC_NUMERIC is not set to "C" (see general remarks)
+ */
+MPV_EXPORT mpv_handle *mpv_create(void);
+
+/**
+ * Initialize an uninitialized mpv instance. If the mpv instance is already
+ * running, an error is returned.
+ *
+ * This function needs to be called to make full use of the client API if the
+ * client API handle was created with mpv_create().
+ *
+ * Only the following options are required to be set _before_ mpv_initialize():
+ *      - options which are only read at initialization time:
+ *        - config
+ *        - config-dir
+ *        - input-conf
+ *        - load-scripts
+ *        - script
+ *        - player-operation-mode
+ *        - input-app-events (macOS)
+ *      - all encoding mode options
+ *
+ * @return error code
+ */
+MPV_EXPORT int mpv_initialize(mpv_handle *ctx);
+
+/**
+ * Disconnect and destroy the mpv_handle. ctx will be deallocated with this
+ * API call.
+ *
+ * If the last mpv_handle is detached, the core player is destroyed. In
+ * addition, if there are only weak mpv_handles (such as created by
+ * mpv_create_weak_client() or internal scripts), these mpv_handles will
+ * be sent MPV_EVENT_SHUTDOWN. This function may block until these clients
+ * have responded to the shutdown event, and the core is finally destroyed.
+ */
+MPV_EXPORT void mpv_destroy(mpv_handle *ctx);
+
+/**
+ * Similar to mpv_destroy(), but brings the player and all clients down
+ * as well, and waits until all of them are destroyed. This function blocks. The
+ * advantage over mpv_destroy() is that while mpv_destroy() merely
+ * detaches the client handle from the player, this function quits the player,
+ * waits until all other clients are destroyed (i.e. all mpv_handles are
+ * detached), and also waits for the final termination of the player.
+ *
+ * Since mpv_destroy() is called somewhere on the way, it's not safe to
+ * call other functions concurrently on the same context.
+ *
+ * Since mpv client API version 1.29:
+ *  The first call on any mpv_handle will block until the core is destroyed.
+ *  This means it will wait until other mpv_handle have been destroyed. If you
+ *  want asynchronous destruction, just run the "quit" command, and then react
+ *  to the MPV_EVENT_SHUTDOWN event.
+ *  If another mpv_handle already called mpv_terminate_destroy(), this call will
+ *  not actually block. It will destroy the mpv_handle, and exit immediately,
+ *  while other mpv_handles might still be uninitializing.
+ *
+ * Before mpv client API version 1.29:
+ *  If this is called on a mpv_handle that was not created with mpv_create(),
+ *  this function will merely send a quit command and then call
+ *  mpv_destroy(), without waiting for the actual shutdown.
+ */
+MPV_EXPORT void mpv_terminate_destroy(mpv_handle *ctx);
+
+/**
+ * Create a new client handle connected to the same player core as ctx. This
+ * context has its own event queue, its own mpv_request_event() state, its own
+ * mpv_request_log_messages() state, its own set of observed properties, and
+ * its own state for asynchronous operations. Otherwise, everything is shared.
+ *
+ * This handle should be destroyed with mpv_destroy() if no longer
+ * needed. The core will live as long as there is at least 1 handle referencing
+ * it. Any handle can make the core quit, which will result in every handle
+ * receiving MPV_EVENT_SHUTDOWN.
+ *
+ * This function can not be called before the main handle was initialized with
+ * mpv_initialize(). The new handle is always initialized, unless ctx=NULL was
+ * passed.
+ *
+ * @param ctx Used to get the reference to the mpv core; handle-specific
+ *            settings and parameters are not used.
+ *            If NULL, this function behaves like mpv_create() (ignores name).
+ * @param name The client name. This will be returned by mpv_client_name(). If
+ *             the name is already in use, or contains non-alphanumeric
+ *             characters (other than '_'), the name is modified to fit.
+ *             If NULL, an arbitrary name is automatically chosen.
+ * @return a new handle, or NULL on error
+ */
+MPV_EXPORT mpv_handle *mpv_create_client(mpv_handle *ctx, const char *name);
+
+/**
+ * This is the same as mpv_create_client(), but the created mpv_handle is
+ * treated as a weak reference. If all mpv_handles referencing a core are
+ * weak references, the core is automatically destroyed. (This still goes
+ * through normal uninit of course. Effectively, if the last non-weak mpv_handle
+ * is destroyed, then the weak mpv_handles receive MPV_EVENT_SHUTDOWN and are
+ * asked to terminate as well.)
+ *
+ * Note if you want to use this like refcounting: you have to be aware that
+ * mpv_terminate_destroy() _and_ mpv_destroy() for the last non-weak
+ * mpv_handle will block until all weak mpv_handles are destroyed.
+ */
+MPV_EXPORT mpv_handle *mpv_create_weak_client(mpv_handle *ctx, const char *name);
+
+/**
+ * Load a config file. This loads and parses the file, and sets every entry in
+ * the config file's default section as if mpv_set_option_string() is called.
+ *
+ * The filename should be an absolute path. If it isn't, the actual path used
+ * is unspecified. (Note: an absolute path starts with '/' on UNIX.) If the
+ * file wasn't found, MPV_ERROR_INVALID_PARAMETER is returned.
+ *
+ * If a fatal error happens when parsing a config file, MPV_ERROR_OPTION_ERROR
+ * is returned. Errors when setting options as well as other types or errors
+ * are ignored (even if options do not exist). You can still try to capture
+ * the resulting error messages with mpv_request_log_messages(). Note that it's
+ * possible that some options were successfully set even if any of these errors
+ * happen.
+ *
+ * @param filename absolute path to the config file on the local filesystem
+ * @return error code
+ */
+MPV_EXPORT int mpv_load_config_file(mpv_handle *ctx, const char *filename);
+
+/**
+ * Return the internal time in nanoseconds. This has an arbitrary start offset,
+ * but will never wrap or go backwards.
+ *
+ * Note that this is always the real time, and doesn't necessarily have to do
+ * with playback time. For example, playback could go faster or slower due to
+ * playback speed, or due to playback being paused. Use the "time-pos" property
+ * instead to get the playback status.
+ *
+ * Unlike other libmpv APIs, this can be called at absolutely any time (even
+ * within wakeup callbacks), as long as the context is valid.
+ *
+ * Safe to be called from mpv render API threads.
+ */
+MPV_EXPORT int64_t mpv_get_time_ns(mpv_handle *ctx);
+
+/**
+ * Same as mpv_get_time_ns but in microseconds.
+ */
+MPV_EXPORT int64_t mpv_get_time_us(mpv_handle *ctx);
+
+/**
+ * Data format for options and properties. The API functions to get/set
+ * properties and options support multiple formats, and this enum describes
+ * them.
+ */
+typedef enum mpv_format {
+    /**
+     * Invalid. Sometimes used for empty values. This is always defined to 0,
+     * so a normal 0-init of mpv_format (or e.g. mpv_node) is guaranteed to set
+     * this it to MPV_FORMAT_NONE (which makes some things saner as consequence).
+     */
+    MPV_FORMAT_NONE             = 0,
+    /**
+     * The basic type is char*. It returns the raw property string, like
+     * using ${=property} in input.conf (see input.rst).
+     *
+     * NULL isn't an allowed value.
+     *
+     * Warning: although the encoding is usually UTF-8, this is not always the
+     *          case. File tags often store strings in some legacy codepage,
+     *          and even filenames don't necessarily have to be in UTF-8 (at
+     *          least on Linux). If you pass the strings to code that requires
+     *          valid UTF-8, you have to sanitize it in some way.
+     *          On Windows, filenames are always UTF-8, and libmpv converts
+     *          between UTF-8 and UTF-16 when using win32 API functions. See
+     *          the "Encoding of filenames" section for details.
+     *
+     * Example for reading:
+     *
+     *     char *result = NULL;
+     *     if (mpv_get_property(ctx, "property", MPV_FORMAT_STRING, &result) < 0)
+     *         goto error;
+     *     printf("%s\n", result);
+     *     mpv_free(result);
+     *
+     * Or just use mpv_get_property_string().
+     *
+     * Example for writing:
+     *
+     *     char *value = "the new value";
+     *     // yep, you pass the address to the variable
+     *     // (needed for symmetry with other types and mpv_get_property)
+     *     mpv_set_property(ctx, "property", MPV_FORMAT_STRING, &value);
+     *
+     * Or just use mpv_set_property_string().
+     *
+     */
+    MPV_FORMAT_STRING           = 1,
+    /**
+     * The basic type is char*. It returns the OSD property string, like
+     * using ${property} in input.conf (see input.rst). In many cases, this
+     * is the same as the raw string, but in other cases it's formatted for
+     * display on OSD. It's intended to be human readable. Do not attempt to
+     * parse these strings.
+     *
+     * Only valid when doing read access. The rest works like MPV_FORMAT_STRING.
+     */
+    MPV_FORMAT_OSD_STRING       = 2,
+    /**
+     * The basic type is int. The only allowed values are 0 ("no")
+     * and 1 ("yes").
+     *
+     * Example for reading:
+     *
+     *     int result;
+     *     if (mpv_get_property(ctx, "property", MPV_FORMAT_FLAG, &result) < 0)
+     *         goto error;
+     *     printf("%s\n", result ? "true" : "false");
+     *
+     * Example for writing:
+     *
+     *     int flag = 1;
+     *     mpv_set_property(ctx, "property", MPV_FORMAT_FLAG, &flag);
+     */
+    MPV_FORMAT_FLAG             = 3,
+    /**
+     * The basic type is int64_t.
+     */
+    MPV_FORMAT_INT64            = 4,
+    /**
+     * The basic type is double.
+     */
+    MPV_FORMAT_DOUBLE           = 5,
+    /**
+     * The type is mpv_node.
+     *
+     * For reading, you usually would pass a pointer to a stack-allocated
+     * mpv_node value to mpv, and when you're done you call
+     * mpv_free_node_contents(&node).
+     * You're expected not to write to the data - if you have to, copy it
+     * first (which you have to do manually).
+     *
+     * For writing, you construct your own mpv_node, and pass a pointer to the
+     * API. The API will never write to your data (and copy it if needed), so
+     * you're free to use any form of allocation or memory management you like.
+     *
+     * Warning: when reading, always check the mpv_node.format member. For
+     *          example, properties might change their type in future versions
+     *          of mpv, or sometimes even during runtime.
+     *
+     * Example for reading:
+     *
+     *     mpv_node result;
+     *     if (mpv_get_property(ctx, "property", MPV_FORMAT_NODE, &result) < 0)
+     *         goto error;
+     *     printf("format=%d\n", (int)result.format);
+     *     mpv_free_node_contents(&result).
+     *
+     * Example for writing:
+     *
+     *     mpv_node value;
+     *     value.format = MPV_FORMAT_STRING;
+     *     value.u.string = "hello";
+     *     mpv_set_property(ctx, "property", MPV_FORMAT_NODE, &value);
+     */
+    MPV_FORMAT_NODE             = 6,
+    /**
+     * Used with mpv_node only. Can usually not be used directly.
+     */
+    MPV_FORMAT_NODE_ARRAY       = 7,
+    /**
+     * See MPV_FORMAT_NODE_ARRAY.
+     */
+    MPV_FORMAT_NODE_MAP         = 8,
+    /**
+     * A raw, untyped byte array. Only used only with mpv_node, and only in
+     * some very specific situations. (Some commands use it.)
+     */
+    MPV_FORMAT_BYTE_ARRAY       = 9
+} mpv_format;
+
+/**
+ * Generic data storage.
+ *
+ * If mpv writes this struct (e.g. via mpv_get_property()), you must not change
+ * the data. In some cases (mpv_get_property()), you have to free it with
+ * mpv_free_node_contents(). If you fill this struct yourself, you're also
+ * responsible for freeing it, and you must not call mpv_free_node_contents().
+ */
+typedef struct mpv_node {
+    union {
+        char *string;   /** valid if format==MPV_FORMAT_STRING */
+        int flag;       /** valid if format==MPV_FORMAT_FLAG   */
+        int64_t int64;  /** valid if format==MPV_FORMAT_INT64  */
+        double double_; /** valid if format==MPV_FORMAT_DOUBLE */
+        /**
+         * valid if format==MPV_FORMAT_NODE_ARRAY
+         *    or if format==MPV_FORMAT_NODE_MAP
+         */
+        struct mpv_node_list *list;
+        /**
+         * valid if format==MPV_FORMAT_BYTE_ARRAY
+         */
+        struct mpv_byte_array *ba;
+    } u;
+    /**
+     * Type of the data stored in this struct. This value rules what members in
+     * the given union can be accessed. The following formats are currently
+     * defined to be allowed in mpv_node:
+     *
+     *  MPV_FORMAT_STRING       (u.string)
+     *  MPV_FORMAT_FLAG         (u.flag)
+     *  MPV_FORMAT_INT64        (u.int64)
+     *  MPV_FORMAT_DOUBLE       (u.double_)
+     *  MPV_FORMAT_NODE_ARRAY   (u.list)
+     *  MPV_FORMAT_NODE_MAP     (u.list)
+     *  MPV_FORMAT_BYTE_ARRAY   (u.ba)
+     *  MPV_FORMAT_NONE         (no member)
+     *
+     * If you encounter a value you don't know, you must not make any
+     * assumptions about the contents of union u.
+     */
+    mpv_format format;
+} mpv_node;
+
+/**
+ * (see mpv_node)
+ */
+typedef struct mpv_node_list {
+    /**
+     * Number of entries. Negative values are not allowed.
+     */
+    int num;
+    /**
+     * MPV_FORMAT_NODE_ARRAY:
+     *  values[N] refers to value of the Nth item
+     *
+     * MPV_FORMAT_NODE_MAP:
+     *  values[N] refers to value of the Nth key/value pair
+     *
+     * If num > 0, values[0] to values[num-1] (inclusive) are valid.
+     * Otherwise, this can be NULL.
+     */
+    mpv_node *values;
+    /**
+     * MPV_FORMAT_NODE_ARRAY:
+     *  unused (typically NULL), access is not allowed
+     *
+     * MPV_FORMAT_NODE_MAP:
+     *  keys[N] refers to key of the Nth key/value pair. If num > 0, keys[0] to
+     *  keys[num-1] (inclusive) are valid. Otherwise, this can be NULL.
+     *  The keys are in random order. The only guarantee is that keys[N] belongs
+     *  to the value values[N]. NULL keys are not allowed.
+     */
+    char **keys;
+} mpv_node_list;
+
+/**
+ * (see mpv_node)
+ */
+typedef struct mpv_byte_array {
+    /**
+     * Pointer to the data. In what format the data is stored is up to whatever
+     * uses MPV_FORMAT_BYTE_ARRAY.
+     */
+    void *data;
+    /**
+     * Size of the data pointed to by ptr.
+     */
+    size_t size;
+} mpv_byte_array;
+
+/**
+ * Frees any data referenced by the node. It doesn't free the node itself.
+ * Call this only if the mpv client API set the node. If you constructed the
+ * node yourself (manually), you have to free it yourself.
+ *
+ * If node->format is MPV_FORMAT_NONE, this call does nothing. Likewise, if
+ * the client API sets a node with this format, this function doesn't need to
+ * be called. (This is just a clarification that there's no danger of anything
+ * strange happening in these cases.)
+ */
+MPV_EXPORT void mpv_free_node_contents(mpv_node *node);
+
+/**
+ * Set an option. Note that you can't normally set options during runtime. It
+ * works in uninitialized state (see mpv_create()), and in some cases in at
+ * runtime.
+ *
+ * Using a format other than MPV_FORMAT_NODE is equivalent to constructing a
+ * mpv_node with the given format and data, and passing the mpv_node to this
+ * function.
+ *
+ * Note: this is semi-deprecated. For most purposes, this is not needed anymore.
+ *       Starting with mpv version 0.21.0 (version 1.23) most options can be set
+ *       with mpv_set_property() (and related functions), and even before
+ *       mpv_initialize(). In some obscure corner cases, using this function
+ *       to set options might still be required (see
+ *       "Inconsistencies between options and properties" in the manpage). Once
+ *       these are resolved, the option setting functions might be fully
+ *       deprecated.
+ *
+ * @param name Option name. This is the same as on the mpv command line, but
+ *             without the leading "--".
+ * @param format see enum mpv_format.
+ * @param[in] data Option value (according to the format).
+ * @return error code
+ */
+MPV_EXPORT int mpv_set_option(mpv_handle *ctx, const char *name, mpv_format format,
+                              void *data);
+
+/**
+ * Convenience function to set an option to a string value. This is like
+ * calling mpv_set_option() with MPV_FORMAT_STRING.
+ *
+ * @return error code
+ */
+MPV_EXPORT int mpv_set_option_string(mpv_handle *ctx, const char *name, const char *data);
+
+/**
+ * Send a command to the player. Commands are the same as those used in
+ * input.conf, except that this function takes parameters in a pre-split
+ * form.
+ *
+ * The commands and their parameters are documented in input.rst.
+ *
+ * Does not use OSD and string expansion by default (unlike mpv_command_string()
+ * and input.conf).
+ *
+ * @param[in] args NULL-terminated list of strings. Usually, the first item
+ *                 is the command, and the following items are arguments.
+ * @return error code
+ */
+MPV_EXPORT int mpv_command(mpv_handle *ctx, const char **args);
+
+/**
+ * Same as mpv_command(), but allows passing structured data in any format.
+ * In particular, calling mpv_command() is exactly like calling
+ * mpv_command_node() with the format set to MPV_FORMAT_NODE_ARRAY, and
+ * every arg passed in order as MPV_FORMAT_STRING.
+ *
+ * Does not use OSD and string expansion by default.
+ *
+ * The args argument can have one of the following formats:
+ *
+ * MPV_FORMAT_NODE_ARRAY:
+ *      Positional arguments. Each entry is an argument using an arbitrary
+ *      format (the format must be compatible to the used command). Usually,
+ *      the first item is the command name (as MPV_FORMAT_STRING). The order
+ *      of arguments is as documented in each command description.
+ *
+ * MPV_FORMAT_NODE_MAP:
+ *      Named arguments. This requires at least an entry with the key "name"
+ *      to be present, which must be a string, and contains the command name.
+ *      The special entry "_flags" is optional, and if present, must be an
+ *      array of strings, each being a command prefix to apply. All other
+ *      entries are interpreted as arguments. They must use the argument names
+ *      as documented in each command description. Some commands do not
+ *      support named arguments at all, and must use MPV_FORMAT_NODE_ARRAY.
+ *
+ * @param[in] args mpv_node with format set to one of the values documented
+ *                 above (see there for details)
+ * @param[out] result Optional, pass NULL if unused. If not NULL, and if the
+ *                    function succeeds, this is set to command-specific return
+ *                    data. You must call mpv_free_node_contents() to free it
+ *                    (again, only if the command actually succeeds).
+ *                    Not many commands actually use this at all.
+ * @return error code (the result parameter is not set on error)
+ */
+MPV_EXPORT int mpv_command_node(mpv_handle *ctx, mpv_node *args, mpv_node *result);
+
+/**
+ * This is essentially identical to mpv_command() but it also returns a result.
+ *
+ * Does not use OSD and string expansion by default.
+ *
+ * @param[in] args NULL-terminated list of strings. Usually, the first item
+ *                 is the command, and the following items are arguments.
+ * @param[out] result Optional, pass NULL if unused. If not NULL, and if the
+ *                    function succeeds, this is set to command-specific return
+ *                    data. You must call mpv_free_node_contents() to free it
+ *                    (again, only if the command actually succeeds).
+ *                    Not many commands actually use this at all.
+ * @return error code (the result parameter is not set on error)
+ */
+MPV_EXPORT int mpv_command_ret(mpv_handle *ctx, const char **args, mpv_node *result);
+
+/**
+ * Same as mpv_command, but use input.conf parsing for splitting arguments.
+ * This is slightly simpler, but also more error prone, since arguments may
+ * need quoting/escaping.
+ *
+ * This also has OSD and string expansion enabled by default.
+ */
+MPV_EXPORT int mpv_command_string(mpv_handle *ctx, const char *args);
+
+/**
+ * Same as mpv_command, but run the command asynchronously.
+ *
+ * Commands are executed asynchronously. You will receive a
+ * MPV_EVENT_COMMAND_REPLY event. This event will also have an
+ * error code set if running the command failed. For commands that
+ * return data, the data is put into mpv_event_command.result.
+ *
+ * The only case when you do not receive an event is when the function call
+ * itself fails. This happens only if parsing the command itself (or otherwise
+ * validating it) fails, i.e. the return code of the API call is not 0 or
+ * positive.
+ *
+ * Safe to be called from mpv render API threads.
+ *
+ * @param reply_userdata the value mpv_event.reply_userdata of the reply will
+ *                       be set to (see section about asynchronous calls)
+ * @param args NULL-terminated list of strings (see mpv_command())
+ * @return error code (if parsing or queuing the command fails)
+ */
+MPV_EXPORT int mpv_command_async(mpv_handle *ctx, uint64_t reply_userdata,
+                                 const char **args);
+
+/**
+ * Same as mpv_command_node(), but run it asynchronously. Basically, this
+ * function is to mpv_command_node() what mpv_command_async() is to
+ * mpv_command().
+ *
+ * See mpv_command_async() for details.
+ *
+ * Safe to be called from mpv render API threads.
+ *
+ * @param reply_userdata the value mpv_event.reply_userdata of the reply will
+ *                       be set to (see section about asynchronous calls)
+ * @param args as in mpv_command_node()
+ * @return error code (if parsing or queuing the command fails)
+ */
+MPV_EXPORT int mpv_command_node_async(mpv_handle *ctx, uint64_t reply_userdata,
+                                      mpv_node *args);
+
+/**
+ * Signal to all async requests with the matching ID to abort. This affects
+ * the following API calls:
+ *
+ *      mpv_command_async
+ *      mpv_command_node_async
+ *
+ * All of these functions take a reply_userdata parameter. This API function
+ * tells all requests with the matching reply_userdata value to try to return
+ * as soon as possible. If there are multiple requests with matching ID, it
+ * aborts all of them.
+ *
+ * This API function is mostly asynchronous itself. It will not wait until the
+ * command is aborted. Instead, the command will terminate as usual, but with
+ * some work not done. How this is signaled depends on the specific command (for
+ * example, the "subprocess" command will indicate it by "killed_by_us" set to
+ * true in the result). How long it takes also depends on the situation. The
+ * aborting process is completely asynchronous.
+ *
+ * Not all commands may support this functionality. In this case, this function
+ * will have no effect. The same is true if the request using the passed
+ * reply_userdata has already terminated, has not been started yet, or was
+ * never in use at all.
+ *
+ * You have to be careful of race conditions: the time during which the abort
+ * request will be effective is _after_ e.g. mpv_command_async() has returned,
+ * and before the command has signaled completion with MPV_EVENT_COMMAND_REPLY.
+ *
+ * @param reply_userdata ID of the request to be aborted (see above)
+ */
+MPV_EXPORT void mpv_abort_async_command(mpv_handle *ctx, uint64_t reply_userdata);
+
+/**
+ * Set a property to a given value. Properties are essentially variables which
+ * can be queried or set at runtime. For example, writing to the pause property
+ * will actually pause or unpause playback.
+ *
+ * If the format doesn't match with the internal format of the property, access
+ * usually will fail with MPV_ERROR_PROPERTY_FORMAT. In some cases, the data
+ * is automatically converted and access succeeds. For example, MPV_FORMAT_INT64
+ * is always converted to MPV_FORMAT_DOUBLE, and access using MPV_FORMAT_STRING
+ * usually invokes a string parser. The same happens when calling this function
+ * with MPV_FORMAT_NODE: the underlying format may be converted to another
+ * type if possible.
+ *
+ * Using a format other than MPV_FORMAT_NODE is equivalent to constructing a
+ * mpv_node with the given format and data, and passing the mpv_node to this
+ * function. (Before API version 1.21, this was different.)
+ *
+ * Note: starting with mpv 0.21.0 (client API version 1.23), this can be used to
+ *       set options in general. It even can be used before mpv_initialize()
+ *       has been called. If called before mpv_initialize(), setting properties
+ *       not backed by options will result in MPV_ERROR_PROPERTY_UNAVAILABLE.
+ *       In some cases, properties and options still conflict. In these cases,
+ *       mpv_set_property() accesses the options before mpv_initialize(), and
+ *       the properties after mpv_initialize(). These conflicts will be removed
+ *       in mpv 0.23.0. See mpv_set_option() for further remarks.
+ *
+ * @param name The property name. See input.rst for a list of properties.
+ * @param format see enum mpv_format.
+ * @param[in] data Option value.
+ * @return error code
+ */
+MPV_EXPORT int mpv_set_property(mpv_handle *ctx, const char *name, mpv_format format,
+                                void *data);
+
+/**
+ * Convenience function to set a property to a string value.
+ *
+ * This is like calling mpv_set_property() with MPV_FORMAT_STRING.
+ */
+MPV_EXPORT int mpv_set_property_string(mpv_handle *ctx, const char *name, const char *data);
+
+/**
+ * Convenience function to delete a property.
+ *
+ * This is equivalent to running the command "del [name]".
+ *
+ * @param name The property name. See input.rst for a list of properties.
+ * @return error code
+ */
+MPV_EXPORT int mpv_del_property(mpv_handle *ctx, const char *name);
+
+/**
+ * Set a property asynchronously. You will receive the result of the operation
+ * as MPV_EVENT_SET_PROPERTY_REPLY event. The mpv_event.error field will contain
+ * the result status of the operation. Otherwise, this function is similar to
+ * mpv_set_property().
+ *
+ * Safe to be called from mpv render API threads.
+ *
+ * @param reply_userdata see section about asynchronous calls
+ * @param name The property name.
+ * @param format see enum mpv_format.
+ * @param[in] data Option value. The value will be copied by the function. It
+ *                 will never be modified by the client API.
+ * @return error code if sending the request failed
+ */
+MPV_EXPORT int mpv_set_property_async(mpv_handle *ctx, uint64_t reply_userdata,
+                                      const char *name, mpv_format format, void *data);
+
+/**
+ * Read the value of the given property.
+ *
+ * If the format doesn't match with the internal format of the property, access
+ * usually will fail with MPV_ERROR_PROPERTY_FORMAT. In some cases, the data
+ * is automatically converted and access succeeds. For example, MPV_FORMAT_INT64
+ * is always converted to MPV_FORMAT_DOUBLE, and access using MPV_FORMAT_STRING
+ * usually invokes a string formatter.
+ *
+ * @param name The property name.
+ * @param format see enum mpv_format.
+ * @param[out] data Pointer to the variable holding the option value. On
+ *                  success, the variable will be set to a copy of the option
+ *                  value. For formats that require dynamic memory allocation,
+ *                  you can free the value with mpv_free() (strings) or
+ *                  mpv_free_node_contents() (MPV_FORMAT_NODE).
+ * @return error code
+ */
+MPV_EXPORT int mpv_get_property(mpv_handle *ctx, const char *name, mpv_format format,
+                                void *data);
+
+/**
+ * Return the value of the property with the given name as string. This is
+ * equivalent to mpv_get_property() with MPV_FORMAT_STRING.
+ *
+ * See MPV_FORMAT_STRING for character encoding issues.
+ *
+ * On error, NULL is returned. Use mpv_get_property() if you want fine-grained
+ * error reporting.
+ *
+ * @param name The property name.
+ * @return Property value, or NULL if the property can't be retrieved. Free
+ *         the string with mpv_free().
+ */
+MPV_EXPORT char *mpv_get_property_string(mpv_handle *ctx, const char *name);
+
+/**
+ * Return the property as "OSD" formatted string. This is the same as
+ * mpv_get_property_string, but using MPV_FORMAT_OSD_STRING.
+ *
+ * @return Property value, or NULL if the property can't be retrieved. Free
+ *         the string with mpv_free().
+ */
+MPV_EXPORT char *mpv_get_property_osd_string(mpv_handle *ctx, const char *name);
+
+/**
+ * Get a property asynchronously. You will receive the result of the operation
+ * as well as the property data with the MPV_EVENT_GET_PROPERTY_REPLY event.
+ * You should check the mpv_event.error field on the reply event.
+ *
+ * Safe to be called from mpv render API threads.
+ *
+ * @param reply_userdata see section about asynchronous calls
+ * @param name The property name.
+ * @param format see enum mpv_format.
+ * @return error code if sending the request failed
+ */
+MPV_EXPORT int mpv_get_property_async(mpv_handle *ctx, uint64_t reply_userdata,
+                                      const char *name, mpv_format format);
+
+/**
+ * Get a notification whenever the given property changes. You will receive
+ * updates as MPV_EVENT_PROPERTY_CHANGE. Note that this is not very precise:
+ * for some properties, it may not send updates even if the property changed.
+ * This depends on the property, and it's a valid feature request to ask for
+ * better update handling of a specific property. (For some properties, like
+ * ``clock``, which shows the wall clock, this mechanism doesn't make too
+ * much sense anyway.)
+ *
+ * Property changes are coalesced: the change events are returned only once the
+ * event queue becomes empty (e.g. mpv_wait_event() would block or return
+ * MPV_EVENT_NONE), and then only one event per changed property is returned.
+ *
+ * You always get an initial change notification. This is meant to initialize
+ * the user's state to the current value of the property.
+ *
+ * Normally, change events are sent only if the property value changes according
+ * to the requested format. mpv_event_property will contain the property value
+ * as data member.
+ *
+ * Warning: if a property is unavailable or retrieving it caused an error,
+ *          MPV_FORMAT_NONE will be set in mpv_event_property, even if the
+ *          format parameter was set to a different value. In this case, the
+ *          mpv_event_property.data field is invalid.
+ *
+ * If the property is observed with the format parameter set to MPV_FORMAT_NONE,
+ * you get low-level notifications whether the property _may_ have changed, and
+ * the data member in mpv_event_property will be unset. With this mode, you
+ * will have to determine yourself whether the property really changed. On the
+ * other hand, this mechanism can be faster and uses less resources.
+ *
+ * Observing a property that doesn't exist is allowed. (Although it may still
+ * cause some sporadic change events.)
+ *
+ * Keep in mind that you will get change notifications even if you change a
+ * property yourself. Try to avoid endless feedback loops, which could happen
+ * if you react to the change notifications triggered by your own change.
+ *
+ * Only the mpv_handle on which this was called will receive the property
+ * change events, or can unobserve them.
+ *
+ * Safe to be called from mpv render API threads.
+ *
+ * @param reply_userdata This will be used for the mpv_event.reply_userdata
+ *                       field for the received MPV_EVENT_PROPERTY_CHANGE
+ *                       events. (Also see section about asynchronous calls,
+ *                       although this function is somewhat different from
+ *                       actual asynchronous calls.)
+ *                       If you have no use for this, pass 0.
+ *                       Also see mpv_unobserve_property().
+ * @param name The property name.
+ * @param format see enum mpv_format. Can be MPV_FORMAT_NONE to omit values
+ *               from the change events.
+ * @return error code (usually fails only on OOM or unsupported format)
+ */
+MPV_EXPORT int mpv_observe_property(mpv_handle *mpv, uint64_t reply_userdata,
+                                    const char *name, mpv_format format);
+
+/**
+ * Undo mpv_observe_property(). This will remove all observed properties for
+ * which the given number was passed as reply_userdata to mpv_observe_property.
+ *
+ * Safe to be called from mpv render API threads.
+ *
+ * @param registered_reply_userdata ID that was passed to mpv_observe_property
+ * @return negative value is an error code, >=0 is number of removed properties
+ *         on success (includes the case when 0 were removed)
+ */
+MPV_EXPORT int mpv_unobserve_property(mpv_handle *mpv, uint64_t registered_reply_userdata);
+
+typedef enum mpv_event_id {
+    /**
+     * Nothing happened. Happens on timeouts or sporadic wakeups.
+     */
+    MPV_EVENT_NONE              = 0,
+    /**
+     * Happens when the player quits. The player enters a state where it tries
+     * to disconnect all clients. Most requests to the player will fail, and
+     * the client should react to this and quit with mpv_destroy() as soon as
+     * possible.
+     */
+    MPV_EVENT_SHUTDOWN          = 1,
+    /**
+     * See mpv_request_log_messages().
+     */
+    MPV_EVENT_LOG_MESSAGE       = 2,
+    /**
+     * Reply to a mpv_get_property_async() request.
+     * See also mpv_event and mpv_event_property.
+     */
+    MPV_EVENT_GET_PROPERTY_REPLY = 3,
+    /**
+     * Reply to a mpv_set_property_async() request.
+     * (Unlike MPV_EVENT_GET_PROPERTY, mpv_event_property is not used.)
+     */
+    MPV_EVENT_SET_PROPERTY_REPLY = 4,
+    /**
+     * Reply to a mpv_command_async() or mpv_command_node_async() request.
+     * See also mpv_event and mpv_event_command.
+     */
+    MPV_EVENT_COMMAND_REPLY     = 5,
+    /**
+     * Notification before playback start of a file (before the file is loaded).
+     * See also mpv_event and mpv_event_start_file.
+     */
+    MPV_EVENT_START_FILE        = 6,
+    /**
+     * Notification after playback end (after the file was unloaded).
+     * See also mpv_event and mpv_event_end_file.
+     */
+    MPV_EVENT_END_FILE          = 7,
+    /**
+     * Notification when the file has been loaded (headers were read etc.), and
+     * decoding starts.
+     */
+    MPV_EVENT_FILE_LOADED       = 8,
+#if MPV_ENABLE_DEPRECATED
+    /**
+     * Idle mode was entered. In this mode, no file is played, and the playback
+     * core waits for new commands. (The command line player normally quits
+     * instead of entering idle mode, unless --idle was specified. If mpv
+     * was started with mpv_create(), idle mode is enabled by default.)
+     *
+     * @deprecated This is equivalent to using mpv_observe_property() on the
+     *             "idle-active" property. The event is redundant, and might be
+     *             removed in the far future. As a further warning, this event
+     *             is not necessarily sent at the right point anymore (at the
+     *             start of the program), while the property behaves correctly.
+     */
+    MPV_EVENT_IDLE              = 11,
+    /**
+     * Sent every time after a video frame is displayed. Note that currently,
+     * this will be sent in lower frequency if there is no video, or playback
+     * is paused - but that will be removed in the future, and it will be
+     * restricted to video frames only.
+     *
+     * @deprecated Use mpv_observe_property() with relevant properties instead
+     *             (such as "playback-time").
+     */
+    MPV_EVENT_TICK              = 14,
+#endif
+    /**
+     * Triggered by the script-message input command. The command uses the
+     * first argument of the command as client name (see mpv_client_name()) to
+     * dispatch the message, and passes along all arguments starting from the
+     * second argument as strings.
+     * See also mpv_event and mpv_event_client_message.
+     */
+    MPV_EVENT_CLIENT_MESSAGE    = 16,
+    /**
+     * Happens after video changed in some way. This can happen on resolution
+     * changes, pixel format changes, or video filter changes. The event is
+     * sent after the video filters and the VO are reconfigured. Applications
+     * embedding a mpv window should listen to this event in order to resize
+     * the window if needed.
+     * Note that this event can happen sporadically, and you should check
+     * yourself whether the video parameters really changed before doing
+     * something expensive.
+     */
+    MPV_EVENT_VIDEO_RECONFIG    = 17,
+    /**
+     * Similar to MPV_EVENT_VIDEO_RECONFIG. This is relatively uninteresting,
+     * because there is no such thing as audio output embedding.
+     */
+    MPV_EVENT_AUDIO_RECONFIG    = 18,
+    /**
+     * Happens when a seek was initiated. Playback stops. Usually it will
+     * resume with MPV_EVENT_PLAYBACK_RESTART as soon as the seek is finished.
+     */
+    MPV_EVENT_SEEK              = 20,
+    /**
+     * There was a discontinuity of some sort (like a seek), and playback
+     * was reinitialized. Usually happens on start of playback and after
+     * seeking. The main purpose is allowing the client to detect when a seek
+     * request is finished.
+     */
+    MPV_EVENT_PLAYBACK_RESTART  = 21,
+    /**
+     * Event sent due to mpv_observe_property().
+     * See also mpv_event and mpv_event_property.
+     */
+    MPV_EVENT_PROPERTY_CHANGE   = 22,
+    /**
+     * Happens if the internal per-mpv_handle ringbuffer overflows, and at
+     * least 1 event had to be dropped. This can happen if the client doesn't
+     * read the event queue quickly enough with mpv_wait_event(), or if the
+     * client makes a very large number of asynchronous calls at once.
+     *
+     * Event delivery will continue normally once this event was returned
+     * (this forces the client to empty the queue completely).
+     */
+    MPV_EVENT_QUEUE_OVERFLOW    = 24,
+    /**
+     * Triggered if a hook handler was registered with mpv_hook_add(), and the
+     * hook is invoked. If you receive this, you must handle it, and continue
+     * the hook with mpv_hook_continue().
+     * See also mpv_event and mpv_event_hook.
+     */
+    MPV_EVENT_HOOK              = 25,
+    // Internal note: adjust INTERNAL_EVENT_BASE when adding new events.
+} mpv_event_id;
+
+/**
+ * Return a string describing the event. For unknown events, NULL is returned.
+ *
+ * Note that all events actually returned by the API will also yield a non-NULL
+ * string with this function.
+ *
+ * @param event event ID, see see enum mpv_event_id
+ * @return A static string giving a short symbolic name of the event. It
+ *         consists of lower-case alphanumeric characters and can include "-"
+ *         characters. This string is suitable for use in e.g. scripting
+ *         interfaces.
+ *         The string is completely static, i.e. doesn't need to be deallocated,
+ *         and is valid forever.
+ */
+MPV_EXPORT const char *mpv_event_name(mpv_event_id event);
+
+typedef struct mpv_event_property {
+    /**
+     * Name of the property.
+     */
+    const char *name;
+    /**
+     * Format of the data field in the same struct. See enum mpv_format.
+     * This is always the same format as the requested format, except when
+     * the property could not be retrieved (unavailable, or an error happened),
+     * in which case the format is MPV_FORMAT_NONE.
+     */
+    mpv_format format;
+    /**
+     * Received property value. Depends on the format. This is like the
+     * pointer argument passed to mpv_get_property().
+     *
+     * For example, for MPV_FORMAT_STRING you get the string with:
+     *
+     *    char *value = *(char **)(event_property->data);
+     *
+     * Note that this is set to NULL if retrieving the property failed (the
+     * format will be MPV_FORMAT_NONE).
+     */
+    void *data;
+} mpv_event_property;
+
+/**
+ * Numeric log levels. The lower the number, the more important the message is.
+ * MPV_LOG_LEVEL_NONE is never used when receiving messages. The string in
+ * the comment after the value is the name of the log level as used for the
+ * mpv_request_log_messages() function.
+ * Unused numeric values are unused, but reserved for future use.
+ */
+typedef enum mpv_log_level {
+    MPV_LOG_LEVEL_NONE  = 0,    /// "no"    - disable absolutely all messages
+    MPV_LOG_LEVEL_FATAL = 10,   /// "fatal" - critical/aborting errors
+    MPV_LOG_LEVEL_ERROR = 20,   /// "error" - simple errors
+    MPV_LOG_LEVEL_WARN  = 30,   /// "warn"  - possible problems
+    MPV_LOG_LEVEL_INFO  = 40,   /// "info"  - informational message
+    MPV_LOG_LEVEL_V     = 50,   /// "v"     - noisy informational message
+    MPV_LOG_LEVEL_DEBUG = 60,   /// "debug" - very noisy technical information
+    MPV_LOG_LEVEL_TRACE = 70,   /// "trace" - extremely noisy
+} mpv_log_level;
+
+typedef struct mpv_event_log_message {
+    /**
+     * The module prefix, identifies the sender of the message. As a special
+     * case, if the message buffer overflows, this will be set to the string
+     * "overflow" (which doesn't appear as prefix otherwise), and the text
+     * field will contain an informative message.
+     */
+    const char *prefix;
+    /**
+     * The log level as string. See mpv_request_log_messages() for possible
+     * values. The level "no" is never used here.
+     */
+    const char *level;
+    /**
+     * The log message. It consists of 1 line of text, and is terminated with
+     * a newline character. (Before API version 1.6, it could contain multiple
+     * or partial lines.)
+     */
+    const char *text;
+    /**
+     * The same contents as the level field, but as a numeric ID.
+     * Since API version 1.6.
+     */
+    mpv_log_level log_level;
+} mpv_event_log_message;
+
+/// Since API version 1.9.
+typedef enum mpv_end_file_reason {
+    /**
+     * The end of file was reached. Sometimes this may also happen on
+     * incomplete or corrupted files, or if the network connection was
+     * interrupted when playing a remote file. It also happens if the
+     * playback range was restricted with --end or --frames or similar.
+     */
+    MPV_END_FILE_REASON_EOF = 0,
+    /**
+     * Playback was stopped by an external action (e.g. playlist controls).
+     */
+    MPV_END_FILE_REASON_STOP = 2,
+    /**
+     * Playback was stopped by the quit command or player shutdown.
+     */
+    MPV_END_FILE_REASON_QUIT = 3,
+    /**
+     * Some kind of error happened that lead to playback abort. Does not
+     * necessarily happen on incomplete or broken files (in these cases, both
+     * MPV_END_FILE_REASON_ERROR or MPV_END_FILE_REASON_EOF are possible).
+     *
+     * mpv_event_end_file.error will be set.
+     */
+    MPV_END_FILE_REASON_ERROR = 4,
+    /**
+     * The file was a playlist or similar. When the playlist is read, its
+     * entries will be appended to the playlist after the entry of the current
+     * file, the entry of the current file is removed, and a MPV_EVENT_END_FILE
+     * event is sent with reason set to MPV_END_FILE_REASON_REDIRECT. Then
+     * playback continues with the playlist contents.
+     * Since API version 1.18.
+     */
+    MPV_END_FILE_REASON_REDIRECT = 5,
+} mpv_end_file_reason;
+
+/// Since API version 1.108.
+typedef struct mpv_event_start_file {
+    /**
+     * Playlist entry ID of the file being loaded now.
+     */
+    int64_t playlist_entry_id;
+} mpv_event_start_file;
+
+typedef struct mpv_event_end_file {
+    /**
+     * Corresponds to the values in enum mpv_end_file_reason.
+     *
+     * Unknown values should be treated as unknown.
+     */
+    mpv_end_file_reason reason;
+    /**
+     * If reason==MPV_END_FILE_REASON_ERROR, this contains a mpv error code
+     * (one of MPV_ERROR_...) giving an approximate reason why playback
+     * failed. In other cases, this field is 0 (no error).
+     * Since API version 1.9.
+     */
+    int error;
+    /**
+     * Playlist entry ID of the file that was being played or attempted to be
+     * played. This has the same value as the playlist_entry_id field in the
+     * corresponding mpv_event_start_file event.
+     * Since API version 1.108.
+     */
+    int64_t playlist_entry_id;
+    /**
+     * If loading ended, because the playlist entry to be played was for example
+     * a playlist, and the current playlist entry is replaced with a number of
+     * other entries. This may happen at least with MPV_END_FILE_REASON_REDIRECT
+     * (other event types may use this for similar but different purposes in the
+     * future). In this case, playlist_insert_id will be set to the playlist
+     * entry ID of the first inserted entry, and playlist_insert_num_entries to
+     * the total number of inserted playlist entries. Note this in this specific
+     * case, the ID of the last inserted entry is playlist_insert_id+num-1.
+     * Beware that depending on circumstances, you may observe the new playlist
+     * entries before seeing the event (e.g. reading the "playlist" property or
+     * getting a property change notification before receiving the event).
+     * Since API version 1.108.
+     */
+    int64_t playlist_insert_id;
+    /**
+     * See playlist_insert_id. Only non-0 if playlist_insert_id is valid. Never
+     * negative.
+     * Since API version 1.108.
+     */
+    int playlist_insert_num_entries;
+} mpv_event_end_file;
+
+typedef struct mpv_event_client_message {
+    /**
+     * Arbitrary arguments chosen by the sender of the message. If num_args > 0,
+     * you can access args[0] through args[num_args - 1] (inclusive). What
+     * these arguments mean is up to the sender and receiver.
+     * None of the valid items are NULL.
+     */
+    int num_args;
+    const char **args;
+} mpv_event_client_message;
+
+typedef struct mpv_event_hook {
+    /**
+     * The hook name as passed to mpv_hook_add().
+     */
+    const char *name;
+    /**
+     * Internal ID that must be passed to mpv_hook_continue().
+     */
+    uint64_t id;
+} mpv_event_hook;
+
+// Since API version 1.102.
+typedef struct mpv_event_command {
+    /**
+     * Result data of the command. Note that success/failure is signaled
+     * separately via mpv_event.error. This field is only for result data
+     * in case of success. Most commands leave it at MPV_FORMAT_NONE. Set
+     * to MPV_FORMAT_NONE on failure.
+     */
+    mpv_node result;
+} mpv_event_command;
+
+typedef struct mpv_event {
+    /**
+     * One of mpv_event. Keep in mind that later ABI compatible releases might
+     * add new event types. These should be ignored by the API user.
+     */
+    mpv_event_id event_id;
+    /**
+     * This is mainly used for events that are replies to (asynchronous)
+     * requests. It contains a status code, which is >= 0 on success, or < 0
+     * on error (a mpv_error value). Usually, this will be set if an
+     * asynchronous request fails.
+     * Used for:
+     *  MPV_EVENT_GET_PROPERTY_REPLY
+     *  MPV_EVENT_SET_PROPERTY_REPLY
+     *  MPV_EVENT_COMMAND_REPLY
+     */
+    int error;
+    /**
+     * If the event is in reply to a request (made with this API and this
+     * API handle), this is set to the reply_userdata parameter of the request
+     * call. Otherwise, this field is 0.
+     * Used for:
+     *  MPV_EVENT_GET_PROPERTY_REPLY
+     *  MPV_EVENT_SET_PROPERTY_REPLY
+     *  MPV_EVENT_COMMAND_REPLY
+     *  MPV_EVENT_PROPERTY_CHANGE
+     *  MPV_EVENT_HOOK
+     */
+    uint64_t reply_userdata;
+    /**
+     * The meaning and contents of the data member depend on the event_id:
+     *  MPV_EVENT_GET_PROPERTY_REPLY:     mpv_event_property*
+     *  MPV_EVENT_PROPERTY_CHANGE:        mpv_event_property*
+     *  MPV_EVENT_LOG_MESSAGE:            mpv_event_log_message*
+     *  MPV_EVENT_CLIENT_MESSAGE:         mpv_event_client_message*
+     *  MPV_EVENT_START_FILE:             mpv_event_start_file* (since v1.108)
+     *  MPV_EVENT_END_FILE:               mpv_event_end_file*
+     *  MPV_EVENT_HOOK:                   mpv_event_hook*
+     *  MPV_EVENT_COMMAND_REPLY*          mpv_event_command*
+     *  other: NULL
+     *
+     * Note: future enhancements might add new event structs for existing or new
+     *       event types.
+     */
+    void *data;
+} mpv_event;
+
+/**
+ * Convert the given src event to a mpv_node, and set *dst to the result. *dst
+ * is set to a MPV_FORMAT_NODE_MAP, with fields for corresponding mpv_event and
+ * mpv_event.data/mpv_event_* fields.
+ *
+ * The exact details are not completely documented out of laziness. A start
+ * is located in the "Events" section of the manpage.
+ *
+ * *dst may point to newly allocated memory, or pointers in mpv_event. You must
+ * copy the entire mpv_node if you want to reference it after mpv_event becomes
+ * invalid (such as making a new mpv_wait_event() call, or destroying the
+ * mpv_handle from which it was returned). Call mpv_free_node_contents() to free
+ * any memory allocations made by this API function.
+ *
+ * Safe to be called from mpv render API threads.
+ *
+ * @param dst Target. This is not read and fully overwritten. Must be released
+ *            with mpv_free_node_contents(). Do not write to pointers returned
+ *            by it. (On error, this may be left as an empty node.)
+ * @param src The source event. Not modified (it's not const due to the author's
+ *            prejudice of the C version of const).
+ * @return error code (MPV_ERROR_NOMEM only, if at all)
+ */
+MPV_EXPORT int mpv_event_to_node(mpv_node *dst, mpv_event *src);
+
+/**
+ * Enable or disable the given event.
+ *
+ * Some events are enabled by default. Some events can't be disabled.
+ *
+ * (Informational note: currently, all events are enabled by default, except
+ *  MPV_EVENT_TICK.)
+ *
+ * Safe to be called from mpv render API threads.
+ *
+ * @param event See enum mpv_event_id.
+ * @param enable 1 to enable receiving this event, 0 to disable it.
+ * @return error code
+ */
+MPV_EXPORT int mpv_request_event(mpv_handle *ctx, mpv_event_id event, int enable);
+
+/**
+ * Enable or disable receiving of log messages. These are the messages the
+ * command line player prints to the terminal. This call sets the minimum
+ * required log level for a message to be received with MPV_EVENT_LOG_MESSAGE.
+ *
+ * @param min_level Minimal log level as string. Valid log levels:
+ *                      no fatal error warn info v debug trace
+ *                  The value "no" disables all messages. This is the default.
+ *                  An exception is the value "terminal-default", which uses the
+ *                  log level as set by the "--msg-level" option. This works
+ *                  even if the terminal is disabled. (Since API version 1.19.)
+ *                  Also see mpv_log_level.
+ * @return error code
+ */
+MPV_EXPORT int mpv_request_log_messages(mpv_handle *ctx, const char *min_level);
+
+/**
+ * Wait for the next event, or until the timeout expires, or if another thread
+ * makes a call to mpv_wakeup(). Passing 0 as timeout will never wait, and
+ * is suitable for polling.
+ *
+ * The internal event queue has a limited size (per client handle). If you
+ * don't empty the event queue quickly enough with mpv_wait_event(), it will
+ * overflow and silently discard further events. If this happens, making
+ * asynchronous requests will fail as well (with MPV_ERROR_EVENT_QUEUE_FULL).
+ *
+ * Only one thread is allowed to call this on the same mpv_handle at a time.
+ * The API won't complain if more than one thread calls this, but it will cause
+ * race conditions in the client when accessing the shared mpv_event struct.
+ * Note that most other API functions are not restricted by this, and no API
+ * function internally calls mpv_wait_event(). Additionally, concurrent calls
+ * to different mpv_handles are always safe.
+ *
+ * As long as the timeout is 0, this is safe to be called from mpv render API
+ * threads.
+ *
+ * @param timeout Timeout in seconds, after which the function returns even if
+ *                no event was received. A MPV_EVENT_NONE is returned on
+ *                timeout. A value of 0 will disable waiting. Negative values
+ *                will wait with an infinite timeout.
+ * @return A struct containing the event ID and other data. The pointer (and
+ *         fields in the struct) stay valid until the next mpv_wait_event()
+ *         call, or until the mpv_handle is destroyed. You must not write to
+ *         the struct, and all memory referenced by it will be automatically
+ *         released by the API on the next mpv_wait_event() call, or when the
+ *         context is destroyed. The return value is never NULL.
+ */
+MPV_EXPORT mpv_event *mpv_wait_event(mpv_handle *ctx, double timeout);
+
+/**
+ * Interrupt the current mpv_wait_event() call. This will wake up the thread
+ * currently waiting in mpv_wait_event(). If no thread is waiting, the next
+ * mpv_wait_event() call will return immediately (this is to avoid lost
+ * wakeups).
+ *
+ * mpv_wait_event() will receive a MPV_EVENT_NONE if it's woken up due to
+ * this call. But note that this dummy event might be skipped if there are
+ * already other events queued. All what counts is that the waiting thread
+ * is woken up at all.
+ *
+ * Safe to be called from mpv render API threads.
+ */
+MPV_EXPORT void mpv_wakeup(mpv_handle *ctx);
+
+/**
+ * Set a custom function that should be called when there are new events. Use
+ * this if blocking in mpv_wait_event() to wait for new events is not feasible.
+ *
+ * Keep in mind that the callback will be called from foreign threads. You
+ * must not make any assumptions of the environment, and you must return as
+ * soon as possible (i.e. no long blocking waits). Exiting the callback through
+ * any other means than a normal return is forbidden (no throwing exceptions,
+ * no longjmp() calls). You must not change any local thread state (such as
+ * the C floating point environment).
+ *
+ * You are not allowed to call any client API functions inside of the callback.
+ * In particular, you should not do any processing in the callback, but wake up
+ * another thread that does all the work. The callback is meant strictly for
+ * notification only, and is called from arbitrary core parts of the player,
+ * that make no considerations for reentrant API use or allowing the callee to
+ * spend a lot of time doing other things. Keep in mind that it's also possible
+ * that the callback is called from a thread while a mpv API function is called
+ * (i.e. it can be reentrant).
+ *
+ * In general, the client API expects you to call mpv_wait_event() to receive
+ * notifications, and the wakeup callback is merely a helper utility to make
+ * this easier in certain situations. Note that it's possible that there's
+ * only one wakeup callback invocation for multiple events. You should call
+ * mpv_wait_event() with no timeout until MPV_EVENT_NONE is reached, at which
+ * point the event queue is empty.
+ *
+ * If you actually want to do processing in a callback, spawn a thread that
+ * does nothing but call mpv_wait_event() in a loop and dispatches the result
+ * to a callback.
+ *
+ * Only one wakeup callback can be set.
+ *
+ * @param cb function that should be called if a wakeup is required
+ * @param d arbitrary userdata passed to cb
+ */
+MPV_EXPORT void mpv_set_wakeup_callback(mpv_handle *ctx, void (*cb)(void *d), void *d);
+
+/**
+ * Block until all asynchronous requests are done. This affects functions like
+ * mpv_command_async(), which return immediately and return their result as
+ * events.
+ *
+ * This is a helper, and somewhat equivalent to calling mpv_wait_event() in a
+ * loop until all known asynchronous requests have sent their reply as event,
+ * except that the event queue is not emptied.
+ *
+ * In case you called mpv_suspend() before, this will also forcibly reset the
+ * suspend counter of the given handle.
+ */
+MPV_EXPORT void mpv_wait_async_requests(mpv_handle *ctx);
+
+/**
+ * A hook is like a synchronous event that blocks the player. You register
+ * a hook handler with this function. You will get an event, which you need
+ * to handle, and once things are ready, you can let the player continue with
+ * mpv_hook_continue().
+ *
+ * Currently, hooks can't be removed explicitly. But they will be implicitly
+ * removed if the mpv_handle it was registered with is destroyed. This also
+ * continues the hook if it was being handled by the destroyed mpv_handle (but
+ * this should be avoided, as it might mess up order of hook execution).
+ *
+ * Hook handlers are ordered globally by priority and order of registration.
+ * Handlers for the same hook with same priority are invoked in order of
+ * registration (the handler registered first is run first). Handlers with
+ * lower priority are run first (which seems backward).
+ *
+ * See the "Hooks" section in the manpage to see which hooks are currently
+ * defined.
+ *
+ * Some hooks might be reentrant (so you get multiple MPV_EVENT_HOOK for the
+ * same hook). If this can happen for a specific hook type, it will be
+ * explicitly documented in the manpage.
+ *
+ * Only the mpv_handle on which this was called will receive the hook events,
+ * or can "continue" them.
+ *
+ * @param reply_userdata This will be used for the mpv_event.reply_userdata
+ *                       field for the received MPV_EVENT_HOOK events.
+ *                       If you have no use for this, pass 0.
+ * @param name The hook name. This should be one of the documented names. But
+ *             if the name is unknown, the hook event will simply be never
+ *             raised.
+ * @param priority See remarks above. Use 0 as a neutral default.
+ * @return error code (usually fails only on OOM)
+ */
+MPV_EXPORT int mpv_hook_add(mpv_handle *ctx, uint64_t reply_userdata,
+                            const char *name, int priority);
+
+/**
+ * Respond to a MPV_EVENT_HOOK event. You must call this after you have handled
+ * the event. There is no way to "cancel" or "stop" the hook.
+ *
+ * Calling this will will typically unblock the player for whatever the hook
+ * is responsible for (e.g. for the "on_load" hook it lets it continue
+ * playback).
+ *
+ * It is explicitly undefined behavior to call this more than once for each
+ * MPV_EVENT_HOOK, to pass an incorrect ID, or to call this on a mpv_handle
+ * different from the one that registered the handler and received the event.
+ *
+ * @param id This must be the value of the mpv_event_hook.id field for the
+ *           corresponding MPV_EVENT_HOOK.
+ * @return error code
+ */
+MPV_EXPORT int mpv_hook_continue(mpv_handle *ctx, uint64_t id);
+
+#if MPV_ENABLE_DEPRECATED
+
+/**
+ * Return a UNIX file descriptor referring to the read end of a pipe. This
+ * pipe can be used to wake up a poll() based processing loop. The purpose of
+ * this function is very similar to mpv_set_wakeup_callback(), and provides
+ * a primitive mechanism to handle coordinating a foreign event loop and the
+ * libmpv event loop. The pipe is non-blocking. It's closed when the mpv_handle
+ * is destroyed. This function always returns the same value (on success).
+ *
+ * This is in fact implemented using the same underlying code as for
+ * mpv_set_wakeup_callback() (though they don't conflict), and it is as if each
+ * callback invocation writes a single 0 byte to the pipe. When the pipe
+ * becomes readable, the code calling poll() (or select()) on the pipe should
+ * read all contents of the pipe and then call mpv_wait_event(c, 0) until
+ * no new events are returned. The pipe contents do not matter and can just
+ * be discarded. There is not necessarily one byte per readable event in the
+ * pipe. For example, the pipes are non-blocking, and mpv won't block if the
+ * pipe is full. Pipes are normally limited to 4096 bytes, so if there are
+ * more than 4096 events, the number of readable bytes can not equal the number
+ * of events queued. Also, it's possible that mpv does not write to the pipe
+ * once it's guaranteed that the client was already signaled. See the example
+ * below how to do it correctly.
+ *
+ * Example:
+ *
+ *  int pipefd = mpv_get_wakeup_pipe(mpv);
+ *  if (pipefd < 0)
+ *      error();
+ *  while (1) {
+ *      struct pollfd pfds[1] = {
+ *          { .fd = pipefd, .events = POLLIN },
+ *      };
+ *      // Wait until there are possibly new mpv events.
+ *      poll(pfds, 1, -1);
+ *      if (pfds[0].revents & POLLIN) {
+ *          // Empty the pipe. Doing this before calling mpv_wait_event()
+ *          // ensures that no wakeups are missed. It's not so important to
+ *          // make sure the pipe is really empty (it will just cause some
+ *          // additional wakeups in unlikely corner cases).
+ *          char unused[256];
+ *          read(pipefd, unused, sizeof(unused));
+ *          while (1) {
+ *              mpv_event *ev = mpv_wait_event(mpv, 0);
+ *              // If MPV_EVENT_NONE is received, the event queue is empty.
+ *              if (ev->event_id == MPV_EVENT_NONE)
+ *                  break;
+ *              // Process the event.
+ *              ...
+ *          }
+ *      }
+ *  }
+ *
+ * @deprecated this function will be removed in the future. If you need this
+ *             functionality, use mpv_set_wakeup_callback(), create a pipe
+ *             manually, and call write() on your pipe in the callback.
+ *
+ * @return A UNIX FD of the read end of the wakeup pipe, or -1 on error.
+ *         On MS Windows/MinGW, this will always return -1.
+ */
+MPV_EXPORT int mpv_get_wakeup_pipe(mpv_handle *ctx);
+
+#endif
+
+/**
+ * Defining MPV_CPLUGIN_DYNAMIC_SYM during plugin compilation will replace mpv_*
+ * functions with function pointers. Those pointer will be initialized when
+ * loading the plugin.
+ *
+ * It is recommended to use this symbol table when targeting Windows. The loader
+ * does not have notion of global symbols. Loading cplugin into mpv process will
+ * not allow this plugin to call any of the symbols that may be available in
+ * other modules. Instead cplugin has to link explicitly to specific PE binary,
+ * libmpv-2.dll/mpv.exe or any other binary that may have linked mpv statically.
+ * This limits portability of cplugin as it would need to be compiled separately
+ * for each of target PE binary that includes mpv's symbols. Which in practice
+ * is unrealistic, as we want one cplugin to be loaded without those restrictions.
+ *
+ * Instead of linking to any PE binary, we create function pointers for all mpv's
+ * exported symbols. For convenience names of entrypoints are redefined to those
+ * pointer, so no changes are required in cplugin source code, except of defining
+ * MPV_CPLUGIN_DYNAMIC_SYM. Those function pointer are exported to make them
+ * available for mpv to init with correct values during runtime, before calling
+ * `mpv_open_cplugin`.
+ *
+ * Note that those pointers are decorated with `selectany` attribute, so no need
+ * to worry about multiple definitions, linker will keep only single instance.
+ */
+#ifdef MPV_CPLUGIN_DYNAMIC_SYM
+
+#define MPV_DEFINE_SYM_PTR(name)  \
+    MPV_SELECTANY MPV_EXPORT      \
+    MPV_DECLTYPE(name) *pfn_##name;
+
+MPV_DEFINE_SYM_PTR(mpv_client_api_version)
+#define mpv_client_api_version pfn_mpv_client_api_version
+MPV_DEFINE_SYM_PTR(mpv_error_string)
+#define mpv_error_string pfn_mpv_error_string
+MPV_DEFINE_SYM_PTR(mpv_free)
+#define mpv_free pfn_mpv_free
+MPV_DEFINE_SYM_PTR(mpv_client_name)
+#define mpv_client_name pfn_mpv_client_name
+MPV_DEFINE_SYM_PTR(mpv_client_id)
+#define mpv_client_id pfn_mpv_client_id
+MPV_DEFINE_SYM_PTR(mpv_create)
+#define mpv_create pfn_mpv_create
+MPV_DEFINE_SYM_PTR(mpv_initialize)
+#define mpv_initialize pfn_mpv_initialize
+MPV_DEFINE_SYM_PTR(mpv_destroy)
+#define mpv_destroy pfn_mpv_destroy
+MPV_DEFINE_SYM_PTR(mpv_terminate_destroy)
+#define mpv_terminate_destroy pfn_mpv_terminate_destroy
+MPV_DEFINE_SYM_PTR(mpv_create_client)
+#define mpv_create_client pfn_mpv_create_client
+MPV_DEFINE_SYM_PTR(mpv_create_weak_client)
+#define mpv_create_weak_client pfn_mpv_create_weak_client
+MPV_DEFINE_SYM_PTR(mpv_load_config_file)
+#define mpv_load_config_file pfn_mpv_load_config_file
+MPV_DEFINE_SYM_PTR(mpv_get_time_ns)
+#define mpv_get_time_ns pfn_mpv_get_time_ns
+MPV_DEFINE_SYM_PTR(mpv_get_time_us)
+#define mpv_get_time_us pfn_mpv_get_time_us
+MPV_DEFINE_SYM_PTR(mpv_free_node_contents)
+#define mpv_free_node_contents pfn_mpv_free_node_contents
+MPV_DEFINE_SYM_PTR(mpv_set_option)
+#define mpv_set_option pfn_mpv_set_option
+MPV_DEFINE_SYM_PTR(mpv_set_option_string)
+#define mpv_set_option_string pfn_mpv_set_option_string
+MPV_DEFINE_SYM_PTR(mpv_command)
+#define mpv_command pfn_mpv_command
+MPV_DEFINE_SYM_PTR(mpv_command_node)
+#define mpv_command_node pfn_mpv_command_node
+MPV_DEFINE_SYM_PTR(mpv_command_ret)
+#define mpv_command_ret pfn_mpv_command_ret
+MPV_DEFINE_SYM_PTR(mpv_command_string)
+#define mpv_command_string pfn_mpv_command_string
+MPV_DEFINE_SYM_PTR(mpv_command_async)
+#define mpv_command_async pfn_mpv_command_async
+MPV_DEFINE_SYM_PTR(mpv_command_node_async)
+#define mpv_command_node_async pfn_mpv_command_node_async
+MPV_DEFINE_SYM_PTR(mpv_abort_async_command)
+#define mpv_abort_async_command pfn_mpv_abort_async_command
+MPV_DEFINE_SYM_PTR(mpv_set_property)
+#define mpv_set_property pfn_mpv_set_property
+MPV_DEFINE_SYM_PTR(mpv_set_property_string)
+#define mpv_set_property_string pfn_mpv_set_property_string
+MPV_DEFINE_SYM_PTR(mpv_del_property)
+#define mpv_del_property pfn_mpv_del_property
+MPV_DEFINE_SYM_PTR(mpv_set_property_async)
+#define mpv_set_property_async pfn_mpv_set_property_async
+MPV_DEFINE_SYM_PTR(mpv_get_property)
+#define mpv_get_property pfn_mpv_get_property
+MPV_DEFINE_SYM_PTR(mpv_get_property_string)
+#define mpv_get_property_string pfn_mpv_get_property_string
+MPV_DEFINE_SYM_PTR(mpv_get_property_osd_string)
+#define mpv_get_property_osd_string pfn_mpv_get_property_osd_string
+MPV_DEFINE_SYM_PTR(mpv_get_property_async)
+#define mpv_get_property_async pfn_mpv_get_property_async
+MPV_DEFINE_SYM_PTR(mpv_observe_property)
+#define mpv_observe_property pfn_mpv_observe_property
+MPV_DEFINE_SYM_PTR(mpv_unobserve_property)
+#define mpv_unobserve_property pfn_mpv_unobserve_property
+MPV_DEFINE_SYM_PTR(mpv_event_name)
+#define mpv_event_name pfn_mpv_event_name
+MPV_DEFINE_SYM_PTR(mpv_event_to_node)
+#define mpv_event_to_node pfn_mpv_event_to_node
+MPV_DEFINE_SYM_PTR(mpv_request_event)
+#define mpv_request_event pfn_mpv_request_event
+MPV_DEFINE_SYM_PTR(mpv_request_log_messages)
+#define mpv_request_log_messages pfn_mpv_request_log_messages
+MPV_DEFINE_SYM_PTR(mpv_wait_event)
+#define mpv_wait_event pfn_mpv_wait_event
+MPV_DEFINE_SYM_PTR(mpv_wakeup)
+#define mpv_wakeup pfn_mpv_wakeup
+MPV_DEFINE_SYM_PTR(mpv_set_wakeup_callback)
+#define mpv_set_wakeup_callback pfn_mpv_set_wakeup_callback
+MPV_DEFINE_SYM_PTR(mpv_wait_async_requests)
+#define mpv_wait_async_requests pfn_mpv_wait_async_requests
+MPV_DEFINE_SYM_PTR(mpv_hook_add)
+#define mpv_hook_add pfn_mpv_hook_add
+MPV_DEFINE_SYM_PTR(mpv_hook_continue)
+#define mpv_hook_continue pfn_mpv_hook_continue
+MPV_DEFINE_SYM_PTR(mpv_get_wakeup_pipe)
+#define mpv_get_wakeup_pipe pfn_mpv_get_wakeup_pipe
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/include/render.h b/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/include/render.h
new file mode 100644
index 00000000..862ffdeb
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/include/render.h
@@ -0,0 +1,759 @@
+/* Copyright (C) 2018 the mpv developers
+ *
+ * Permission to use, copy, modify, and/or distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#ifndef MPV_CLIENT_API_RENDER_H_
+#define MPV_CLIENT_API_RENDER_H_
+
+#include "client.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * Overview
+ * --------
+ *
+ * This API can be used to make mpv render using supported graphic APIs (such
+ * as OpenGL). It can be used to handle video display.
+ *
+ * The renderer needs to be created with mpv_render_context_create() before
+ * you start playback (or otherwise cause a VO to be created). Then (with most
+ * backends) mpv_render_context_render() can be used to explicitly render the
+ * current video frame. Use mpv_render_context_set_update_callback() to get
+ * notified when there is a new frame to draw.
+ *
+ * Preferably rendering should be done in a separate thread. If you call
+ * normal libmpv API functions on the renderer thread, deadlocks can result
+ * (these are made non-fatal with timeouts, but user experience will obviously
+ * suffer). See "Threading" section below.
+ *
+ * You can output and embed video without this API by setting the mpv "wid"
+ * option to a native window handle (see "Embedding the video window" section
+ * in the client.h header). In general, using the render API is recommended,
+ * because window embedding can cause various issues, especially with GUI
+ * toolkits and certain platforms.
+ *
+ * Supported backends
+ * ------------------
+ *
+ * OpenGL: via MPV_RENDER_API_TYPE_OPENGL, see render_gl.h header.
+ * Software: via MPV_RENDER_API_TYPE_SW, see section "Software renderer"
+ *
+ * Threading
+ * ---------
+ *
+ * You are recommended to do rendering on a separate thread than normal libmpv
+ * use.
+ *
+ * The mpv_render_* functions can be called from any thread, under the
+ * following conditions:
+ *  - only one of the mpv_render_* functions can be called at the same time
+ *    (unless they belong to different mpv cores created by mpv_create())
+ *  - never can be called from within the callbacks set with
+ *    mpv_set_wakeup_callback() or mpv_render_context_set_update_callback()
+ *  - if the OpenGL backend is used, for all functions the OpenGL context
+ *    must be "current" in the calling thread, and it must be the same OpenGL
+ *    context as the mpv_render_context was created with. Otherwise, undefined
+ *    behavior will occur.
+ *  - the thread does not call libmpv API functions other than the mpv_render_*
+ *    functions, except APIs which are declared as safe (see below). Likewise,
+ *    there must be no lock or wait dependency from the render thread to a
+ *    thread using other libmpv functions. Basically, the situation that your
+ *    render thread waits for a "not safe" libmpv API function to return must
+ *    not happen. If you ignore this requirement, deadlocks can happen, which
+ *    are made non-fatal with timeouts; then playback quality will be degraded,
+ *    and the message
+ *          mpv_render_context_render() not being called or stuck.
+ *    is logged. If you set MPV_RENDER_PARAM_ADVANCED_CONTROL, you promise that
+ *    this won't happen, and must absolutely guarantee it, or a real deadlock
+ *    will freeze the mpv core thread forever.
+ *
+ * libmpv functions which are safe to call from a render thread are:
+ *  - functions marked with "Safe to be called from mpv render API threads."
+ *  - client.h functions which don't have an explicit or implicit mpv_handle
+ *    parameter
+ *  - mpv_render_* functions; but only for the same mpv_render_context pointer.
+ *    If the pointer is different, mpv_render_context_free() is not safe. (The
+ *    reason is that if MPV_RENDER_PARAM_ADVANCED_CONTROL is set, it may have
+ *    to process still queued requests from the core, which it can do only for
+ *    the current context, while requests for other contexts would deadlock.
+ *    Also, it may have to wait and block for the core to terminate the video
+ *    chain to make sure no resources are used after context destruction.)
+ *  - if the mpv_handle parameter refers to a different mpv core than the one
+ *    you're rendering for (very obscure, but allowed)
+ *
+ * Note about old libmpv version:
+ *
+ *      Before API version 1.105 (basically in mpv 0.29.x), simply enabling
+ *      MPV_RENDER_PARAM_ADVANCED_CONTROL could cause deadlock issues. This can
+ *      be worked around by setting the "vd-lavc-dr" option to "no".
+ *      In addition, you were required to call all mpv_render*() API functions
+ *      from the same thread on which mpv_render_context_create() was originally
+ *      run (for the same the mpv_render_context). Not honoring it led to UB
+ *      (deadlocks, use of invalid mp_thread handles), even if you moved your GL
+ *      context to a different thread correctly.
+ *      These problems were addressed in API version 1.105 (mpv 0.30.0).
+ *
+ * Context and handle lifecycle
+ * ----------------------------
+ *
+ * Video initialization will fail if the render context was not initialized yet
+ * (with mpv_render_context_create()), or it will revert to a VO that creates
+ * its own window.
+ *
+ * Currently, there can be only 1 mpv_render_context at a time per mpv core.
+ *
+ * Calling mpv_render_context_free() while a VO is using the render context is
+ * active will disable video.
+ *
+ * You must free the context with mpv_render_context_free() before the mpv core
+ * is destroyed. If this doesn't happen, undefined behavior will result.
+ *
+ * Software renderer
+ * -----------------
+ *
+ * MPV_RENDER_API_TYPE_SW provides an extremely simple (but slow) renderer to
+ * memory surfaces. You probably don't want to use this. Use other render API
+ * types, or other methods of video embedding.
+ *
+ * Use mpv_render_context_create() with MPV_RENDER_PARAM_API_TYPE set to
+ * MPV_RENDER_API_TYPE_SW.
+ *
+ * Call mpv_render_context_render() with various MPV_RENDER_PARAM_SW_* fields
+ * to render the video frame to an in-memory surface. The following fields are
+ * required: MPV_RENDER_PARAM_SW_SIZE, MPV_RENDER_PARAM_SW_FORMAT,
+ * MPV_RENDER_PARAM_SW_STRIDE, MPV_RENDER_PARAM_SW_POINTER.
+ *
+ * This method of rendering is very slow, because everything, including color
+ * conversion, scaling, and OSD rendering, is done on the CPU, single-threaded.
+ * In particular, large video or display sizes, as well as presence of OSD or
+ * subtitles can make it too slow for realtime. As with other software rendering
+ * VOs, setting "sw-fast" may help. Enabling or disabling zimg may help,
+ * depending on the platform.
+ *
+ * In addition, certain multimedia job creation measures like HDR may not work
+ * properly, and will have to be manually handled by for example inserting
+ * filters.
+ *
+ * This API is not really suitable to extract individual frames from video etc.
+ * (basically non-playback uses) - there are better libraries for this. It can
+ * be used this way, but it may be clunky and tricky.
+ *
+ * Further notes:
+ * - MPV_RENDER_PARAM_FLIP_Y is currently ignored (unsupported)
+ * - MPV_RENDER_PARAM_DEPTH is ignored (meaningless)
+ */
+
+/**
+ * Opaque context, returned by mpv_render_context_create().
+ */
+typedef struct mpv_render_context mpv_render_context;
+
+/**
+ * Parameters for mpv_render_param (which is used in a few places such as
+ * mpv_render_context_create().
+ *
+ * Also see mpv_render_param for conventions and how to use it.
+ */
+typedef enum mpv_render_param_type {
+    /**
+     * Not a valid value, but also used to terminate a params array. Its value
+     * is always guaranteed to be 0 (even if the ABI changes in the future).
+     */
+    MPV_RENDER_PARAM_INVALID = 0,
+    /**
+     * The render API to use. Valid for mpv_render_context_create().
+     *
+     * Type: char*
+     *
+     * Defined APIs:
+     *
+     *   MPV_RENDER_API_TYPE_OPENGL:
+     *      OpenGL desktop 2.1 or later (preferably core profile compatible to
+     *      OpenGL 3.2), or OpenGLES 2.0 or later.
+     *      Providing MPV_RENDER_PARAM_OPENGL_INIT_PARAMS is required.
+     *      It is expected that an OpenGL context is valid and "current" when
+     *      calling mpv_render_* functions (unless specified otherwise). It
+     *      must be the same context for the same mpv_render_context.
+     */
+    MPV_RENDER_PARAM_API_TYPE = 1,
+    /**
+     * Required parameters for initializing the OpenGL renderer. Valid for
+     * mpv_render_context_create().
+     * Type: mpv_opengl_init_params*
+     */
+    MPV_RENDER_PARAM_OPENGL_INIT_PARAMS = 2,
+    /**
+     * Describes a GL render target. Valid for mpv_render_context_render().
+     * Type: mpv_opengl_fbo*
+     */
+    MPV_RENDER_PARAM_OPENGL_FBO = 3,
+    /**
+     * Control flipped rendering. Valid for mpv_render_context_render().
+     * Type: int*
+     * If the value is set to 0, render normally. Otherwise, render it flipped,
+     * which is needed e.g. when rendering to an OpenGL default framebuffer
+     * (which has a flipped coordinate system).
+     */
+    MPV_RENDER_PARAM_FLIP_Y = 4,
+    /**
+     * Control surface depth. Valid for mpv_render_context_render().
+     * Type: int*
+     * This implies the depth of the surface passed to the render function in
+     * bits per channel. If omitted or set to 0, the renderer will assume 8.
+     * Typically used to control dithering.
+     */
+    MPV_RENDER_PARAM_DEPTH = 5,
+    /**
+     * ICC profile blob. Valid for mpv_render_context_set_parameter().
+     * Type: mpv_byte_array*
+     * Set an ICC profile for use with the "icc-profile-auto" option. (If the
+     * option is not enabled, the ICC data will not be used.)
+     */
+    MPV_RENDER_PARAM_ICC_PROFILE = 6,
+    /**
+     * Ambient light in lux. Valid for mpv_render_context_set_parameter().
+     * Type: int*
+     * This can be used for automatic gamma correction.
+     */
+    MPV_RENDER_PARAM_AMBIENT_LIGHT = 7,
+    /**
+     * X11 Display, sometimes used for hwdec. Valid for
+     * mpv_render_context_create(). The Display must stay valid for the lifetime
+     * of the mpv_render_context.
+     * Type: Display*
+     */
+    MPV_RENDER_PARAM_X11_DISPLAY = 8,
+    /**
+     * Wayland display, sometimes used for hwdec. Valid for
+     * mpv_render_context_create(). The wl_display must stay valid for the
+     * lifetime of the mpv_render_context.
+     * Type: struct wl_display*
+     */
+    MPV_RENDER_PARAM_WL_DISPLAY = 9,
+    /**
+     * Better control about rendering and enabling some advanced features. Valid
+     * for mpv_render_context_create().
+     *
+     * This conflates multiple requirements the API user promises to abide if
+     * this option is enabled:
+     *
+     *  - The API user's render thread, which is calling the mpv_render_*()
+     *    functions, never waits for the core. Otherwise deadlocks can happen.
+     *    See "Threading" section.
+     *  - The callback set with mpv_render_context_set_update_callback() can now
+     *    be called even if there is no new frame. The API user should call the
+     *    mpv_render_context_update() function, and interpret the return value
+     *    for whether a new frame should be rendered.
+     *  - Correct functionality is impossible if the update callback is not set,
+     *    or not set soon enough after mpv_render_context_create() (the core can
+     *    block while waiting for you to call mpv_render_context_update(), and
+     *    if the update callback is not correctly set, it will deadlock, or
+     *    block for too long).
+     *
+     * In general, setting this option will enable the following features (and
+     * possibly more):
+     *
+     *  - "Direct rendering", which means the player decodes directly to a
+     *    texture, which saves a copy per video frame ("vd-lavc-dr" option
+     *    needs to be enabled, and the rendering backend as well as the
+     *    underlying GPU API/driver needs to have support for it).
+     *  - Rendering screenshots with the GPU API if supported by the backend
+     *    (instead of using a suboptimal software fallback via libswscale).
+     *
+     * Warning: do not just add this without reading the "Threading" section
+     *          above, and then wondering that deadlocks happen. The
+     *          requirements are tricky. But also note that even if advanced
+     *          control is disabled, not adhering to the rules will lead to
+     *          playback problems. Enabling advanced controls simply makes
+     *          violating these rules fatal.
+     *
+     * Type: int*: 0 for disable (default), 1 for enable
+     */
+    MPV_RENDER_PARAM_ADVANCED_CONTROL = 10,
+    /**
+     * Return information about the next frame to render. Valid for
+     * mpv_render_context_get_info().
+     *
+     * Type: mpv_render_frame_info*
+     *
+     * It strictly returns information about the _next_ frame. The implication
+     * is that e.g. mpv_render_context_update()'s return value will have
+     * MPV_RENDER_UPDATE_FRAME set, and the user is supposed to call
+     * mpv_render_context_render(). If there is no next frame, then the
+     * return value will have is_valid set to 0.
+     */
+    MPV_RENDER_PARAM_NEXT_FRAME_INFO = 11,
+    /**
+     * Enable or disable video timing. Valid for mpv_render_context_render().
+     *
+     * Type: int*: 0 for disable, 1 for enable (default)
+     *
+     * When video is timed to audio, the player attempts to render video a bit
+     * ahead, and then do a blocking wait until the target display time is
+     * reached. This blocks mpv_render_context_render() for up to the amount
+     * specified with the "video-timing-offset" global option. You can set
+     * this parameter to 0 to disable this kind of waiting. If you do, it's
+     * recommended to use the target time value in mpv_render_frame_info to
+     * wait yourself, or to set the "video-timing-offset" to 0 instead.
+     *
+     * Disabling this without doing anything in addition will result in A/V sync
+     * being slightly off.
+     */
+    MPV_RENDER_PARAM_BLOCK_FOR_TARGET_TIME = 12,
+    /**
+     * Use to skip rendering in mpv_render_context_render().
+     *
+     * Type: int*: 0 for rendering (default), 1 for skipping
+     *
+     * If this is set, you don't need to pass a target surface to the render
+     * function (and if you do, it's completely ignored). This can still call
+     * into the lower level APIs (i.e. if you use OpenGL, the OpenGL context
+     * must be set).
+     *
+     * Be aware that the render API will consider this frame as having been
+     * rendered. All other normal rules also apply, for example about whether
+     * you have to call mpv_render_context_report_swap(). It also does timing
+     * in the same way.
+     */
+    MPV_RENDER_PARAM_SKIP_RENDERING = 13,
+    /**
+     * Deprecated. Not supported. Use MPV_RENDER_PARAM_DRM_DISPLAY_V2 instead.
+     * Type : struct mpv_opengl_drm_params*
+     */
+    MPV_RENDER_PARAM_DRM_DISPLAY = 14,
+    /**
+     * DRM draw surface size, contains draw surface dimensions.
+     * Valid for mpv_render_context_create().
+     * Type : struct mpv_opengl_drm_draw_surface_size*
+     */
+    MPV_RENDER_PARAM_DRM_DRAW_SURFACE_SIZE = 15,
+    /**
+     * DRM display, contains drm display handles.
+     * Valid for mpv_render_context_create().
+     * Type : struct mpv_opengl_drm_params_v2*
+    */
+    MPV_RENDER_PARAM_DRM_DISPLAY_V2 = 16,
+    /**
+     * MPV_RENDER_API_TYPE_SW only: rendering target surface size, mandatory.
+     * Valid for MPV_RENDER_API_TYPE_SW & mpv_render_context_render().
+     * Type: int[2] (e.g.: int s[2] = {w, h}; param.data = &s[0];)
+     *
+     * The video frame is transformed as with other VOs. Typically, this means
+     * the video gets scaled and black bars are added if the video size or
+     * aspect ratio mismatches with the target size.
+     */
+    MPV_RENDER_PARAM_SW_SIZE = 17,
+    /**
+     * MPV_RENDER_API_TYPE_SW only: rendering target surface pixel format,
+     * mandatory.
+     * Valid for MPV_RENDER_API_TYPE_SW & mpv_render_context_render().
+     * Type: char* (e.g.: char *f = "rgb0"; param.data = f;)
+     *
+     * Valid values are:
+     *  "rgb0", "bgr0", "0bgr", "0rgb"
+     *      4 bytes per pixel RGB, 1 byte (8 bit) per component, component bytes
+     *      with increasing address from left to right (e.g. "rgb0" has r at
+     *      address 0), the "0" component contains uninitialized garbage (often
+     *      the value 0, but not necessarily; the bad naming is inherited from
+     *      FFmpeg)
+     *      Pixel alignment size: 4 bytes
+     *  "rgb24"
+     *      3 bytes per pixel RGB. This is strongly discouraged because it is
+     *      very slow.
+     *      Pixel alignment size: 1 bytes
+     *  other
+     *      The API may accept other pixel formats, using mpv internal format
+     *      names, as long as it's internally marked as RGB, has exactly 1
+     *      plane, and is supported as conversion output. It is not a good idea
+     *      to rely on any of these. Their semantics and handling could change.
+     */
+    MPV_RENDER_PARAM_SW_FORMAT = 18,
+    /**
+     * MPV_RENDER_API_TYPE_SW only: rendering target surface bytes per line,
+     * mandatory.
+     * Valid for MPV_RENDER_API_TYPE_SW & mpv_render_context_render().
+     * Type: size_t*
+     *
+     * This is the number of bytes between a pixel (x, y) and (x, y + 1) on the
+     * target surface. It must be a multiple of the pixel size, and have space
+     * for the surface width as specified by MPV_RENDER_PARAM_SW_SIZE.
+     *
+     * Both stride and pointer value should be a multiple of 64 to facilitate
+     * fast SIMD operation. Lower alignment might trigger slower code paths,
+     * and in the worst case, will copy the entire target frame. If mpv is built
+     * with zimg (and zimg is not disabled), the performance impact might be
+     * less.
+     * In either cases, the pointer and stride must be aligned at least to the
+     * pixel alignment size. Otherwise, crashes and undefined behavior is
+     * possible on platforms which do not support unaligned accesses (either
+     * through normal memory access or aligned SIMD memory access instructions).
+     */
+    MPV_RENDER_PARAM_SW_STRIDE = 19,
+    /*
+     * MPV_RENDER_API_TYPE_SW only: rendering target surface pixel data pointer,
+     * mandatory.
+     * Valid for MPV_RENDER_API_TYPE_SW & mpv_render_context_render().
+     * Type: void*
+     *
+     * This points to the first pixel at the left/top corner (0, 0). In
+     * particular, each line y starts at (pointer + stride * y). Upon rendering,
+     * all data between pointer and (pointer + stride * h) is overwritten.
+     * Whether the padding between (w, y) and (0, y + 1) is overwritten is left
+     * unspecified (it should not be, but unfortunately some scaler backends
+     * will do it anyway). It is assumed that even the padding after the last
+     * line (starting at bytepos(w, h) until (pointer + stride * h)) is
+     * writable.
+     *
+     * See MPV_RENDER_PARAM_SW_STRIDE for alignment requirements.
+     */
+    MPV_RENDER_PARAM_SW_POINTER = 20,
+} mpv_render_param_type;
+
+/**
+ * For backwards compatibility with the old naming of
+ * MPV_RENDER_PARAM_DRM_DRAW_SURFACE_SIZE
+ */
+#define MPV_RENDER_PARAM_DRM_OSD_SIZE MPV_RENDER_PARAM_DRM_DRAW_SURFACE_SIZE
+
+/**
+ * Used to pass arbitrary parameters to some mpv_render_* functions. The
+ * meaning of the data parameter is determined by the type, and each
+ * MPV_RENDER_PARAM_* documents what type the value must point to.
+ *
+ * Each value documents the required data type as the pointer you cast to
+ * void* and set on mpv_render_param.data. For example, if MPV_RENDER_PARAM_FOO
+ * documents the type as Something* , then the code should look like this:
+ *
+ *   Something foo = {...};
+ *   mpv_render_param param;
+ *   param.type = MPV_RENDER_PARAM_FOO;
+ *   param.data = & foo;
+ *
+ * Normally, the data field points to exactly 1 object. If the type is char*,
+ * it points to a 0-terminated string.
+ *
+ * In all cases (unless documented otherwise) the pointers need to remain
+ * valid during the call only. Unless otherwise documented, the API functions
+ * will not write to the params array or any data pointed to it.
+ *
+ * As a convention, parameter arrays are always terminated by type==0. There
+ * is no specific order of the parameters required. The order of the 2 fields in
+ * this struct is guaranteed (even after ABI changes).
+ */
+typedef struct mpv_render_param {
+    enum mpv_render_param_type type;
+    void *data;
+} mpv_render_param;
+
+
+/**
+ * Predefined values for MPV_RENDER_PARAM_API_TYPE.
+ */
+// See render_gl.h
+#define MPV_RENDER_API_TYPE_OPENGL "opengl"
+// See section "Software renderer"
+#define MPV_RENDER_API_TYPE_SW "sw"
+
+/**
+ * Flags used in mpv_render_frame_info.flags. Each value represents a bit in it.
+ */
+typedef enum mpv_render_frame_info_flag {
+    /**
+     * Set if there is actually a next frame. If unset, there is no next frame
+     * yet, and other flags and fields that require a frame to be queued will
+     * be unset.
+     *
+     * This is set for _any_ kind of frame, even for redraw requests.
+     *
+     * Note that when this is unset, it simply means no new frame was
+     * decoded/queued yet, not necessarily that the end of the video was
+     * reached. A new frame can be queued after some time.
+     *
+     * If the return value of mpv_render_context_render() had the
+     * MPV_RENDER_UPDATE_FRAME flag set, this flag will usually be set as well,
+     * unless the frame is rendered, or discarded by other asynchronous events.
+     */
+    MPV_RENDER_FRAME_INFO_PRESENT         = 1 << 0,
+    /**
+     * If set, the frame is not an actual new video frame, but a redraw request.
+     * For example if the video is paused, and an option that affects video
+     * rendering was changed (or any other reason), an update request can be
+     * issued and this flag will be set.
+     *
+     * Typically, redraw frames will not be subject to video timing.
+     *
+     * Implies MPV_RENDER_FRAME_INFO_PRESENT.
+     */
+    MPV_RENDER_FRAME_INFO_REDRAW          = 1 << 1,
+    /**
+     * If set, this is supposed to reproduce the previous frame perfectly. This
+     * is usually used for certain "video-sync" options ("display-..." modes).
+     * Typically the renderer will blit the video from a FBO. Unset otherwise.
+     *
+     * Implies MPV_RENDER_FRAME_INFO_PRESENT.
+     */
+    MPV_RENDER_FRAME_INFO_REPEAT          = 1 << 2,
+    /**
+     * If set, the player timing code expects that the user thread blocks on
+     * vsync (by either delaying the render call, or by making a call to
+     * mpv_render_context_report_swap() at vsync time).
+     *
+     * Implies MPV_RENDER_FRAME_INFO_PRESENT.
+     */
+    MPV_RENDER_FRAME_INFO_BLOCK_VSYNC     = 1 << 3,
+} mpv_render_frame_info_flag;
+
+/**
+ * Information about the next video frame that will be rendered. Can be
+ * retrieved with MPV_RENDER_PARAM_NEXT_FRAME_INFO.
+ */
+typedef struct mpv_render_frame_info {
+    /**
+     * A bitset of mpv_render_frame_info_flag values (i.e. multiple flags are
+     * combined with bitwise or).
+     */
+    uint64_t flags;
+    /**
+     * Absolute time at which the frame is supposed to be displayed. This is in
+     * the same unit and base as the time returned by mpv_get_time_us(). For
+     * frames that are redrawn, or if vsync locked video timing is used (see
+     * "video-sync" option), then this can be 0. The "video-timing-offset"
+     * option determines how much "headroom" the render thread gets (but a high
+     * enough frame rate can reduce it anyway). mpv_render_context_render() will
+     * normally block until the time is elapsed, unless you pass it
+     * MPV_RENDER_PARAM_BLOCK_FOR_TARGET_TIME = 0.
+     */
+    int64_t target_time;
+} mpv_render_frame_info;
+
+/**
+ * Initialize the renderer state. Depending on the backend used, this will
+ * access the underlying GPU API and initialize its own objects.
+ *
+ * You must free the context with mpv_render_context_free(). Not doing so before
+ * the mpv core is destroyed may result in memory leaks or crashes.
+ *
+ * Currently, only at most 1 context can exists per mpv core (it represents the
+ * main video output).
+ *
+ * You should pass the following parameters:
+ *  - MPV_RENDER_PARAM_API_TYPE to select the underlying backend/GPU API.
+ *  - Backend-specific init parameter, like MPV_RENDER_PARAM_OPENGL_INIT_PARAMS.
+ *  - Setting MPV_RENDER_PARAM_ADVANCED_CONTROL and following its rules is
+ *    strongly recommended.
+ *  - If you want to use hwdec, possibly hwdec interop resources.
+ *
+ * @param res set to the context (on success) or NULL (on failure). The value
+ *            is never read and always overwritten.
+ * @param mpv handle used to get the core (the mpv_render_context won't depend
+ *            on this specific handle, only the core referenced by it)
+ * @param params an array of parameters, terminated by type==0. It's left
+ *               unspecified what happens with unknown parameters. At least
+ *               MPV_RENDER_PARAM_API_TYPE is required, and most backends will
+ *               require another backend-specific parameter.
+ * @return error code, including but not limited to:
+ *      MPV_ERROR_UNSUPPORTED: the OpenGL version is not supported
+ *                             (or required extensions are missing)
+ *      MPV_ERROR_NOT_IMPLEMENTED: an unknown API type was provided, or
+ *                                 support for the requested API was not
+ *                                 built in the used libmpv binary.
+ *      MPV_ERROR_INVALID_PARAMETER: at least one of the provided parameters was
+ *                                   not valid.
+ */
+MPV_EXPORT int mpv_render_context_create(mpv_render_context **res, mpv_handle *mpv,
+                                         mpv_render_param *params);
+
+/**
+ * Attempt to change a single parameter. Not all backends and parameter types
+ * support all kinds of changes.
+ *
+ * @param ctx a valid render context
+ * @param param the parameter type and data that should be set
+ * @return error code. If a parameter could actually be changed, this returns
+ *         success, otherwise an error code depending on the parameter type
+ *         and situation.
+ */
+MPV_EXPORT int mpv_render_context_set_parameter(mpv_render_context *ctx,
+                                                mpv_render_param param);
+
+/**
+ * Retrieve information from the render context. This is NOT a counterpart to
+ * mpv_render_context_set_parameter(), because you generally can't read
+ * parameters set with it, and this function is not meant for this purpose.
+ * Instead, this is for communicating information from the renderer back to the
+ * user. See mpv_render_param_type; entries which support this function
+ * explicitly mention it, and for other entries you can assume it will fail.
+ *
+ * You pass param with param.type set and param.data pointing to a variable
+ * of the required data type. The function will then overwrite that variable
+ * with the returned value (at least on success).
+ *
+ * @param ctx a valid render context
+ * @param param the parameter type and data that should be retrieved
+ * @return error code. If a parameter could actually be retrieved, this returns
+ *         success, otherwise an error code depending on the parameter type
+ *         and situation. MPV_ERROR_NOT_IMPLEMENTED is used for unknown
+ *         param.type, or if retrieving it is not supported.
+ */
+MPV_EXPORT int mpv_render_context_get_info(mpv_render_context *ctx,
+                                           mpv_render_param param);
+
+typedef void (*mpv_render_update_fn)(void *cb_ctx);
+
+/**
+ * Set the callback that notifies you when a new video frame is available, or
+ * if the video display configuration somehow changed and requires a redraw.
+ * Similar to mpv_set_wakeup_callback(), you must not call any mpv API from
+ * the callback, and all the other listed restrictions apply (such as not
+ * exiting the callback by throwing exceptions).
+ *
+ * This can be called from any thread, except from an update callback. In case
+ * of the OpenGL backend, no OpenGL state or API is accessed.
+ *
+ * Calling this will raise an update callback immediately.
+ *
+ * @param callback callback(callback_ctx) is called if the frame should be
+ *                 redrawn
+ * @param callback_ctx opaque argument to the callback
+ */
+MPV_EXPORT void mpv_render_context_set_update_callback(mpv_render_context *ctx,
+                                                       mpv_render_update_fn callback,
+                                                       void *callback_ctx);
+
+/**
+ * The API user is supposed to call this when the update callback was invoked
+ * (like all mpv_render_* functions, this has to happen on the render thread,
+ * and _not_ from the update callback itself).
+ *
+ * This is optional if MPV_RENDER_PARAM_ADVANCED_CONTROL was not set (default).
+ * Otherwise, it's a hard requirement that this is called after each update
+ * callback. If multiple update callback happened, and the function could not
+ * be called sooner, it's OK to call it once after the last callback.
+ *
+ * If an update callback happens during or after this function, the function
+ * must be called again at the soonest possible time.
+ *
+ * If MPV_RENDER_PARAM_ADVANCED_CONTROL was set, this will do additional work
+ * such as allocating textures for the video decoder.
+ *
+ * @return a bitset of mpv_render_update_flag values (i.e. multiple flags are
+ *         combined with bitwise or). Typically, this will tell the API user
+ *         what should happen next. E.g. if the MPV_RENDER_UPDATE_FRAME flag is
+ *         set, mpv_render_context_render() should be called. If flags unknown
+ *         to the API user are set, or if the return value is 0, nothing needs
+ *         to be done.
+ */
+MPV_EXPORT uint64_t mpv_render_context_update(mpv_render_context *ctx);
+
+/**
+ * Flags returned by mpv_render_context_update(). Each value represents a bit
+ * in the function's return value.
+ */
+typedef enum mpv_render_update_flag {
+    /**
+     * A new video frame must be rendered. mpv_render_context_render() must be
+     * called.
+     */
+    MPV_RENDER_UPDATE_FRAME         = 1 << 0,
+} mpv_render_context_flag;
+
+/**
+ * Render video.
+ *
+ * Typically renders the video to a target surface provided via mpv_render_param
+ * (the details depend on the backend in use). Options like "panscan" are
+ * applied to determine which part of the video should be visible and how the
+ * video should be scaled. You can change these options at runtime by using the
+ * mpv property API.
+ *
+ * The renderer will reconfigure itself every time the target surface
+ * configuration (such as size) is changed.
+ *
+ * This function implicitly pulls a video frame from the internal queue and
+ * renders it. If no new frame is available, the previous frame is redrawn.
+ * The update callback set with mpv_render_context_set_update_callback()
+ * notifies you when a new frame was added. The details potentially depend on
+ * the backends and the provided parameters.
+ *
+ * Generally, libmpv will invoke your update callback some time before the video
+ * frame should be shown, and then lets this function block until the supposed
+ * display time. This will limit your rendering to video FPS. You can prevent
+ * this by setting the "video-timing-offset" global option to 0. (This applies
+ * only to "audio" video sync mode.)
+ *
+ * You should pass the following parameters:
+ *  - Backend-specific target object, such as MPV_RENDER_PARAM_OPENGL_FBO.
+ *  - Possibly transformations, such as MPV_RENDER_PARAM_FLIP_Y.
+ *
+ * @param ctx a valid render context
+ * @param params an array of parameters, terminated by type==0. Which parameters
+ *               are required depends on the backend. It's left unspecified what
+ *               happens with unknown parameters.
+ * @return error code
+ */
+MPV_EXPORT int mpv_render_context_render(mpv_render_context *ctx, mpv_render_param *params);
+
+/**
+ * Tell the renderer that a frame was flipped at the given time. This is
+ * optional, but can help the player to achieve better timing.
+ *
+ * Note that calling this at least once informs libmpv that you will use this
+ * function. If you use it inconsistently, expect bad video playback.
+ *
+ * If this is called while no video is initialized, it is ignored.
+ *
+ * @param ctx a valid render context
+ */
+MPV_EXPORT void mpv_render_context_report_swap(mpv_render_context *ctx);
+
+/**
+ * Destroy the mpv renderer state.
+ *
+ * If video is still active (e.g. a file playing), video will be disabled
+ * forcefully.
+ *
+ * @param ctx a valid render context. After this function returns, this is not
+ *            a valid pointer anymore. NULL is also allowed and does nothing.
+ */
+MPV_EXPORT void mpv_render_context_free(mpv_render_context *ctx);
+
+#ifdef MPV_CPLUGIN_DYNAMIC_SYM
+
+MPV_DEFINE_SYM_PTR(mpv_render_context_create)
+#define mpv_render_context_create pfn_mpv_render_context_create
+MPV_DEFINE_SYM_PTR(mpv_render_context_set_parameter)
+#define mpv_render_context_set_parameter pfn_mpv_render_context_set_parameter
+MPV_DEFINE_SYM_PTR(mpv_render_context_get_info)
+#define mpv_render_context_get_info pfn_mpv_render_context_get_info
+MPV_DEFINE_SYM_PTR(mpv_render_context_set_update_callback)
+#define mpv_render_context_set_update_callback pfn_mpv_render_context_set_update_callback
+MPV_DEFINE_SYM_PTR(mpv_render_context_update)
+#define mpv_render_context_update pfn_mpv_render_context_update
+MPV_DEFINE_SYM_PTR(mpv_render_context_render)
+#define mpv_render_context_render pfn_mpv_render_context_render
+MPV_DEFINE_SYM_PTR(mpv_render_context_report_swap)
+#define mpv_render_context_report_swap pfn_mpv_render_context_report_swap
+MPV_DEFINE_SYM_PTR(mpv_render_context_free)
+#define mpv_render_context_free pfn_mpv_render_context_free
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/include/render_gl.h b/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/include/render_gl.h
new file mode 100644
index 00000000..aa2719d5
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/include/render_gl.h
@@ -0,0 +1,211 @@
+/* Copyright (C) 2018 the mpv developers
+ *
+ * Permission to use, copy, modify, and/or distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#ifndef MPV_CLIENT_API_RENDER_GL_H_
+#define MPV_CLIENT_API_RENDER_GL_H_
+
+#include "render.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * OpenGL backend
+ * --------------
+ *
+ * This header contains definitions for using OpenGL with the render.h API.
+ *
+ * OpenGL interop
+ * --------------
+ *
+ * The OpenGL backend has some special rules, because OpenGL itself uses
+ * implicit per-thread contexts, which causes additional API problems.
+ *
+ * This assumes the OpenGL context lives on a certain thread controlled by the
+ * API user. All mpv_render_* APIs have to be assumed to implicitly use the
+ * OpenGL context if you pass a mpv_render_context using the OpenGL backend,
+ * unless specified otherwise.
+ *
+ * The OpenGL context is indirectly accessed through the OpenGL function
+ * pointers returned by the get_proc_address callback in mpv_opengl_init_params.
+ * Generally, mpv will not load the system OpenGL library when using this API.
+ *
+ * OpenGL state
+ * ------------
+ *
+ * OpenGL has a large amount of implicit state. All the mpv functions mentioned
+ * above expect that the OpenGL state is reasonably set to OpenGL standard
+ * defaults. Likewise, mpv will attempt to leave the OpenGL context with
+ * standard defaults. The following state is excluded from this:
+ *
+ *      - the glViewport state
+ *      - the glScissor state (but GL_SCISSOR_TEST is in its default value)
+ *      - glBlendFuncSeparate() state (but GL_BLEND is in its default value)
+ *      - glClearColor() state
+ *      - mpv may overwrite the callback set with glDebugMessageCallback()
+ *      - mpv always disables GL_DITHER at init
+ *
+ * Messing with the state could be avoided by creating shared OpenGL contexts,
+ * but this is avoided for the sake of compatibility and interoperability.
+ *
+ * On OpenGL 2.1, mpv will strictly call functions like glGenTextures() to
+ * create OpenGL objects. You will have to do the same. This ensures that
+ * objects created by mpv and the API users don't clash. Also, legacy state
+ * must be either in its defaults, or not interfere with core state.
+ *
+ * API use
+ * -------
+ *
+ * The mpv_render_* API is used. That API supports multiple backends, and this
+ * section documents specifics for the OpenGL backend.
+ *
+ * Use mpv_render_context_create() with MPV_RENDER_PARAM_API_TYPE set to
+ * MPV_RENDER_API_TYPE_OPENGL, and MPV_RENDER_PARAM_OPENGL_INIT_PARAMS provided.
+ *
+ * Call mpv_render_context_render() with MPV_RENDER_PARAM_OPENGL_FBO to render
+ * the video frame to an FBO.
+ *
+ * Hardware decoding
+ * -----------------
+ *
+ * Hardware decoding via this API is fully supported, but requires some
+ * additional setup. (At least if direct hardware decoding modes are wanted,
+ * instead of copying back surface data from GPU to CPU RAM.)
+ *
+ * There may be certain requirements on the OpenGL implementation:
+ *
+ * - Windows: ANGLE is required (although in theory GL/DX interop could be used)
+ * - Intel/Linux: EGL is required, and also the native display resource needs
+ *                to be provided (e.g. MPV_RENDER_PARAM_X11_DISPLAY for X11 and
+ *                MPV_RENDER_PARAM_WL_DISPLAY for Wayland)
+ * - nVidia/Linux: Both GLX and EGL should work (GLX is required if vdpau is
+ *                 used, e.g. due to old drivers.)
+ * - macOS: CGL is required (CGLGetCurrentContext() returning non-NULL)
+ * - iOS: EAGL is required (EAGLContext.currentContext returning non-nil)
+ *
+ * Once these things are setup, hardware decoding can be enabled/disabled at
+ * any time by setting the "hwdec" property.
+ */
+
+/**
+ * For initializing the mpv OpenGL state via MPV_RENDER_PARAM_OPENGL_INIT_PARAMS.
+ */
+typedef struct mpv_opengl_init_params {
+    /**
+     * This retrieves OpenGL function pointers, and will use them in subsequent
+     * operation.
+     * Usually, you can simply call the GL context APIs from this callback (e.g.
+     * glXGetProcAddressARB or wglGetProcAddress), but some APIs do not always
+     * return pointers for all standard functions (even if present); in this
+     * case you have to compensate by looking up these functions yourself when
+     * libmpv wants to resolve them through this callback.
+     * libmpv will not normally attempt to resolve GL functions on its own, nor
+     * does it link to GL libraries directly.
+     */
+    void *(*get_proc_address)(void *ctx, const char *name);
+    /**
+     * Value passed as ctx parameter to get_proc_address().
+     */
+    void *get_proc_address_ctx;
+} mpv_opengl_init_params;
+
+/**
+ * For MPV_RENDER_PARAM_OPENGL_FBO.
+ */
+typedef struct mpv_opengl_fbo {
+    /**
+     * Framebuffer object name. This must be either a valid FBO generated by
+     * glGenFramebuffers() that is complete and color-renderable, or 0. If the
+     * value is 0, this refers to the OpenGL default framebuffer.
+     */
+    int fbo;
+    /**
+     * Valid dimensions. This must refer to the size of the framebuffer. This
+     * must always be set.
+     */
+    int w, h;
+    /**
+     * Underlying texture internal format (e.g. GL_RGBA8), or 0 if unknown. If
+     * this is the default framebuffer, this can be an equivalent.
+     */
+    int internal_format;
+} mpv_opengl_fbo;
+
+/**
+ * Deprecated. For MPV_RENDER_PARAM_DRM_DISPLAY.
+ */
+typedef struct mpv_opengl_drm_params {
+    int fd;
+    int crtc_id;
+    int connector_id;
+    struct _drmModeAtomicReq **atomic_request_ptr;
+    int render_fd;
+} mpv_opengl_drm_params;
+
+/**
+ * For MPV_RENDER_PARAM_DRM_DRAW_SURFACE_SIZE.
+ */
+typedef struct mpv_opengl_drm_draw_surface_size {
+    /**
+     * size of the draw plane surface in pixels.
+     */
+    int width, height;
+} mpv_opengl_drm_draw_surface_size;
+
+/**
+ * For MPV_RENDER_PARAM_DRM_DISPLAY_V2.
+ */
+typedef struct mpv_opengl_drm_params_v2 {
+    /**
+     * DRM fd (int). Set to -1 if invalid.
+     */
+    int fd;
+
+    /**
+     * Currently used crtc id
+     */
+    int crtc_id;
+
+    /**
+     * Currently used connector id
+     */
+    int connector_id;
+
+    /**
+     * Pointer to a drmModeAtomicReq pointer that is being used for the renderloop.
+     * This pointer should hold a pointer to the atomic request pointer
+     * The atomic request pointer is usually changed at every renderloop.
+     */
+    struct _drmModeAtomicReq **atomic_request_ptr;
+
+    /**
+     * DRM render node. Used for VAAPI interop.
+     * Set to -1 if invalid.
+     */
+    int render_fd;
+} mpv_opengl_drm_params_v2;
+
+
+/**
+ * For backwards compatibility with the old naming of mpv_opengl_drm_draw_surface_size
+ */
+#define mpv_opengl_drm_osd_size mpv_opengl_drm_draw_surface_size
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/include/stream_cb.h b/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/include/stream_cb.h
new file mode 100644
index 00000000..9ae6f31a
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/include/stream_cb.h
@@ -0,0 +1,247 @@
+/* Copyright (C) 2017 the mpv developers
+ *
+ * Permission to use, copy, modify, and/or distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#ifndef MPV_CLIENT_API_STREAM_CB_H_
+#define MPV_CLIENT_API_STREAM_CB_H_
+
+#include "client.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * Warning: this API is not stable yet.
+ *
+ * Overview
+ * --------
+ *
+ * This API can be used to make mpv read from a stream with a custom
+ * implementation. This interface is inspired by funopen on BSD and
+ * fopencookie on linux. The stream is backed by user-defined callbacks
+ * which can implement customized open, read, seek, size and close behaviors.
+ *
+ * Usage
+ * -----
+ *
+ * Register your stream callbacks with the mpv_stream_cb_add_ro() function. You
+ * have to provide a mpv_stream_cb_open_ro_fn callback to it (open_fn argument).
+ *
+ * Once registered, you can `loadfile myprotocol://myfile`. Your open_fn will be
+ * invoked with the URI and you must fill out the provided mpv_stream_cb_info
+ * struct. This includes your stream callbacks (like read_fn), and an opaque
+ * cookie, which will be passed as the first argument to all the remaining
+ * stream callbacks.
+ *
+ * Note that your custom callbacks must not invoke libmpv APIs as that would
+ * cause a deadlock. (Unless you call a different mpv_handle than the one the
+ * callback was registered for, and the mpv_handles refer to different mpv
+ * instances.)
+ *
+ * Stream lifetime
+ * ---------------
+ *
+ * A stream remains valid until its close callback has been called. It's up to
+ * libmpv to call the close callback, and the libmpv user cannot close it
+ * directly with the stream_cb API.
+ *
+ * For example, if you consider your custom stream to become suddenly invalid
+ * (maybe because the underlying stream died), libmpv will continue using your
+ * stream. All you can do is returning errors from each callback, until libmpv
+ * gives up and closes it.
+ *
+ * Protocol registration and lifetime
+ * ----------------------------------
+ *
+ * Protocols remain registered until the mpv instance is terminated. This means
+ * in particular that it can outlive the mpv_handle that was used to register
+ * it, but once mpv_terminate_destroy() is called, your registered callbacks
+ * will not be called again.
+ *
+ * Protocol unregistration is finished after the mpv core has been destroyed
+ * (e.g. after mpv_terminate_destroy() has returned).
+ *
+ * If you do not call mpv_terminate_destroy() yourself (e.g. plugin-style code),
+ * you will have to deal with the registration or even streams outliving your
+ * code. Here are some possible ways to do this:
+ * - call mpv_terminate_destroy(), which destroys the core, and will make sure
+ *   all streams are closed once this function returns
+ * - you refcount all resources your stream "cookies" reference, so that it
+ *   doesn't matter if streams live longer than expected
+ * - create "cancellation" semantics: after your protocol has been unregistered,
+ *   notify all your streams that are still opened, and make them drop all
+ *   referenced resources - then return errors from the stream callbacks as
+ *   long as the stream is still opened
+ *
+ */
+
+/**
+ * Read callback used to implement a custom stream. The semantics of the
+ * callback match read(2) in blocking mode. Short reads are allowed (you can
+ * return less bytes than requested, and libmpv will retry reading the rest
+ * with another call). If no data can be immediately read, the callback must
+ * block until there is new data. A return of 0 will be interpreted as final
+ * EOF, although libmpv might retry the read, or seek to a different position.
+ *
+ * @param cookie opaque cookie identifying the stream,
+ *               returned from mpv_stream_cb_open_fn
+ * @param buf buffer to read data into
+ * @param size of the buffer
+ * @return number of bytes read into the buffer
+ * @return 0 on EOF
+ * @return -1 on error
+ */
+typedef int64_t (*mpv_stream_cb_read_fn)(void *cookie, char *buf, uint64_t nbytes);
+
+/**
+ * Seek callback used to implement a custom stream.
+ *
+ * Note that mpv will issue a seek to position 0 immediately after opening. This
+ * is used to test whether the stream is seekable (since seekability might
+ * depend on the URI contents, not just the protocol). Return
+ * MPV_ERROR_UNSUPPORTED if seeking is not implemented for this stream. This
+ * seek also serves to establish the fact that streams start at position 0.
+ *
+ * This callback can be NULL, in which it behaves as if always returning
+ * MPV_ERROR_UNSUPPORTED.
+ *
+ * @param cookie opaque cookie identifying the stream,
+ *               returned from mpv_stream_cb_open_fn
+ * @param offset target absolute stream position
+ * @return the resulting offset of the stream
+ *         MPV_ERROR_UNSUPPORTED or MPV_ERROR_GENERIC if the seek failed
+ */
+typedef int64_t (*mpv_stream_cb_seek_fn)(void *cookie, int64_t offset);
+
+/**
+ * Size callback used to implement a custom stream.
+ *
+ * Return MPV_ERROR_UNSUPPORTED if no size is known.
+ *
+ * This callback can be NULL, in which it behaves as if always returning
+ * MPV_ERROR_UNSUPPORTED.
+ *
+ * @param cookie opaque cookie identifying the stream,
+ *               returned from mpv_stream_cb_open_fn
+ * @return the total size in bytes of the stream
+ */
+typedef int64_t (*mpv_stream_cb_size_fn)(void *cookie);
+
+/**
+ * Close callback used to implement a custom stream.
+ *
+ * @param cookie opaque cookie identifying the stream,
+ *               returned from mpv_stream_cb_open_fn
+ */
+typedef void (*mpv_stream_cb_close_fn)(void *cookie);
+
+/**
+ * Cancel callback used to implement a custom stream.
+ *
+ * This callback is used to interrupt any current or future read and seek
+ * operations. It will be called from a separate thread than the demux
+ * thread, and should not block.
+ *
+ * This callback can be NULL.
+ *
+ * Available since API 1.106.
+ *
+ * @param cookie opaque cookie identifying the stream,
+ *               returned from mpv_stream_cb_open_fn
+ */
+typedef void (*mpv_stream_cb_cancel_fn)(void *cookie);
+
+/**
+ * See mpv_stream_cb_open_ro_fn callback.
+ */
+typedef struct mpv_stream_cb_info {
+    /**
+     * Opaque user-provided value, which will be passed to the other callbacks.
+     * The close callback will be called to release the cookie. It is not
+     * interpreted by mpv. It doesn't even need to be a valid pointer.
+     *
+     * The user sets this in the mpv_stream_cb_open_ro_fn callback.
+     */
+    void *cookie;
+
+    /**
+     * Callbacks set by the user in the mpv_stream_cb_open_ro_fn callback. Some
+     * of them are optional, and can be left unset.
+     *
+     * The following callbacks are mandatory: read_fn, close_fn
+     */
+    mpv_stream_cb_read_fn read_fn;
+    mpv_stream_cb_seek_fn seek_fn;
+    mpv_stream_cb_size_fn size_fn;
+    mpv_stream_cb_close_fn close_fn;
+    mpv_stream_cb_cancel_fn cancel_fn; /* since API 1.106 */
+} mpv_stream_cb_info;
+
+/**
+ * Open callback used to implement a custom read-only (ro) stream. The user
+ * must set the callback fields in the passed info struct. The cookie field
+ * also can be set to store state associated to the stream instance.
+ *
+ * Note that the info struct is valid only for the duration of this callback.
+ * You can't change the callbacks or the pointer to the cookie at a later point.
+ *
+ * Each stream instance created by the open callback can have different
+ * callbacks.
+ *
+ * The close_fn callback will terminate the stream instance. The pointers to
+ * your callbacks and cookie will be discarded, and the callbacks will not be
+ * called again.
+ *
+ * @param user_data opaque user data provided via mpv_stream_cb_add()
+ * @param uri name of the stream to be opened (with protocol prefix)
+ * @param info fields which the user should fill
+ * @return 0 on success, MPV_ERROR_LOADING_FAILED if the URI cannot be opened.
+ */
+typedef int (*mpv_stream_cb_open_ro_fn)(void *user_data, char *uri,
+                                        mpv_stream_cb_info *info);
+
+/**
+ * Add a custom stream protocol. This will register a protocol handler under
+ * the given protocol prefix, and invoke the given callbacks if an URI with the
+ * matching protocol prefix is opened.
+ *
+ * The "ro" is for read-only - only read-only streams can be registered with
+ * this function.
+ *
+ * The callback remains registered until the mpv core is registered.
+ *
+ * If a custom stream with the same name is already registered, then the
+ * MPV_ERROR_INVALID_PARAMETER error is returned.
+ *
+ * @param protocol protocol prefix, for example "foo" for "foo://" URIs
+ * @param user_data opaque pointer passed into the mpv_stream_cb_open_fn
+ *                  callback.
+ * @return error code
+ */
+MPV_EXPORT int mpv_stream_cb_add_ro(mpv_handle *ctx, const char *protocol, void *user_data,
+                                    mpv_stream_cb_open_ro_fn open_fn);
+
+#ifdef MPV_CPLUGIN_DYNAMIC_SYM
+
+MPV_DEFINE_SYM_PTR(mpv_stream_cb_add_ro)
+#define mpv_stream_cb_add_ro pfn_mpv_stream_cb_add_ro
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/src/lib.rs b/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/src/lib.rs
new file mode 100644
index 00000000..aa544c72
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/libmpv2-sys/src/lib.rs
@@ -0,0 +1,12 @@
+#![allow(non_upper_case_globals)]
+#![allow(non_camel_case_types)]
+#![allow(non_snake_case)]
+
+include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
+
+#[inline]
+/// Returns the associated error string.
+pub fn mpv_error_str(e: mpv_error) -> &'static str {
+    let raw = unsafe { mpv_error_string(e) };
+    unsafe { ::std::ffi::CStr::from_ptr(raw) }.to_str().unwrap()
+}
diff --git a/pkgs/by-name/yt/yt/libmpv2/src/lib.rs b/pkgs/by-name/yt/yt/libmpv2/src/lib.rs
new file mode 100644
index 00000000..4b267e24
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/src/lib.rs
@@ -0,0 +1,96 @@
+//! This crate provides abstractions for
+//! [libmpv](https://github.com/mpv-player/mpv/tree/master/libmpv) of the
+//! [mpv media player](https://github.com/mpv-player/mpv).
+//!
+//! Libmpv requires `LC_NUMERIC` to be `C`, which should be the default value.
+//!
+//! Most of the documentation is paraphrased or even copied from the
+//! [mpv manual](https://mpv.io/manual/master/),
+//! if any questions arise it will probably answer them in much more depth than this documentation.
+//!
+//! # Examples
+//!
+//! See the 'examples' directory in the crate root.
+
+// Procedure for updating to new libmpv:
+// - make any nessecary API change (if so, bump crate version)
+// - update MPV_CLIENT_API consts in lib.rs
+// - run tests and examples to test whether they still work
+
+#![allow(non_upper_case_globals)]
+
+use std::os::raw as ctype;
+
+pub const MPV_CLIENT_API_MAJOR: ctype::c_ulong = 2;
+pub const MPV_CLIENT_API_MINOR: ctype::c_ulong = 2;
+pub const MPV_CLIENT_API_VERSION: ctype::c_ulong =
+    MPV_CLIENT_API_MAJOR << 16 | MPV_CLIENT_API_MINOR;
+
+mod mpv;
+#[cfg(test)]
+mod tests;
+
+pub use crate::mpv::*;
+
+/// A format mpv can use.
+pub use libmpv2_sys::mpv_format as MpvFormat;
+pub mod mpv_format {
+    pub use libmpv2_sys::mpv_format_MPV_FORMAT_DOUBLE as Double;
+    pub use libmpv2_sys::mpv_format_MPV_FORMAT_FLAG as Flag;
+    pub use libmpv2_sys::mpv_format_MPV_FORMAT_INT64 as Int64;
+    pub use libmpv2_sys::mpv_format_MPV_FORMAT_NODE as Node;
+    pub use libmpv2_sys::mpv_format_MPV_FORMAT_NODE_ARRAY as Array;
+    pub use libmpv2_sys::mpv_format_MPV_FORMAT_NODE_MAP as Map;
+    pub use libmpv2_sys::mpv_format_MPV_FORMAT_NONE as None;
+    pub use libmpv2_sys::mpv_format_MPV_FORMAT_OSD_STRING as OsdString;
+    pub use libmpv2_sys::mpv_format_MPV_FORMAT_STRING as String;
+}
+
+/// An libmpv2_sys mpv error.
+pub use libmpv2_sys::mpv_error as MpvError;
+pub mod mpv_error {
+    pub use libmpv2_sys::mpv_error_MPV_ERROR_AO_INIT_FAILED as AoInitFailed;
+    pub use libmpv2_sys::mpv_error_MPV_ERROR_COMMAND as Command;
+    pub use libmpv2_sys::mpv_error_MPV_ERROR_EVENT_QUEUE_FULL as EventQueueFull;
+    pub use libmpv2_sys::mpv_error_MPV_ERROR_GENERIC as Generic;
+    pub use libmpv2_sys::mpv_error_MPV_ERROR_INVALID_PARAMETER as InvalidParameter;
+    pub use libmpv2_sys::mpv_error_MPV_ERROR_LOADING_FAILED as LoadingFailed;
+    pub use libmpv2_sys::mpv_error_MPV_ERROR_NOMEM as NoMem;
+    pub use libmpv2_sys::mpv_error_MPV_ERROR_NOTHING_TO_PLAY as NothingToPlay;
+    pub use libmpv2_sys::mpv_error_MPV_ERROR_NOT_IMPLEMENTED as NotImplemented;
+    pub use libmpv2_sys::mpv_error_MPV_ERROR_OPTION_ERROR as OptionError;
+    pub use libmpv2_sys::mpv_error_MPV_ERROR_OPTION_FORMAT as OptionFormat;
+    pub use libmpv2_sys::mpv_error_MPV_ERROR_OPTION_NOT_FOUND as OptionNotFound;
+    pub use libmpv2_sys::mpv_error_MPV_ERROR_PROPERTY_ERROR as PropertyError;
+    pub use libmpv2_sys::mpv_error_MPV_ERROR_PROPERTY_FORMAT as PropertyFormat;
+    pub use libmpv2_sys::mpv_error_MPV_ERROR_PROPERTY_NOT_FOUND as PropertyNotFound;
+    pub use libmpv2_sys::mpv_error_MPV_ERROR_PROPERTY_UNAVAILABLE as PropertyUnavailable;
+    pub use libmpv2_sys::mpv_error_MPV_ERROR_SUCCESS as Success;
+    pub use libmpv2_sys::mpv_error_MPV_ERROR_UNINITIALIZED as Uninitialized;
+    pub use libmpv2_sys::mpv_error_MPV_ERROR_UNKNOWN_FORMAT as UnknownFormat;
+    pub use libmpv2_sys::mpv_error_MPV_ERROR_UNSUPPORTED as Unsupported;
+    pub use libmpv2_sys::mpv_error_MPV_ERROR_VO_INIT_FAILED as VoInitFailed;
+}
+
+/// Log verbosity level.
+pub use libmpv2_sys::mpv_log_level as LogLevel;
+pub mod mpv_log_level {
+    pub use libmpv2_sys::mpv_log_level_MPV_LOG_LEVEL_DEBUG as Debug;
+    pub use libmpv2_sys::mpv_log_level_MPV_LOG_LEVEL_ERROR as Error;
+    pub use libmpv2_sys::mpv_log_level_MPV_LOG_LEVEL_FATAL as Fatal;
+    pub use libmpv2_sys::mpv_log_level_MPV_LOG_LEVEL_INFO as Info;
+    pub use libmpv2_sys::mpv_log_level_MPV_LOG_LEVEL_NONE as None;
+    pub use libmpv2_sys::mpv_log_level_MPV_LOG_LEVEL_TRACE as Trace;
+    pub use libmpv2_sys::mpv_log_level_MPV_LOG_LEVEL_V as V;
+    pub use libmpv2_sys::mpv_log_level_MPV_LOG_LEVEL_WARN as Warn;
+}
+
+/// The reason a file stopped.
+pub use libmpv2_sys::mpv_end_file_reason as EndFileReason;
+pub mod mpv_end_file_reason {
+    pub use libmpv2_sys::mpv_end_file_reason_MPV_END_FILE_REASON_EOF as Eof;
+    pub use libmpv2_sys::mpv_end_file_reason_MPV_END_FILE_REASON_ERROR as Error;
+    pub use libmpv2_sys::mpv_end_file_reason_MPV_END_FILE_REASON_QUIT as Quit;
+    pub use libmpv2_sys::mpv_end_file_reason_MPV_END_FILE_REASON_REDIRECT as Redirect;
+    pub use libmpv2_sys::mpv_end_file_reason_MPV_END_FILE_REASON_STOP as Stop;
+}
diff --git a/pkgs/by-name/yt/yt/libmpv2/src/mpv.rs b/pkgs/by-name/yt/yt/libmpv2/src/mpv.rs
new file mode 100644
index 00000000..007db124
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/src/mpv.rs
@@ -0,0 +1,610 @@
+macro_rules! mpv_cstr_to_str {
+    ($cstr: expr) => {
+        std::ffi::CStr::from_ptr($cstr)
+            .to_str()
+            .map_err(Error::from)
+    };
+}
+
+mod errors;
+
+/// Event handling
+pub mod events;
+/// Custom protocols (`protocol://$url`) for playback
+#[cfg(feature = "protocols")]
+pub mod protocol;
+/// Custom rendering
+#[cfg(feature = "render")]
+pub mod render;
+
+use log::debug;
+
+pub use self::errors::*;
+use self::events::EventContext;
+use super::*;
+
+use std::{
+    ffi::CString,
+    mem::MaybeUninit,
+    ops::Deref,
+    ptr::{self, NonNull},
+    sync::atomic::AtomicBool,
+};
+
+fn mpv_err<T>(ret: T, err: ctype::c_int) -> Result<T> {
+    if err == 0 {
+        Ok(ret)
+    } else {
+        // debug!("Creating a raw error: {}", to_string_mpv_error(err));
+        Err(Error::Raw(err))
+    }
+}
+
+/// This trait describes which types are allowed to be passed to getter mpv APIs.
+pub unsafe trait GetData: Sized {
+    #[doc(hidden)]
+    fn get_from_c_void<T, F: FnMut(*mut ctype::c_void) -> Result<T>>(mut fun: F) -> Result<Self> {
+        let mut val = MaybeUninit::uninit();
+        let _ = fun(val.as_mut_ptr() as *mut _)?;
+        Ok(unsafe { val.assume_init() })
+    }
+    fn get_format() -> Format;
+}
+
+/// This trait describes which types are allowed to be passed to setter mpv APIs.
+pub unsafe trait SetData: Sized {
+    #[doc(hidden)]
+    fn call_as_c_void<T, F: FnMut(*mut ctype::c_void) -> Result<T>>(
+        mut self,
+        mut fun: F,
+    ) -> Result<T> {
+        fun(&mut self as *mut Self as _)
+    }
+    fn get_format() -> Format;
+}
+
+unsafe impl GetData for f64 {
+    fn get_format() -> Format {
+        Format::Double
+    }
+}
+
+unsafe impl SetData for f64 {
+    fn get_format() -> Format {
+        Format::Double
+    }
+}
+
+unsafe impl GetData for i64 {
+    fn get_format() -> Format {
+        Format::Int64
+    }
+}
+
+pub mod mpv_node {
+    use self::sys_node::SysMpvNode;
+    use crate::{Error, Format, GetData, Result};
+    use std::{mem::MaybeUninit, os::raw::c_void, ptr};
+
+    #[derive(Debug, Clone)]
+    pub enum MpvNode {
+        String(String),
+        Flag(bool),
+        Int64(i64),
+        Double(f64),
+        ArrayIter(MpvNodeArrayIter),
+        MapIter(MpvNodeMapIter),
+        None,
+    }
+
+    impl MpvNode {
+        pub fn bool(&self) -> Option<bool> {
+            if let MpvNode::Flag(value) = *self {
+                Some(value)
+            } else {
+                None
+            }
+        }
+        pub fn i64(&self) -> Option<i64> {
+            if let MpvNode::Int64(value) = *self {
+                Some(value)
+            } else {
+                None
+            }
+        }
+        pub fn f64(&self) -> Option<f64> {
+            if let MpvNode::Double(value) = *self {
+                Some(value)
+            } else {
+                None
+            }
+        }
+
+        pub fn str(&self) -> Option<&str> {
+            if let MpvNode::String(value) = self {
+                Some(value)
+            } else {
+                None
+            }
+        }
+
+        pub fn array(self) -> Option<MpvNodeArrayIter> {
+            if let MpvNode::ArrayIter(value) = self {
+                Some(value)
+            } else {
+                None
+            }
+        }
+
+        pub fn map(self) -> Option<MpvNodeMapIter> {
+            if let MpvNode::MapIter(value) = self {
+                Some(value)
+            } else {
+                None
+            }
+        }
+    }
+
+    impl PartialEq for MpvNode {
+        fn eq(&self, other: &Self) -> bool {
+            match (self, other) {
+                (Self::String(l0), Self::String(r0)) => l0 == r0,
+                (Self::Flag(l0), Self::Flag(r0)) => l0 == r0,
+                (Self::Int64(l0), Self::Int64(r0)) => l0 == r0,
+                (Self::Double(l0), Self::Double(r0)) => l0 == r0,
+                (Self::ArrayIter(l0), Self::ArrayIter(r0)) => l0.clone().eq(r0.clone()),
+                (Self::MapIter(l0), Self::MapIter(r0)) => l0.clone().eq(r0.clone()),
+                _ => core::mem::discriminant(self) == core::mem::discriminant(other),
+            }
+        }
+    }
+
+    #[derive(Debug)]
+    struct DropWrapper(libmpv2_sys::mpv_node);
+
+    impl Drop for DropWrapper {
+        fn drop(&mut self) {
+            unsafe {
+                libmpv2_sys::mpv_free_node_contents(&mut self.0 as *mut libmpv2_sys::mpv_node)
+            };
+        }
+    }
+
+    pub mod sys_node {
+        use super::{DropWrapper, MpvNode, MpvNodeArrayIter, MpvNodeMapIter};
+        use crate::{mpv_error, mpv_format, Error, Result};
+        use std::rc::Rc;
+
+        #[derive(Debug, Clone)]
+        pub struct SysMpvNode {
+            // Reference counted pointer to a parent node so it stays alive long enough.
+            //
+            // MPV has one big cleanup function that takes a node so store the parent node
+            // and force it to stay alive until the reference count hits 0.
+            parent: Option<Rc<DropWrapper>>,
+            node: libmpv2_sys::mpv_node,
+        }
+
+        impl SysMpvNode {
+            pub fn new(node: libmpv2_sys::mpv_node, drop: bool) -> Self {
+                Self {
+                    parent: if drop {
+                        Some(Rc::new(DropWrapper(node)))
+                    } else {
+                        None
+                    },
+                    node,
+                }
+            }
+
+            pub fn child(self: Self, node: libmpv2_sys::mpv_node) -> Self {
+                Self {
+                    parent: self.parent,
+                    node,
+                }
+            }
+
+            pub fn value(&self) -> Result<MpvNode> {
+                let node = self.node;
+                Ok(match node.format {
+                    mpv_format::Flag => MpvNode::Flag(unsafe { node.u.flag } == 1),
+                    mpv_format::Int64 => MpvNode::Int64(unsafe { node.u.int64 }),
+                    mpv_format::Double => MpvNode::Double(unsafe { node.u.double_ }),
+                    mpv_format::String => {
+                        let text = unsafe { mpv_cstr_to_str!(node.u.string) }?.to_owned();
+                        MpvNode::String(text)
+                    }
+                    mpv_format::Array => {
+                        let list = unsafe { *node.u.list };
+                        let iter = MpvNodeArrayIter {
+                            node: self.clone(),
+                            start: unsafe { *node.u.list }.values,
+                            end: unsafe { list.values.offset(list.num.try_into().unwrap()) },
+                        };
+                        return Ok(MpvNode::ArrayIter(iter));
+                    }
+
+                    mpv_format::Map => MpvNode::MapIter(MpvNodeMapIter {
+                        list: unsafe { *node.u.list },
+                        curr: 0,
+                        node: self.clone(),
+                    }),
+                    mpv_format::None => MpvNode::None,
+                    _ => return Err(Error::Raw(mpv_error::PropertyError)),
+                })
+            }
+        }
+    }
+
+    #[derive(Debug, Clone)]
+    pub struct MpvNodeArrayIter {
+        // Reference counted pointer to a parent node so it stays alive long enough.
+        //
+        // MPV has one big cleanup function that takes a node so store the parent node
+        // and force it to stay alive until the reference count hits 0.
+        node: SysMpvNode,
+        start: *const libmpv2_sys::mpv_node,
+        end: *const libmpv2_sys::mpv_node,
+    }
+
+    impl Iterator for MpvNodeArrayIter {
+        type Item = MpvNode;
+
+        fn next(&mut self) -> Option<Self::Item> {
+            if self.start == self.end {
+                None
+            } else {
+                unsafe {
+                    let result = ptr::read(self.start);
+                    let node = SysMpvNode::child(self.node.clone(), result);
+                    self.start = self.start.offset(1);
+                    node.value().ok()
+                }
+            }
+        }
+    }
+
+    #[derive(Debug, Clone)]
+    pub struct MpvNodeMapIter {
+        // Reference counted pointer to a parent node so it stays alive long enough.
+        //
+        // MPV has one big cleanup function that takes a node so store the parent node
+        // and force it to stay alive until the reference count hits 0.
+        node: SysMpvNode,
+        list: libmpv2_sys::mpv_node_list,
+        curr: usize,
+    }
+
+    impl Iterator for MpvNodeMapIter {
+        type Item = (String, MpvNode);
+
+        fn next(&mut self) -> Option<Self::Item> {
+            if self.curr >= self.list.num.try_into().unwrap() {
+                None
+            } else {
+                let offset = self.curr.try_into().unwrap();
+                let (key, value) = unsafe {
+                    (
+                        mpv_cstr_to_str!(*self.list.keys.offset(offset)),
+                        *self.list.values.offset(offset),
+                    )
+                };
+                self.curr += 1;
+                let node = SysMpvNode::child(self.node.clone(), value);
+                Some((key.unwrap().to_string(), node.value().unwrap()))
+            }
+        }
+    }
+
+    unsafe impl GetData for MpvNode {
+        fn get_from_c_void<T, F: FnMut(*mut c_void) -> Result<T>>(mut fun: F) -> Result<Self> {
+            let mut val = MaybeUninit::uninit();
+            fun(val.as_mut_ptr() as *mut _)?;
+            let sys_node = unsafe { val.assume_init() };
+            let node = SysMpvNode::new(sys_node, true);
+            node.value()
+        }
+
+        fn get_format() -> Format {
+            Format::Node
+        }
+    }
+}
+
+unsafe impl SetData for i64 {
+    fn get_format() -> Format {
+        Format::Int64
+    }
+}
+
+unsafe impl GetData for bool {
+    fn get_format() -> Format {
+        Format::Flag
+    }
+}
+
+unsafe impl SetData for bool {
+    fn call_as_c_void<T, F: FnMut(*mut ctype::c_void) -> Result<T>>(self, mut fun: F) -> Result<T> {
+        let mut cpy: i64 = if self { 1 } else { 0 };
+        fun(&mut cpy as *mut i64 as *mut _)
+    }
+
+    fn get_format() -> Format {
+        Format::Flag
+    }
+}
+
+unsafe impl GetData for String {
+    fn get_from_c_void<T, F: FnMut(*mut ctype::c_void) -> Result<T>>(mut fun: F) -> Result<String> {
+        let ptr = &mut ptr::null();
+        fun(ptr as *mut *const ctype::c_char as _)?;
+
+        let ret = unsafe { mpv_cstr_to_str!(*ptr) }?.to_owned();
+        unsafe { libmpv2_sys::mpv_free(*ptr as *mut _) };
+        Ok(ret)
+    }
+
+    fn get_format() -> Format {
+        Format::String
+    }
+}
+
+unsafe impl SetData for String {
+    fn call_as_c_void<T, F: FnMut(*mut ctype::c_void) -> Result<T>>(self, mut fun: F) -> Result<T> {
+        let string = CString::new(self)?;
+        fun((&mut string.as_ptr()) as *mut *const ctype::c_char as *mut _)
+    }
+
+    fn get_format() -> Format {
+        Format::String
+    }
+}
+
+/// Wrapper around an `&str` returned by mpv, that properly deallocates it with mpv's allocator.
+#[derive(Debug, Hash, Eq, PartialEq)]
+pub struct MpvStr<'a>(&'a str);
+impl<'a> Deref for MpvStr<'a> {
+    type Target = str;
+
+    fn deref(&self) -> &str {
+        self.0
+    }
+}
+impl<'a> Drop for MpvStr<'a> {
+    fn drop(&mut self) {
+        unsafe { libmpv2_sys::mpv_free(self.0.as_ptr() as *mut u8 as _) };
+    }
+}
+
+unsafe impl<'a> GetData for MpvStr<'a> {
+    fn get_from_c_void<T, F: FnMut(*mut ctype::c_void) -> Result<T>>(
+        mut fun: F,
+    ) -> Result<MpvStr<'a>> {
+        let ptr = &mut ptr::null();
+        let _ = fun(ptr as *mut *const ctype::c_char as _)?;
+
+        Ok(MpvStr(unsafe { mpv_cstr_to_str!(*ptr) }?))
+    }
+
+    fn get_format() -> Format {
+        Format::String
+    }
+}
+
+unsafe impl<'a> SetData for &'a str {
+    fn call_as_c_void<T, F: FnMut(*mut ctype::c_void) -> Result<T>>(self, mut fun: F) -> Result<T> {
+        let string = CString::new(self)?;
+        fun((&mut string.as_ptr()) as *mut *const ctype::c_char as *mut _)
+    }
+
+    fn get_format() -> Format {
+        Format::String
+    }
+}
+
+#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
+/// Subset of `mpv_format` used by the public API.
+pub enum Format {
+    String,
+    Flag,
+    Int64,
+    Double,
+    Node,
+}
+
+impl Format {
+    fn as_mpv_format(&self) -> MpvFormat {
+        match *self {
+            Format::String => mpv_format::String,
+            Format::Flag => mpv_format::Flag,
+            Format::Int64 => mpv_format::Int64,
+            Format::Double => mpv_format::Double,
+            Format::Node => mpv_format::Node,
+        }
+    }
+}
+
+/// Context passed to the `initializer` of `Mpv::with_initialzer`.
+pub struct MpvInitializer {
+    ctx: *mut libmpv2_sys::mpv_handle,
+}
+
+impl MpvInitializer {
+    /// Set the value of a property.
+    pub fn set_property<T: SetData>(&self, name: &str, data: T) -> Result<()> {
+        let name = CString::new(name)?;
+        let format = T::get_format().as_mpv_format() as _;
+        data.call_as_c_void(|ptr| {
+            mpv_err((), unsafe {
+                libmpv2_sys::mpv_set_property(self.ctx, name.as_ptr(), format, ptr)
+            })
+        })
+    }
+
+    /// Set the value of an option
+    pub fn set_option<T: SetData>(&self, name: &str, data: T) -> Result<()> {
+        let name = CString::new(name)?;
+        let format = T::get_format().as_mpv_format() as _;
+        data.call_as_c_void(|ptr| {
+            mpv_err((), unsafe {
+                libmpv2_sys::mpv_set_option(self.ctx, name.as_ptr(), format, ptr)
+            })
+        })
+    }
+}
+
+/// The central mpv context.
+pub struct Mpv {
+    /// The handle to the mpv core
+    pub ctx: NonNull<libmpv2_sys::mpv_handle>,
+    event_context: EventContext,
+    #[cfg(feature = "protocols")]
+    protocols_guard: AtomicBool,
+}
+
+unsafe impl Send for Mpv {}
+unsafe impl Sync for Mpv {}
+
+impl Drop for Mpv {
+    fn drop(&mut self) {
+        unsafe {
+            libmpv2_sys::mpv_terminate_destroy(self.ctx.as_ptr());
+        }
+    }
+}
+
+impl Mpv {
+    /// Create a new `Mpv`.
+    /// The default settings can be probed by running: `$ mpv --show-profile=libmpv`.
+    pub fn new() -> Result<Mpv> {
+        Mpv::with_initializer(|_| Ok(()))
+    }
+
+    /// Create a new `Mpv`.
+    /// The same as `Mpv::new`, but you can set properties before `Mpv` is initialized.
+    pub fn with_initializer<F: FnOnce(MpvInitializer) -> Result<()>>(
+        initializer: F,
+    ) -> Result<Mpv> {
+        let api_version = unsafe { libmpv2_sys::mpv_client_api_version() };
+        if crate::MPV_CLIENT_API_MAJOR != api_version >> 16 {
+            return Err(Error::VersionMismatch {
+                linked: crate::MPV_CLIENT_API_VERSION,
+                loaded: api_version,
+            });
+        }
+
+        let ctx = unsafe { libmpv2_sys::mpv_create() };
+        if ctx.is_null() {
+            return Err(Error::Null);
+        }
+
+        initializer(MpvInitializer { ctx })?;
+        mpv_err((), unsafe { libmpv2_sys::mpv_initialize(ctx) }).map_err(|err| {
+            unsafe { libmpv2_sys::mpv_terminate_destroy(ctx) };
+            err
+        })?;
+
+        let ctx = unsafe { NonNull::new_unchecked(ctx) };
+
+        Ok(Mpv {
+            ctx,
+            event_context: EventContext::new(ctx),
+            #[cfg(feature = "protocols")]
+            protocols_guard: AtomicBool::new(false),
+        })
+    }
+
+    /// Execute a command
+    pub fn execute(&self, name: &str, args: &[&str]) -> Result<()> {
+        if args.is_empty() {
+            debug!("Running mpv command: '{}'", name);
+        } else {
+            debug!("Running mpv command: '{} {}'", name, args.join(" "));
+        }
+
+        self.command(name, args)?;
+
+        Ok(())
+    }
+
+    /// Load a configuration file. The path has to be absolute, and a file.
+    pub fn load_config(&self, path: &str) -> Result<()> {
+        let file = CString::new(path)?.into_raw();
+        let ret = mpv_err((), unsafe {
+            libmpv2_sys::mpv_load_config_file(self.ctx.as_ptr(), file)
+        });
+        unsafe {
+            drop(CString::from_raw(file));
+        };
+        ret
+    }
+
+    pub fn event_context(&self) -> &EventContext {
+        &self.event_context
+    }
+
+    pub fn event_context_mut(&mut self) -> &mut EventContext {
+        &mut self.event_context
+    }
+
+    /// Send a command to the `Mpv` instance. This uses `mpv_command_string` internally,
+    /// so that the syntax is the same as described in the [manual for the input.conf](https://mpv.io/manual/master/#list-of-input-commands).
+    ///
+    /// Note that you may have to escape strings with `""` when they contain spaces.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// # use libmpv2::{Mpv};
+    /// # use libmpv2::mpv_node::MpvNode;
+    /// # use std::collections::HashMap;
+    /// mpv.command("loadfile", &["test-data/jellyfish.mp4", "append-play"]).unwrap();
+    /// # let node = mpv.get_property::<MpvNode>("playlist").unwrap();
+    /// # let mut list = node.array().unwrap().collect::<Vec<_>>();
+    /// # let map = list.pop().unwrap().map().unwrap().collect::<HashMap<_, _>>();
+    /// # assert_eq!(map, HashMap::from([(String::from("id"), MpvNode::Int64(1)), (String::from("current"), MpvNode::Flag(true)), (String::from("filename"), MpvNode::String(String::from("test-data/jellyfish.mp4")))]));
+    /// ```
+    pub fn command(&self, name: &str, args: &[&str]) -> Result<()> {
+        let mut cmd = name.to_owned();
+
+        for elem in args {
+            cmd.push(' ');
+            cmd.push_str(elem);
+        }
+
+        let raw = CString::new(cmd)?;
+        mpv_err((), unsafe {
+            libmpv2_sys::mpv_command_string(self.ctx.as_ptr(), raw.as_ptr())
+        })
+    }
+
+    /// Set the value of a property.
+    pub fn set_property<T: SetData>(&self, name: &str, data: T) -> Result<()> {
+        let name = CString::new(name)?;
+        let format = T::get_format().as_mpv_format() as _;
+        data.call_as_c_void(|ptr| {
+            mpv_err((), unsafe {
+                libmpv2_sys::mpv_set_property(self.ctx.as_ptr(), name.as_ptr(), format, ptr)
+            })
+        })
+    }
+
+    /// Get the value of a property.
+    pub fn get_property<T: GetData>(&self, name: &str) -> Result<T> {
+        let name = CString::new(name)?;
+
+        let format = T::get_format().as_mpv_format() as _;
+        T::get_from_c_void(|ptr| {
+            mpv_err((), unsafe {
+                libmpv2_sys::mpv_get_property(self.ctx.as_ptr(), name.as_ptr(), format, ptr)
+            })
+        })
+    }
+
+    /// Internal time in microseconds, this has an arbitrary offset, and will never go backwards.
+    ///
+    /// This can be called at any time, even if it was stated that no API function should be called.
+    pub fn get_internal_time(&self) -> i64 {
+        unsafe { libmpv2_sys::mpv_get_time_us(self.ctx.as_ptr()) }
+    }
+}
diff --git a/pkgs/by-name/yt/yt/libmpv2/src/mpv/errors.rs b/pkgs/by-name/yt/yt/libmpv2/src/mpv/errors.rs
new file mode 100644
index 00000000..f3efda79
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/src/mpv/errors.rs
@@ -0,0 +1,100 @@
+use std::{ffi::NulError, os::raw as ctype, str::Utf8Error};
+
+use thiserror::Error;
+
+use super::mpv_error;
+
+#[allow(missing_docs)]
+pub type Result<T> = ::std::result::Result<T, Error>;
+
+#[derive(Error, Debug)]
+pub enum Error {
+    #[error("loading file failed: {error}")]
+    Loadfile { error: String },
+
+    #[error("version mismatch detected! Linked version ({linked}) is unequal to the loaded version ({loaded})")]
+    VersionMismatch {
+        linked: ctype::c_ulong,
+        loaded: ctype::c_ulong,
+    },
+
+    #[error("invalid utf8 returned")]
+    InvalidUtf8,
+
+    #[error("null pointer returned")]
+    Null,
+
+    #[error("raw error returned: {}", to_string_mpv_error(*(.0)))]
+    Raw(crate::MpvError),
+}
+
+impl From<NulError> for Error {
+    fn from(_other: NulError) -> Error {
+        Error::Null
+    }
+}
+
+impl From<Utf8Error> for Error {
+    fn from(_other: Utf8Error) -> Error {
+        Error::InvalidUtf8
+    }
+}
+impl From<crate::MpvError> for Error {
+    fn from(other: crate::MpvError) -> Error {
+        Error::Raw(other)
+    }
+}
+
+pub(crate) fn to_string_mpv_error(num: crate::MpvError) -> String {
+    let (error, help) = to_string_mpv_error_raw(num);
+
+    if help.is_empty() {
+        error.to_owned()
+    } else {
+        format!("{} ({})", error, help)
+    }
+}
+
+fn to_string_mpv_error_raw(num: crate::MpvError) -> (&'static str, &'static str) {
+    // debug!("Turning error num '{}' to a string.", num);
+
+    match num {
+        mpv_error::EventQueueFull => (
+            "The event ringbuffer is full.",
+            "This means the client is choked, and can't receive any events. This can happen when too many asynchronous requests have been made, but not answered. Probably never happens in practice, unless the mpv core is frozen for some reason, and the client keeps making asynchronous requests. (Bugs in the client API implementation could also trigger this, e.g. if events become \"lost\".)",
+        ),
+
+        mpv_error::NoMem => ("Memory allocation failed.", ""),
+
+        mpv_error::Uninitialized => ("The mpv core wasn't configured and initialized yet", " See the notes in mpv_create()."),
+
+        mpv_error::InvalidParameter => ("Generic catch-all error if a parameter is set to an invalid or unsupported value.", "This is used if there is no better error code."),
+
+        mpv_error::OptionNotFound => ("Trying to set an option that doesn't exist.", ""),
+        mpv_error::OptionFormat => ("Trying to set an option using an unsupported MPV_FORMAT.", ""),
+        mpv_error::OptionError => ("Setting the option failed", " Typically this happens if the provided option value could not be parsed."),
+
+        mpv_error::PropertyNotFound => ("The accessed property doesn't exist.", ""),
+        mpv_error::PropertyFormat => ("Trying to set or get a property using an unsupported MPV_FORMAT.", ""),
+        mpv_error::PropertyUnavailable => ("The property exists, but is not available", "This usually happens when the associated subsystem is not active, e.g. querying audio parameters while audio is disabled."),
+        mpv_error::PropertyError => ("Error setting or getting a property.", ""),
+
+        mpv_error::Command => ("General error when running a command with mpv_command and similar.", ""),
+
+        mpv_error::LoadingFailed => ("Generic error on loading (usually used with mpv_event_end_file.error).", ""),
+
+        mpv_error::AoInitFailed => ("Initializing the audio output failed.", ""),
+        mpv_error::VoInitFailed => ("Initializing the video output failed.", ""),
+
+        mpv_error::NothingToPlay => ("There was no audio or video data to play", "This also happens if the file was recognized, but did not contain any audio or video streams, or no streams were selected."),
+
+        mpv_error::UnknownFormat => ("     * When trying to load the file, the file format could not be determined, or the file was too broken to open it.", ""),
+
+        mpv_error::Generic => ("Generic error for signaling that certain system requirements are not fulfilled.", ""),
+        mpv_error::NotImplemented => ("The API function which was called is a stub only", ""),
+        mpv_error::Unsupported => ("Unspecified error.", ""),
+
+        mpv_error::Success => unreachable!("This is not an error. It's just here, to ensure that the 0 case marks an success'"),
+        _ => unreachable!("Mpv seems to have changed it's constants."),
+    }
+}
diff --git a/pkgs/by-name/yt/yt/libmpv2/src/mpv/events.rs b/pkgs/by-name/yt/yt/libmpv2/src/mpv/events.rs
new file mode 100644
index 00000000..b6513890
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/src/mpv/events.rs
@@ -0,0 +1,373 @@
+use crate::mpv_node::sys_node::SysMpvNode;
+use crate::{mpv::mpv_err, *};
+
+use std::ffi::{c_void, CString};
+use std::os::raw as ctype;
+use std::ptr::NonNull;
+use std::slice;
+
+/// An `Event`'s ID.
+pub use libmpv2_sys::mpv_event_id as EventId;
+
+use self::mpv_node::MpvNode;
+pub mod mpv_event_id {
+    pub use libmpv2_sys::mpv_event_id_MPV_EVENT_AUDIO_RECONFIG as AudioReconfig;
+    pub use libmpv2_sys::mpv_event_id_MPV_EVENT_CLIENT_MESSAGE as ClientMessage;
+    pub use libmpv2_sys::mpv_event_id_MPV_EVENT_COMMAND_REPLY as CommandReply;
+    pub use libmpv2_sys::mpv_event_id_MPV_EVENT_END_FILE as EndFile;
+    pub use libmpv2_sys::mpv_event_id_MPV_EVENT_FILE_LOADED as FileLoaded;
+    pub use libmpv2_sys::mpv_event_id_MPV_EVENT_GET_PROPERTY_REPLY as GetPropertyReply;
+    pub use libmpv2_sys::mpv_event_id_MPV_EVENT_HOOK as Hook;
+    pub use libmpv2_sys::mpv_event_id_MPV_EVENT_LOG_MESSAGE as LogMessage;
+    pub use libmpv2_sys::mpv_event_id_MPV_EVENT_NONE as None;
+    pub use libmpv2_sys::mpv_event_id_MPV_EVENT_PLAYBACK_RESTART as PlaybackRestart;
+    pub use libmpv2_sys::mpv_event_id_MPV_EVENT_PROPERTY_CHANGE as PropertyChange;
+    pub use libmpv2_sys::mpv_event_id_MPV_EVENT_QUEUE_OVERFLOW as QueueOverflow;
+    pub use libmpv2_sys::mpv_event_id_MPV_EVENT_SEEK as Seek;
+    pub use libmpv2_sys::mpv_event_id_MPV_EVENT_SET_PROPERTY_REPLY as SetPropertyReply;
+    pub use libmpv2_sys::mpv_event_id_MPV_EVENT_SHUTDOWN as Shutdown;
+    pub use libmpv2_sys::mpv_event_id_MPV_EVENT_START_FILE as StartFile;
+    pub use libmpv2_sys::mpv_event_id_MPV_EVENT_TICK as Tick;
+    pub use libmpv2_sys::mpv_event_id_MPV_EVENT_VIDEO_RECONFIG as VideoReconfig;
+}
+
+#[derive(Debug)]
+/// Data that is returned by both `GetPropertyReply` and `PropertyChange` events.
+pub enum PropertyData<'a> {
+    Str(&'a str),
+    OsdStr(&'a str),
+    Flag(bool),
+    Int64(i64),
+    Double(ctype::c_double),
+    Node(MpvNode),
+}
+
+impl<'a> PropertyData<'a> {
+    // SAFETY: meant to extract the data from an event property. See `mpv_event_property` in
+    // `client.h`
+    unsafe fn from_raw(format: MpvFormat, ptr: *mut ctype::c_void) -> Result<PropertyData<'a>> {
+        assert!(!ptr.is_null());
+        match format {
+            mpv_format::Flag => Ok(PropertyData::Flag(*(ptr as *mut bool))),
+            mpv_format::String => {
+                let char_ptr = *(ptr as *mut *mut ctype::c_char);
+                Ok(PropertyData::Str(mpv_cstr_to_str!(char_ptr)?))
+            }
+            mpv_format::OsdString => {
+                let char_ptr = *(ptr as *mut *mut ctype::c_char);
+                Ok(PropertyData::OsdStr(mpv_cstr_to_str!(char_ptr)?))
+            }
+            mpv_format::Double => Ok(PropertyData::Double(*(ptr as *mut f64))),
+            mpv_format::Int64 => Ok(PropertyData::Int64(*(ptr as *mut i64))),
+            mpv_format::Node => {
+                let sys_node = *(ptr as *mut libmpv2_sys::mpv_node);
+                let node = SysMpvNode::new(sys_node, false);
+                return Ok(PropertyData::Node(node.value().unwrap()));
+            }
+            mpv_format::None => unreachable!(),
+            _ => unimplemented!(),
+        }
+    }
+}
+
+pub type PlaylistEntryId = i64;
+
+#[derive(Debug)]
+pub enum Event<'a> {
+    /// Received when the player is shutting down
+    Shutdown,
+    /// *Has not been tested*, received when explicitly asked to MPV
+    LogMessage {
+        prefix: &'a str,
+        level: &'a str,
+        text: &'a str,
+        log_level: LogLevel,
+    },
+    /// Received when using get_property_async
+    GetPropertyReply {
+        name: &'a str,
+        result: PropertyData<'a>,
+        reply_userdata: u64,
+    },
+    /// Received when using set_property_async
+    SetPropertyReply(u64),
+    /// Received when using command_async
+    CommandReply(u64),
+    /// Event received when a new file is playing
+    StartFile(PlaylistEntryId),
+    /// Event received when the file being played currently has stopped, for an error or not
+    EndFile(EndFileReason),
+    /// Event received when a file has been *loaded*, but has not been started
+    FileLoaded,
+    ClientMessage(Vec<&'a str>),
+    VideoReconfig,
+    AudioReconfig,
+    /// The player changed current position
+    Seek,
+    PlaybackRestart,
+    /// Received when used with observe_property
+    PropertyChange {
+        name: &'a str,
+        change: PropertyData<'a>,
+        reply_userdata: u64,
+    },
+    /// Received when the Event Queue is full
+    QueueOverflow,
+    /// A deprecated event
+    Deprecated(libmpv2_sys::mpv_event),
+}
+
+unsafe extern "C" fn wu_wrapper<F: Fn() + Send + 'static>(ctx: *mut c_void) {
+    if ctx.is_null() {
+        panic!("ctx for wakeup wrapper is NULL");
+    }
+
+    (*(ctx as *mut F))();
+}
+
+/// Context to listen to events.
+pub struct EventContext {
+    ctx: NonNull<libmpv2_sys::mpv_handle>,
+    wakeup_callback_cleanup: Option<Box<dyn FnOnce()>>,
+}
+
+unsafe impl Send for EventContext {}
+
+impl EventContext {
+    pub fn new(ctx: NonNull<libmpv2_sys::mpv_handle>) -> Self {
+        EventContext {
+            ctx,
+            wakeup_callback_cleanup: None,
+        }
+    }
+
+    /// Enable an event.
+    pub fn enable_event(&self, ev: events::EventId) -> Result<()> {
+        mpv_err((), unsafe {
+            libmpv2_sys::mpv_request_event(self.ctx.as_ptr(), ev, 1)
+        })
+    }
+
+    /// Enable all, except deprecated, events.
+    pub fn enable_all_events(&self) -> Result<()> {
+        for i in (2..9).chain(16..19).chain(20..23).chain(24..26) {
+            self.enable_event(i)?;
+        }
+        Ok(())
+    }
+
+    /// Disable an event.
+    pub fn disable_event(&self, ev: events::EventId) -> Result<()> {
+        mpv_err((), unsafe {
+            libmpv2_sys::mpv_request_event(self.ctx.as_ptr(), ev, 0)
+        })
+    }
+
+    /// Diable all deprecated events.
+    pub fn disable_deprecated_events(&self) -> Result<()> {
+        self.disable_event(libmpv2_sys::mpv_event_id_MPV_EVENT_IDLE)?;
+        Ok(())
+    }
+
+    /// Diable all events.
+    pub fn disable_all_events(&self) -> Result<()> {
+        for i in 2..26 {
+            self.disable_event(i as _)?;
+        }
+        Ok(())
+    }
+
+    /// Observe `name` property for changes. `id` can be used to unobserve this (or many) properties
+    /// again.
+    pub fn observe_property(&self, name: &str, format: Format, id: u64) -> Result<()> {
+        let name = CString::new(name)?;
+        mpv_err((), unsafe {
+            libmpv2_sys::mpv_observe_property(
+                self.ctx.as_ptr(),
+                id,
+                name.as_ptr(),
+                format.as_mpv_format() as _,
+            )
+        })
+    }
+
+    /// Unobserve any property associated with `id`.
+    pub fn unobserve_property(&self, id: u64) -> Result<()> {
+        mpv_err((), unsafe {
+            libmpv2_sys::mpv_unobserve_property(self.ctx.as_ptr(), id)
+        })
+    }
+
+    /// Wait for `timeout` seconds for an `Event`. Passing `0` as `timeout` will poll.
+    /// For more information, as always, see the mpv-sys docs of `mpv_wait_event`.
+    ///
+    /// This function is intended to be called repeatedly in a wait-event loop.
+    ///
+    /// Returns `Some(Err(...))` if there was invalid utf-8, or if either an
+    /// `MPV_EVENT_GET_PROPERTY_REPLY`, `MPV_EVENT_SET_PROPERTY_REPLY`, `MPV_EVENT_COMMAND_REPLY`,
+    /// or `MPV_EVENT_PROPERTY_CHANGE` event failed, or if `MPV_EVENT_END_FILE` reported an error.
+    pub fn wait_event(&mut self, timeout: f64) -> Option<Result<Event>> {
+        let event = unsafe { *libmpv2_sys::mpv_wait_event(self.ctx.as_ptr(), timeout) };
+
+        // debug!("Got an event from mpv: {:#?}", event);
+
+        if event.event_id != mpv_event_id::None {
+            if let Err(e) = mpv_err((), event.error) {
+                return Some(Err(e));
+            }
+        }
+
+        match event.event_id {
+            mpv_event_id::None => None,
+            mpv_event_id::Shutdown => Some(Ok(Event::Shutdown)),
+            mpv_event_id::LogMessage => {
+                let log_message =
+                    unsafe { *(event.data as *mut libmpv2_sys::mpv_event_log_message) };
+
+                let prefix = unsafe { mpv_cstr_to_str!(log_message.prefix) };
+                Some(prefix.and_then(|prefix| {
+                    Ok(Event::LogMessage {
+                        prefix,
+                        level: unsafe { mpv_cstr_to_str!(log_message.level)? },
+                        text: unsafe { mpv_cstr_to_str!(log_message.text)? },
+                        log_level: log_message.log_level,
+                    })
+                }))
+            }
+            mpv_event_id::GetPropertyReply => {
+                let property = unsafe { *(event.data as *mut libmpv2_sys::mpv_event_property) };
+
+                let name = unsafe { mpv_cstr_to_str!(property.name) };
+                Some(name.and_then(|name| {
+                    // SAFETY: safe because we are passing format + data from an mpv_event_property
+                    let result = unsafe { PropertyData::from_raw(property.format, property.data) }?;
+
+                    Ok(Event::GetPropertyReply {
+                        name,
+                        result,
+                        reply_userdata: event.reply_userdata,
+                    })
+                }))
+            }
+            mpv_event_id::SetPropertyReply => Some(mpv_err(
+                Event::SetPropertyReply(event.reply_userdata),
+                event.error,
+            )),
+            mpv_event_id::CommandReply => Some(mpv_err(
+                Event::CommandReply(event.reply_userdata),
+                event.error,
+            )),
+            mpv_event_id::StartFile => {
+                let playlist_id = unsafe { *(event.data as *mut i64) };
+
+                Some(Ok(Event::StartFile(playlist_id)))
+            }
+            mpv_event_id::EndFile => {
+                let end_file = unsafe { *(event.data as *mut libmpv2_sys::mpv_event_end_file) };
+
+                // debug!("Got an end file event, with error code '{:#?}'", end_file);
+
+                if let Err(e) = mpv_err((), end_file.error) {
+                    Some(Err(e))
+                } else {
+                    Some(Ok(Event::EndFile(end_file.reason as _)))
+                }
+            }
+            mpv_event_id::FileLoaded => Some(Ok(Event::FileLoaded)),
+            mpv_event_id::ClientMessage => {
+                let client_message =
+                    unsafe { *(event.data as *mut libmpv2_sys::mpv_event_client_message) };
+                let messages = unsafe {
+                    slice::from_raw_parts_mut(client_message.args, client_message.num_args as _)
+                };
+                Some(Ok(Event::ClientMessage(
+                    messages
+                        .iter()
+                        .map(|msg| unsafe { mpv_cstr_to_str!(*msg) })
+                        .collect::<Result<Vec<_>>>()
+                        .unwrap(),
+                )))
+            }
+            mpv_event_id::VideoReconfig => Some(Ok(Event::VideoReconfig)),
+            mpv_event_id::AudioReconfig => Some(Ok(Event::AudioReconfig)),
+            mpv_event_id::Seek => Some(Ok(Event::Seek)),
+            mpv_event_id::PlaybackRestart => Some(Ok(Event::PlaybackRestart)),
+            mpv_event_id::PropertyChange => {
+                let property = unsafe { *(event.data as *mut libmpv2_sys::mpv_event_property) };
+
+                // This happens if the property is not available. For example,
+                // if you reached EndFile while observing a property.
+                if property.format == mpv_format::None {
+                    None
+                } else {
+                    let name = unsafe { mpv_cstr_to_str!(property.name) };
+                    Some(name.and_then(|name| {
+                        // SAFETY: safe because we are passing format + data from an mpv_event_property
+                        let change =
+                            unsafe { PropertyData::from_raw(property.format, property.data) }?;
+
+                        Ok(Event::PropertyChange {
+                            name,
+                            change,
+                            reply_userdata: event.reply_userdata,
+                        })
+                    }))
+                }
+            }
+            mpv_event_id::QueueOverflow => Some(Ok(Event::QueueOverflow)),
+            _ => Some(Ok(Event::Deprecated(event))),
+        }
+    }
+
+    /// Set a custom function that should be called when there are new events. Use this if
+    /// blocking in [wait_event](#method.wait_event) to wait for new events is not feasible.
+    ///
+    /// Keep in mind that the callback will be called from foreign threads. You must not make
+    /// any assumptions of the environment, and you must return as soon as possible (i.e. no
+    /// long blocking waits). Exiting the callback through any other means than a normal return
+    /// is forbidden (no throwing exceptions, no `longjmp()` calls). You must not change any
+    /// local thread state (such as the C floating point environment).
+    ///
+    /// You are not allowed to call any client API functions inside of the callback. In
+    /// particular, you should not do any processing in the callback, but wake up another
+    /// thread that does all the work. The callback is meant strictly for notification only,
+    /// and is called from arbitrary core parts of the player, that make no considerations for
+    /// reentrant API use or allowing the callee to spend a lot of time doing other things.
+    /// Keep in mind that it’s also possible that the callback is called from a thread while a
+    /// mpv API function is called (i.e. it can be reentrant).
+    ///
+    /// In general, the client API expects you to call [wait_event](#method.wait_event) to receive
+    /// notifications, and the wakeup callback is merely a helper utility to make this easier in
+    /// certain situations. Note that it’s possible that there’s only one wakeup callback
+    /// invocation for multiple events. You should call [wait_event](#method.wait_event) with no timeout until
+    /// `None` is returned, at which point the event queue is empty.
+    ///
+    /// If you actually want to do processing in a callback, spawn a thread that does nothing but
+    /// call [wait_event](#method.wait_event) in a loop and dispatches the result to a callback.
+    ///
+    /// Only one wakeup callback can be set.
+    pub fn set_wakeup_callback<F: Fn() + Send + 'static>(&mut self, callback: F) {
+        if let Some(wakeup_callback_cleanup) = self.wakeup_callback_cleanup.take() {
+            wakeup_callback_cleanup();
+        }
+        let raw_callback = Box::into_raw(Box::new(callback));
+        self.wakeup_callback_cleanup = Some(Box::new(move || unsafe {
+            drop(Box::from_raw(raw_callback));
+        }) as Box<dyn FnOnce()>);
+        unsafe {
+            libmpv2_sys::mpv_set_wakeup_callback(
+                self.ctx.as_ptr(),
+                Some(wu_wrapper::<F>),
+                raw_callback as *mut c_void,
+            );
+        }
+    }
+}
+
+impl Drop for EventContext {
+    fn drop(&mut self) {
+        if let Some(wakeup_callback_cleanup) = self.wakeup_callback_cleanup.take() {
+            wakeup_callback_cleanup();
+        }
+    }
+}
diff --git a/pkgs/by-name/yt/yt/libmpv2/src/mpv/protocol.rs b/pkgs/by-name/yt/yt/libmpv2/src/mpv/protocol.rs
new file mode 100644
index 00000000..9ad3b3d9
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/src/mpv/protocol.rs
@@ -0,0 +1,251 @@
+use super::*;
+
+use std::alloc::{self, Layout};
+use std::marker::PhantomData;
+use std::mem;
+use std::os::raw as ctype;
+use std::panic;
+use std::panic::RefUnwindSafe;
+use std::slice;
+use std::sync::{atomic::Ordering, Mutex};
+
+impl Mpv {
+    /// Create a context with which custom protocols can be registered.
+    ///
+    /// # Panics
+    /// Panics if a context already exists
+    pub fn create_protocol_context<T, U>(&self) -> ProtocolContext<T, U>
+    where
+        T: RefUnwindSafe,
+        U: RefUnwindSafe,
+    {
+        match self.protocols_guard.compare_exchange(
+            false,
+            true,
+            Ordering::AcqRel,
+            Ordering::Acquire,
+        ) {
+            Ok(_) => ProtocolContext::new(self.ctx, PhantomData::<&Self>),
+            Err(_) => panic!("A protocol context already exists"),
+        }
+    }
+}
+
+/// Return a persistent `T` that is passed to all other `Stream*` functions, panic on errors.
+pub type StreamOpen<T, U> = fn(&mut U, &str) -> T;
+/// Do any necessary cleanup.
+pub type StreamClose<T> = fn(Box<T>);
+/// Seek to the given offset. Return the new offset, or either `MpvError::Generic` if seeking
+/// failed or panic.
+pub type StreamSeek<T> = fn(&mut T, i64) -> i64;
+/// Target buffer with fixed capacity.
+/// Return either the number of read bytes, `0` on EOF, or either `-1` or panic on error.
+pub type StreamRead<T> = fn(&mut T, &mut [ctype::c_char]) -> i64;
+/// Return the total size of the stream in bytes. Panic on error.
+pub type StreamSize<T> = fn(&mut T) -> i64;
+
+unsafe extern "C" fn open_wrapper<T, U>(
+    user_data: *mut ctype::c_void,
+    uri: *mut ctype::c_char,
+    info: *mut libmpv2_sys::mpv_stream_cb_info,
+) -> ctype::c_int
+where
+    T: RefUnwindSafe,
+    U: RefUnwindSafe,
+{
+    let data = user_data as *mut ProtocolData<T, U>;
+
+    (*info).cookie = user_data;
+    (*info).read_fn = Some(read_wrapper::<T, U>);
+    (*info).seek_fn = Some(seek_wrapper::<T, U>);
+    (*info).size_fn = Some(size_wrapper::<T, U>);
+    (*info).close_fn = Some(close_wrapper::<T, U>);
+
+    let ret = panic::catch_unwind(|| {
+        let uri = mpv_cstr_to_str!(uri as *const _).unwrap();
+        ptr::write(
+            (*data).cookie,
+            ((*data).open_fn)(&mut (*data).user_data, uri),
+        );
+    });
+
+    if ret.is_ok() {
+        0
+    } else {
+        mpv_error::Generic as _
+    }
+}
+
+unsafe extern "C" fn read_wrapper<T, U>(
+    cookie: *mut ctype::c_void,
+    buf: *mut ctype::c_char,
+    nbytes: u64,
+) -> i64
+where
+    T: RefUnwindSafe,
+    U: RefUnwindSafe,
+{
+    let data = cookie as *mut ProtocolData<T, U>;
+
+    let ret = panic::catch_unwind(|| {
+        let slice = slice::from_raw_parts_mut(buf, nbytes as _);
+        ((*data).read_fn)(&mut *(*data).cookie, slice)
+    });
+    if let Ok(ret) = ret {
+        ret
+    } else {
+        -1
+    }
+}
+
+unsafe extern "C" fn seek_wrapper<T, U>(cookie: *mut ctype::c_void, offset: i64) -> i64
+where
+    T: RefUnwindSafe,
+    U: RefUnwindSafe,
+{
+    let data = cookie as *mut ProtocolData<T, U>;
+
+    if (*data).seek_fn.is_none() {
+        return mpv_error::Unsupported as _;
+    }
+
+    let ret =
+        panic::catch_unwind(|| (*(*data).seek_fn.as_ref().unwrap())(&mut *(*data).cookie, offset));
+    if let Ok(ret) = ret {
+        ret
+    } else {
+        mpv_error::Generic as _
+    }
+}
+
+unsafe extern "C" fn size_wrapper<T, U>(cookie: *mut ctype::c_void) -> i64
+where
+    T: RefUnwindSafe,
+    U: RefUnwindSafe,
+{
+    let data = cookie as *mut ProtocolData<T, U>;
+
+    if (*data).size_fn.is_none() {
+        return mpv_error::Unsupported as _;
+    }
+
+    let ret = panic::catch_unwind(|| (*(*data).size_fn.as_ref().unwrap())(&mut *(*data).cookie));
+    if let Ok(ret) = ret {
+        ret
+    } else {
+        mpv_error::Unsupported as _
+    }
+}
+
+#[allow(unused_must_use)]
+unsafe extern "C" fn close_wrapper<T, U>(cookie: *mut ctype::c_void)
+where
+    T: RefUnwindSafe,
+    U: RefUnwindSafe,
+{
+    let data = Box::from_raw(cookie as *mut ProtocolData<T, U>);
+
+    panic::catch_unwind(|| ((*data).close_fn)(Box::from_raw((*data).cookie)));
+}
+
+struct ProtocolData<T, U> {
+    cookie: *mut T,
+    user_data: U,
+
+    open_fn: StreamOpen<T, U>,
+    close_fn: StreamClose<T>,
+    read_fn: StreamRead<T>,
+    seek_fn: Option<StreamSeek<T>>,
+    size_fn: Option<StreamSize<T>>,
+}
+
+/// This context holds state relevant to custom protocols.
+/// It is created by calling `Mpv::create_protocol_context`.
+pub struct ProtocolContext<'parent, T: RefUnwindSafe, U: RefUnwindSafe> {
+    ctx: NonNull<libmpv2_sys::mpv_handle>,
+    protocols: Mutex<Vec<Protocol<T, U>>>,
+    _does_not_outlive: PhantomData<&'parent Mpv>,
+}
+
+unsafe impl<'parent, T: RefUnwindSafe, U: RefUnwindSafe> Send for ProtocolContext<'parent, T, U> {}
+unsafe impl<'parent, T: RefUnwindSafe, U: RefUnwindSafe> Sync for ProtocolContext<'parent, T, U> {}
+
+impl<'parent, T: RefUnwindSafe, U: RefUnwindSafe> ProtocolContext<'parent, T, U> {
+    fn new(
+        ctx: NonNull<libmpv2_sys::mpv_handle>,
+        marker: PhantomData<&'parent Mpv>,
+    ) -> ProtocolContext<'parent, T, U> {
+        ProtocolContext {
+            ctx,
+            protocols: Mutex::new(Vec::new()),
+            _does_not_outlive: marker,
+        }
+    }
+
+    /// Register a custom `Protocol`. Once a protocol has been registered, it lives as long as
+    /// `Mpv`.
+    ///
+    /// Returns `Error::Mpv(MpvError::InvalidParameter)` if a protocol with the same name has
+    /// already been registered.
+    pub fn register(&self, protocol: Protocol<T, U>) -> Result<()> {
+        let mut protocols = self.protocols.lock().unwrap();
+        protocol.register(self.ctx.as_ptr())?;
+        protocols.push(protocol);
+        Ok(())
+    }
+}
+
+/// `Protocol` holds all state used by a custom protocol.
+pub struct Protocol<T: Sized + RefUnwindSafe, U: RefUnwindSafe> {
+    name: String,
+    data: *mut ProtocolData<T, U>,
+}
+
+impl<T: RefUnwindSafe, U: RefUnwindSafe> Protocol<T, U> {
+    /// `name` is the prefix of the protocol, e.g. `name://path`.
+    ///
+    /// `user_data` is data that will be passed to `open_fn`.
+    ///
+    /// # Safety
+    /// Do not call libmpv functions in any supplied function.
+    /// All panics of the provided functions are catched and can be used as generic error returns.
+    pub unsafe fn new(
+        name: String,
+        user_data: U,
+        open_fn: StreamOpen<T, U>,
+        close_fn: StreamClose<T>,
+        read_fn: StreamRead<T>,
+        seek_fn: Option<StreamSeek<T>>,
+        size_fn: Option<StreamSize<T>>,
+    ) -> Protocol<T, U> {
+        let c_layout = Layout::from_size_align(mem::size_of::<T>(), mem::align_of::<T>()).unwrap();
+        let cookie = alloc::alloc(c_layout) as *mut T;
+        let data = Box::into_raw(Box::new(ProtocolData {
+            cookie,
+            user_data,
+
+            open_fn,
+            close_fn,
+            read_fn,
+            seek_fn,
+            size_fn,
+        }));
+
+        Protocol { name, data }
+    }
+
+    fn register(&self, ctx: *mut libmpv2_sys::mpv_handle) -> Result<()> {
+        let name = CString::new(&self.name[..])?;
+        unsafe {
+            mpv_err(
+                (),
+                libmpv2_sys::mpv_stream_cb_add_ro(
+                    ctx,
+                    name.as_ptr(),
+                    self.data as *mut _,
+                    Some(open_wrapper::<T, U>),
+                ),
+            )
+        }
+    }
+}
diff --git a/pkgs/by-name/yt/yt/libmpv2/src/mpv/render.rs b/pkgs/by-name/yt/yt/libmpv2/src/mpv/render.rs
new file mode 100644
index 00000000..4c51c17c
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/src/mpv/render.rs
@@ -0,0 +1,396 @@
+use crate::{mpv::mpv_err, Error, Result};
+use std::collections::HashMap;
+use std::ffi::{c_void, CStr};
+use std::os::raw::c_int;
+use std::ptr;
+
+type DeleterFn = unsafe fn(*mut c_void);
+
+pub struct RenderContext {
+    ctx: *mut libmpv2_sys::mpv_render_context,
+    update_callback_cleanup: Option<Box<dyn FnOnce()>>,
+}
+
+/// For initializing the mpv OpenGL state via RenderParam::OpenGLInitParams
+pub struct OpenGLInitParams<GLContext> {
+    /// This retrieves OpenGL function pointers, and will use them in subsequent
+    /// operation.
+    /// Usually, you can simply call the GL context APIs from this callback (e.g.
+    /// glXGetProcAddressARB or wglGetProcAddress), but some APIs do not always
+    /// return pointers for all standard functions (even if present); in this
+    /// case you have to compensate by looking up these functions yourself when
+    /// libmpv wants to resolve them through this callback.
+    /// libmpv will not normally attempt to resolve GL functions on its own, nor
+    /// does it link to GL libraries directly.
+    pub get_proc_address: fn(ctx: &GLContext, name: &str) -> *mut c_void,
+
+    /// Value passed as ctx parameter to get_proc_address().
+    pub ctx: GLContext,
+}
+
+/// For RenderParam::FBO
+pub struct FBO {
+    pub fbo: i32,
+    pub width: i32,
+    pub height: i32,
+}
+
+#[repr(u32)]
+#[derive(Clone)]
+pub enum RenderFrameInfoFlag {
+    Present = libmpv2_sys::mpv_render_frame_info_flag_MPV_RENDER_FRAME_INFO_PRESENT,
+    Redraw = libmpv2_sys::mpv_render_frame_info_flag_MPV_RENDER_FRAME_INFO_REDRAW,
+    Repeat = libmpv2_sys::mpv_render_frame_info_flag_MPV_RENDER_FRAME_INFO_REPEAT,
+    BlockVSync = libmpv2_sys::mpv_render_frame_info_flag_MPV_RENDER_FRAME_INFO_BLOCK_VSYNC,
+}
+
+impl From<u64> for RenderFrameInfoFlag {
+    // mpv_render_frame_info_flag is u32, but mpv_render_frame_info.flags is u64 o\
+    fn from(val: u64) -> Self {
+        let val = val as u32;
+        match val {
+            libmpv2_sys::mpv_render_frame_info_flag_MPV_RENDER_FRAME_INFO_PRESENT => {
+                RenderFrameInfoFlag::Present
+            }
+            libmpv2_sys::mpv_render_frame_info_flag_MPV_RENDER_FRAME_INFO_REDRAW => {
+                RenderFrameInfoFlag::Redraw
+            }
+            libmpv2_sys::mpv_render_frame_info_flag_MPV_RENDER_FRAME_INFO_REPEAT => {
+                RenderFrameInfoFlag::Repeat
+            }
+            libmpv2_sys::mpv_render_frame_info_flag_MPV_RENDER_FRAME_INFO_BLOCK_VSYNC => {
+                RenderFrameInfoFlag::BlockVSync
+            }
+            _ => panic!("Tried converting invalid value to RenderFrameInfoFlag"),
+        }
+    }
+}
+
+#[derive(Clone)]
+pub struct RenderFrameInfo {
+    pub flags: RenderFrameInfoFlag,
+    pub target_time: i64,
+}
+
+pub enum RenderParamApiType {
+    OpenGl,
+}
+
+pub enum RenderParam<GLContext> {
+    Invalid,
+    ApiType(RenderParamApiType),
+    InitParams(OpenGLInitParams<GLContext>),
+    FBO(FBO),
+    FlipY(bool),
+    Depth(i32),
+    ICCProfile(Vec<u8>),
+    AmbientLight(i32),
+    X11Display(*const c_void),
+    WaylandDisplay(*const c_void),
+    AdvancedControl(bool),
+    NextFrameInfo(RenderFrameInfo),
+    BlockForTargetTime(bool),
+    SkipRendering(bool),
+}
+
+impl<C> From<&RenderParam<C>> for u32 {
+    fn from(val: &RenderParam<C>) -> Self {
+        match val {
+            RenderParam::Invalid => 0,
+            RenderParam::ApiType(_) => 1,
+            RenderParam::InitParams(_) => 2,
+            RenderParam::FBO(_) => 3,
+            RenderParam::FlipY(_) => 4,
+            RenderParam::Depth(_) => 5,
+            RenderParam::ICCProfile(_) => 6,
+            RenderParam::AmbientLight(_) => 7,
+            RenderParam::X11Display(_) => 8,
+            RenderParam::WaylandDisplay(_) => 9,
+            RenderParam::AdvancedControl(_) => 10,
+            RenderParam::NextFrameInfo(_) => 11,
+            RenderParam::BlockForTargetTime(_) => 12,
+            RenderParam::SkipRendering(_) => 13,
+        }
+    }
+}
+
+unsafe extern "C" fn gpa_wrapper<GLContext>(ctx: *mut c_void, name: *const i8) -> *mut c_void {
+    if ctx.is_null() {
+        panic!("ctx for get_proc_address wrapper is NULL");
+    }
+
+    let params: *mut OpenGLInitParams<GLContext> = ctx as _;
+    let params = &*params;
+    (params.get_proc_address)(
+        &params.ctx,
+        CStr::from_ptr(name)
+            .to_str()
+            .expect("Could not convert function name to str"),
+    )
+}
+
+unsafe extern "C" fn ru_wrapper<F: Fn() + Send + 'static>(ctx: *mut c_void) {
+    if ctx.is_null() {
+        panic!("ctx for render_update wrapper is NULL");
+    }
+
+    (*(ctx as *mut F))();
+}
+
+impl<C> From<OpenGLInitParams<C>> for libmpv2_sys::mpv_opengl_init_params {
+    fn from(val: OpenGLInitParams<C>) -> Self {
+        Self {
+            get_proc_address: Some(gpa_wrapper::<OpenGLInitParams<C>>),
+            get_proc_address_ctx: Box::into_raw(Box::new(val)) as *mut c_void,
+        }
+    }
+}
+
+impl<C> From<RenderParam<C>> for libmpv2_sys::mpv_render_param {
+    fn from(val: RenderParam<C>) -> Self {
+        let type_ = u32::from(&val);
+        let data = match val {
+            RenderParam::Invalid => ptr::null_mut(),
+            RenderParam::ApiType(api_type) => match api_type {
+                RenderParamApiType::OpenGl => {
+                    libmpv2_sys::MPV_RENDER_API_TYPE_OPENGL.as_ptr() as *mut c_void
+                }
+            },
+            RenderParam::InitParams(params) => {
+                Box::into_raw(Box::new(libmpv2_sys::mpv_opengl_init_params::from(params)))
+                    as *mut c_void
+            }
+            RenderParam::FBO(fbo) => Box::into_raw(Box::new(fbo)) as *mut c_void,
+            RenderParam::FlipY(flip) => Box::into_raw(Box::new(flip as c_int)) as *mut c_void,
+            RenderParam::Depth(depth) => Box::into_raw(Box::new(depth)) as *mut c_void,
+            RenderParam::ICCProfile(bytes) => {
+                Box::into_raw(bytes.into_boxed_slice()) as *mut c_void
+            }
+            RenderParam::AmbientLight(lux) => Box::into_raw(Box::new(lux)) as *mut c_void,
+            RenderParam::X11Display(ptr) => ptr as *mut _,
+            RenderParam::WaylandDisplay(ptr) => ptr as *mut _,
+            RenderParam::AdvancedControl(adv_ctrl) => {
+                Box::into_raw(Box::new(adv_ctrl as c_int)) as *mut c_void
+            }
+            RenderParam::NextFrameInfo(frame_info) => {
+                Box::into_raw(Box::new(frame_info)) as *mut c_void
+            }
+            RenderParam::BlockForTargetTime(block) => {
+                Box::into_raw(Box::new(block as c_int)) as *mut c_void
+            }
+            RenderParam::SkipRendering(skip_rendering) => {
+                Box::into_raw(Box::new(skip_rendering as c_int)) as *mut c_void
+            }
+        };
+        Self { type_, data }
+    }
+}
+
+unsafe fn free_void_data<T>(ptr: *mut c_void) {
+    drop(Box::<T>::from_raw(ptr as *mut T));
+}
+
+unsafe fn free_init_params<C>(ptr: *mut c_void) {
+    let params = Box::from_raw(ptr as *mut libmpv2_sys::mpv_opengl_init_params);
+    drop(Box::from_raw(
+        params.get_proc_address_ctx as *mut OpenGLInitParams<C>,
+    ));
+}
+
+impl RenderContext {
+    pub fn new<C>(
+        mpv: &mut libmpv2_sys::mpv_handle,
+        params: impl IntoIterator<Item = RenderParam<C>>,
+    ) -> Result<Self> {
+        let params: Vec<_> = params.into_iter().collect();
+        let mut raw_params: Vec<libmpv2_sys::mpv_render_param> = Vec::new();
+        raw_params.reserve(params.len() + 1);
+        let mut raw_ptrs: HashMap<*const c_void, DeleterFn> = HashMap::new();
+
+        for p in params {
+            // The render params are type-erased after they are passed to mpv. This is where we last
+            // know their real types, so we keep a deleter here.
+            let deleter: Option<DeleterFn> = match p {
+                RenderParam::InitParams(_) => Some(free_init_params::<C>),
+                RenderParam::FBO(_) => Some(free_void_data::<FBO>),
+                RenderParam::FlipY(_) => Some(free_void_data::<i32>),
+                RenderParam::Depth(_) => Some(free_void_data::<i32>),
+                RenderParam::ICCProfile(_) => Some(free_void_data::<Box<[u8]>>),
+                RenderParam::AmbientLight(_) => Some(free_void_data::<i32>),
+                RenderParam::NextFrameInfo(_) => Some(free_void_data::<RenderFrameInfo>),
+                _ => None,
+            };
+            let raw_param: libmpv2_sys::mpv_render_param = p.into();
+            if let Some(deleter) = deleter {
+                raw_ptrs.insert(raw_param.data, deleter);
+            }
+
+            raw_params.push(raw_param);
+        }
+        // the raw array must end with type = 0
+        raw_params.push(libmpv2_sys::mpv_render_param {
+            type_: 0,
+            data: ptr::null_mut(),
+        });
+
+        unsafe {
+            let raw_array =
+                Box::into_raw(raw_params.into_boxed_slice()) as *mut libmpv2_sys::mpv_render_param;
+            let ctx = Box::into_raw(Box::new(std::ptr::null_mut() as _));
+            let err = libmpv2_sys::mpv_render_context_create(ctx, &mut *mpv, raw_array);
+            drop(Box::from_raw(raw_array));
+            for (ptr, deleter) in raw_ptrs.iter() {
+                (deleter)(*ptr as _);
+            }
+
+            mpv_err(
+                Self {
+                    ctx: *Box::from_raw(ctx),
+                    update_callback_cleanup: None,
+                },
+                err,
+            )
+        }
+    }
+
+    pub fn set_parameter<C>(&self, param: RenderParam<C>) -> Result<()> {
+        unsafe {
+            mpv_err(
+                (),
+                libmpv2_sys::mpv_render_context_set_parameter(
+                    self.ctx,
+                    libmpv2_sys::mpv_render_param::from(param),
+                ),
+            )
+        }
+    }
+
+    pub fn get_info<C>(&self, param: RenderParam<C>) -> Result<RenderParam<C>> {
+        let is_next_frame_info = matches!(param, RenderParam::NextFrameInfo(_));
+        let raw_param = libmpv2_sys::mpv_render_param::from(param);
+        let res = unsafe { libmpv2_sys::mpv_render_context_get_info(self.ctx, raw_param) };
+        if res == 0 {
+            if !is_next_frame_info {
+                panic!("I don't know how to handle this info type.");
+            }
+            let raw_frame_info = raw_param.data as *mut libmpv2_sys::mpv_render_frame_info;
+            unsafe {
+                let raw_frame_info = *raw_frame_info;
+                return Ok(RenderParam::NextFrameInfo(RenderFrameInfo {
+                    flags: raw_frame_info.flags.into(),
+                    target_time: raw_frame_info.target_time,
+                }));
+            }
+        }
+        Err(Error::Raw(res))
+    }
+
+    /// Render video.
+    ///
+    /// Typically renders the video to a target surface provided via `fbo`
+    /// (the details depend on the backend in use). Options like "panscan" are
+    /// applied to determine which part of the video should be visible and how the
+    /// video should be scaled. You can change these options at runtime by using the
+    /// mpv property API.
+    ///
+    /// The renderer will reconfigure itself every time the target surface
+    /// configuration (such as size) is changed.
+    ///
+    /// This function implicitly pulls a video frame from the internal queue and
+    /// renders it. If no new frame is available, the previous frame is redrawn.
+    /// The update callback set with [set_update_callback](Self::set_update_callback)
+    /// notifies you when a new frame was added. The details potentially depend on
+    /// the backends and the provided parameters.
+    ///
+    /// Generally, libmpv will invoke your update callback some time before the video
+    /// frame should be shown, and then lets this function block until the supposed
+    /// display time. This will limit your rendering to video FPS. You can prevent
+    /// this by setting the "video-timing-offset" global option to 0. (This applies
+    /// only to "audio" video sync mode.)
+    ///
+    /// # Arguments
+    ///
+    /// * `fbo` - A framebuffer object to render to. In OpenGL, 0 is the current backbuffer
+    /// * `width` - The width of the framebuffer in pixels. This is used for scaling the
+    ///             video properly.
+    /// * `height` - The height of the framebuffer in pixels. This is used for scaling the
+    ///              video properly.
+    /// * `flip` - Whether to draw the image upside down. This is needed for OpenGL because
+    ///            it uses a coordinate system with positive Y up, but videos use positive
+    ///            Y down.
+    pub fn render<GLContext>(&self, fbo: i32, width: i32, height: i32, flip: bool) -> Result<()> {
+        let mut raw_params: Vec<libmpv2_sys::mpv_render_param> = Vec::with_capacity(3);
+        let mut raw_ptrs: HashMap<*const c_void, DeleterFn> = HashMap::new();
+
+        let raw_param: libmpv2_sys::mpv_render_param =
+            RenderParam::<GLContext>::FBO(FBO { fbo, width, height }).into();
+        raw_ptrs.insert(raw_param.data, free_void_data::<FBO>);
+        raw_params.push(raw_param);
+        let raw_param: libmpv2_sys::mpv_render_param = RenderParam::<GLContext>::FlipY(flip).into();
+        raw_ptrs.insert(raw_param.data, free_void_data::<i32>);
+        raw_params.push(raw_param);
+        // the raw array must end with type = 0
+        raw_params.push(libmpv2_sys::mpv_render_param {
+            type_: 0,
+            data: ptr::null_mut(),
+        });
+
+        let raw_array =
+            Box::into_raw(raw_params.into_boxed_slice()) as *mut libmpv2_sys::mpv_render_param;
+
+        let ret = unsafe {
+            mpv_err(
+                (),
+                libmpv2_sys::mpv_render_context_render(self.ctx, raw_array),
+            )
+        };
+        unsafe {
+            drop(Box::from_raw(raw_array));
+        }
+
+        unsafe {
+            for (ptr, deleter) in raw_ptrs.iter() {
+                (deleter)(*ptr as _);
+            }
+        }
+
+        ret
+    }
+
+    /// Set the callback that notifies you when a new video frame is available, or if the video display
+    /// configuration somehow changed and requires a redraw. Similar to [EventContext::set_wakeup_callback](crate::events::EventContext::set_wakeup_callback), you
+    /// must not call any mpv API from the callback, and all the other listed restrictions apply (such
+    /// as not exiting the callback by throwing exceptions).
+    ///
+    /// This can be called from any thread, except from an update callback. In case of the OpenGL backend,
+    /// no OpenGL state or API is accessed.
+    ///
+    /// Calling this will raise an update callback immediately.
+    pub fn set_update_callback<F: Fn() + Send + 'static>(&mut self, callback: F) {
+        if let Some(update_callback_cleanup) = self.update_callback_cleanup.take() {
+            update_callback_cleanup();
+        }
+        let raw_callback = Box::into_raw(Box::new(callback));
+        self.update_callback_cleanup = Some(Box::new(move || unsafe {
+            drop(Box::from_raw(raw_callback));
+        }) as Box<dyn FnOnce()>);
+        unsafe {
+            libmpv2_sys::mpv_render_context_set_update_callback(
+                self.ctx,
+                Some(ru_wrapper::<F>),
+                raw_callback as *mut c_void,
+            );
+        }
+    }
+}
+
+impl Drop for RenderContext {
+    fn drop(&mut self) {
+        if let Some(update_callback_cleanup) = self.update_callback_cleanup.take() {
+            update_callback_cleanup();
+        }
+        unsafe {
+            libmpv2_sys::mpv_render_context_free(self.ctx);
+        }
+    }
+}
diff --git a/pkgs/by-name/yt/yt/libmpv2/src/tests.rs b/pkgs/by-name/yt/yt/libmpv2/src/tests.rs
new file mode 100644
index 00000000..5678257d
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/src/tests.rs
@@ -0,0 +1,212 @@
+use crate::events::{Event, EventContext, PropertyData};
+use crate::mpv_node::MpvNode;
+use crate::*;
+
+use std::collections::HashMap;
+use std::thread;
+use std::time::Duration;
+
+#[test]
+fn initializer() {
+    let mpv = Mpv::with_initializer(|init| {
+        init.set_property("osc", true)?;
+        init.set_property("input-default-bindings", true)?;
+        init.set_property("volume", 30)?;
+
+        Ok(())
+    })
+    .unwrap();
+
+    assert_eq!(true, mpv.get_property("osc").unwrap());
+    assert_eq!(true, mpv.get_property("input-default-bindings").unwrap());
+    assert_eq!(30i64, mpv.get_property("volume").unwrap());
+}
+
+#[test]
+fn properties() {
+    let mpv = Mpv::new().unwrap();
+    mpv.set_property("volume", 0).unwrap();
+    mpv.set_property("vo", "null").unwrap();
+    mpv.set_property("ytdl-format", "best[width<240]").unwrap();
+    mpv.set_property("sub-gauss", 0.6).unwrap();
+
+    assert_eq!(0i64, mpv.get_property("volume").unwrap());
+    let vo: MpvStr = mpv.get_property("vo").unwrap();
+    assert_eq!("null", &*vo);
+    assert_eq!(true, mpv.get_property("ytdl").unwrap());
+    let subg: f64 = mpv.get_property("sub-gauss").unwrap();
+    assert_eq!(
+        0.6,
+        f64::round(subg * f64::powi(10.0, 4)) / f64::powi(10.0, 4)
+    );
+    mpv.command(
+        "loadfile",
+        &["test-data/speech_12kbps_mb.wav", "append-play"],
+    )
+    .unwrap();
+    thread::sleep(Duration::from_millis(250));
+
+    let title: MpvStr = mpv.get_property("media-title").unwrap();
+    assert_eq!(&*title, "speech_12kbps_mb.wav");
+}
+
+macro_rules! assert_event_occurs {
+    ($ctx:ident, $timeout:literal, $( $expected:pat),+) => {
+        loop {
+            match $ctx.wait_event($timeout) {
+                $( Some($expected) )|+ => {
+                    break;
+                },
+                None => {
+                    continue
+                },
+                other => panic!("Event did not occur, got: {:?}", other),
+            }
+        }
+    }
+}
+
+#[test]
+fn events() {
+    let mpv = Mpv::new().unwrap();
+    let mut ev_ctx = EventContext::new(mpv.ctx);
+    ev_ctx.disable_deprecated_events().unwrap();
+
+    ev_ctx.observe_property("volume", Format::Int64, 0).unwrap();
+    ev_ctx
+        .observe_property("media-title", Format::String, 1)
+        .unwrap();
+
+    mpv.set_property("vo", "null").unwrap();
+
+    // speed up playback so test finishes faster
+    mpv.set_property("speed", 100).unwrap();
+
+    assert_event_occurs!(
+        ev_ctx,
+        3.,
+        Ok(Event::PropertyChange {
+            name: "volume",
+            change: PropertyData::Int64(100),
+            reply_userdata: 0,
+        })
+    );
+
+    mpv.set_property("volume", 0).unwrap();
+    assert_event_occurs!(
+        ev_ctx,
+        10.,
+        Ok(Event::PropertyChange {
+            name: "volume",
+            change: PropertyData::Int64(0),
+            reply_userdata: 0,
+        })
+    );
+    assert!(ev_ctx.wait_event(3.).is_none());
+    mpv.command("loadfile", &["test-data/jellyfish.mp4", "append-play"])
+        .unwrap();
+    assert_event_occurs!(ev_ctx, 10., Ok(Event::StartFile));
+    assert_event_occurs!(
+        ev_ctx,
+        10.,
+        Ok(Event::PropertyChange {
+            name: "media-title",
+            change: PropertyData::Str("jellyfish.mp4"),
+            reply_userdata: 1,
+        })
+    );
+    assert_event_occurs!(ev_ctx, 3., Ok(Event::AudioReconfig));
+    assert_event_occurs!(ev_ctx, 3., Ok(Event::AudioReconfig));
+    assert_event_occurs!(ev_ctx, 3., Ok(Event::FileLoaded));
+    assert_event_occurs!(ev_ctx, 3., Ok(Event::AudioReconfig));
+    assert_event_occurs!(ev_ctx, 3., Ok(Event::VideoReconfig));
+
+    mpv.command("loadfile", &["test-data/speech_12kbps_mb.wav", "replace"])
+        .unwrap();
+    assert_event_occurs!(ev_ctx, 3., Ok(Event::VideoReconfig));
+    assert_event_occurs!(ev_ctx, 3., Ok(Event::AudioReconfig));
+    assert_event_occurs!(ev_ctx, 3., Ok(Event::VideoReconfig));
+    assert_event_occurs!(ev_ctx, 3., Ok(Event::EndFile(mpv_end_file_reason::Stop)));
+    assert_event_occurs!(ev_ctx, 3., Ok(Event::StartFile));
+    assert_event_occurs!(
+        ev_ctx,
+        3.,
+        Ok(Event::PropertyChange {
+            name: "media-title",
+            change: PropertyData::Str("speech_12kbps_mb.wav"),
+            reply_userdata: 1,
+        })
+    );
+    assert_event_occurs!(ev_ctx, 3., Ok(Event::AudioReconfig));
+    assert_event_occurs!(ev_ctx, 3., Ok(Event::AudioReconfig));
+    assert_event_occurs!(ev_ctx, 3., Ok(Event::VideoReconfig));
+    assert_event_occurs!(ev_ctx, 3., Ok(Event::FileLoaded));
+    assert_event_occurs!(ev_ctx, 3., Ok(Event::AudioReconfig));
+    assert_event_occurs!(ev_ctx, 3., Ok(Event::AudioReconfig));
+    assert_event_occurs!(ev_ctx, 3., Ok(Event::PlaybackRestart));
+    assert_event_occurs!(ev_ctx, 3., Ok(Event::AudioReconfig));
+    assert_event_occurs!(ev_ctx, 10., Ok(Event::EndFile(mpv_end_file_reason::Eof)));
+    assert_event_occurs!(ev_ctx, 3., Ok(Event::AudioReconfig));
+    assert!(ev_ctx.wait_event(3.).is_none());
+}
+
+#[test]
+fn node_map() -> Result<()> {
+    let mpv = Mpv::new()?;
+
+    mpv.command(
+        "loadfile",
+        &["test-data/speech_12kbps_mb.wav", "append-play"],
+    )
+    .unwrap();
+
+    thread::sleep(Duration::from_millis(250));
+    let audio_params = mpv.get_property::<MpvNode>("audio-params")?;
+    let params = audio_params.map().unwrap().collect::<HashMap<_, _>>();
+
+    assert_eq!(params.len(), 5);
+
+    let format = params.get("format").unwrap();
+    assert_eq!(format, &MpvNode::String("s16".to_string()));
+
+    let samplerate = params.get("samplerate").unwrap();
+    assert_eq!(samplerate, &MpvNode::Int64(48_000));
+
+    let channels = params.get("channels").unwrap();
+    assert_eq!(channels, &MpvNode::String("mono".to_string()));
+
+    let hr_channels = params.get("hr-channels").unwrap();
+    assert_eq!(hr_channels, &MpvNode::String("mono".to_string()));
+
+    let channel_count = params.get("channel-count").unwrap();
+    assert_eq!(channel_count, &MpvNode::Int64(1));
+
+    Ok(())
+}
+
+#[test]
+fn node_array() -> Result<()> {
+    let mpv = Mpv::new()?;
+
+    mpv.command(
+        "loadfile",
+        &["test-data/speech_12kbps_mb.wav", "append-play"],
+    )
+    .unwrap();
+
+    thread::sleep(Duration::from_millis(250));
+    let playlist = mpv.get_property::<MpvNode>("playlist")?;
+    let items = playlist.array().unwrap().collect::<Vec<_>>();
+
+    assert_eq!(items.len(), 1);
+    let track = items[0].clone().map().unwrap().collect::<HashMap<_, _>>();
+
+    let filename = track.get("filename").unwrap();
+
+    assert_eq!(
+        filename,
+        &MpvNode::String("test-data/speech_12kbps_mb.wav".to_string())
+    );
+
+    Ok(())
+}
diff --git a/pkgs/by-name/yt/yt/libmpv2/update.sh b/pkgs/by-name/yt/yt/libmpv2/update.sh
new file mode 100755
index 00000000..7d517e8b
--- /dev/null
+++ b/pkgs/by-name/yt/yt/libmpv2/update.sh
@@ -0,0 +1,4 @@
+#!/usr/bin/env sh
+
+[ "$1" = "upgrade" ] && cargo upgrade
+cargo update
diff --git a/pkgs/by-name/yt/yt/scripts/mkdb.sh b/pkgs/by-name/yt/yt/scripts/mkdb.sh
new file mode 100755
index 00000000..307e4459
--- /dev/null
+++ b/pkgs/by-name/yt/yt/scripts/mkdb.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env sh
+
+root="$(dirname "$0")/.."
+
+rm "$root/target/database.sqlite"
+
+sqlite3 "$root/target/database.sqlite" <"$root/src/storage/video_database/schema.sql"
+
+# vim: ft=sh
diff --git a/pkgs/by-name/yt/yt/src/app.rs b/pkgs/by-name/yt/yt/src/app.rs
new file mode 100644
index 00000000..cacb64bb
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/app.rs
@@ -0,0 +1,29 @@
+use anyhow::{Context, Result};
+use sqlx::{query, sqlite::SqliteConnectOptions, SqlitePool};
+
+use crate::constants;
+
+pub struct App {
+    pub database: SqlitePool,
+}
+
+impl App {
+    pub async fn new() -> Result<Self> {
+        let db_name = constants::database()?;
+
+        let options = SqliteConnectOptions::new()
+            .filename(db_name)
+            .optimize_on_close(true, None)
+            .create_if_missing(true);
+
+        let pool = SqlitePool::connect_with(options)
+            .await
+            .context("Failed to connect to database!")?;
+
+        query(include_str!("storage/video_database/schema.sql"))
+            .execute(&pool)
+            .await?;
+
+        Ok(App { database: pool })
+    }
+}
diff --git a/pkgs/by-name/yt/yt/src/bin/yt/main.rs b/pkgs/by-name/yt/yt/src/bin/yt/main.rs
deleted file mode 100644
index 37348834..00000000
--- a/pkgs/by-name/yt/yt/src/bin/yt/main.rs
+++ /dev/null
@@ -1,91 +0,0 @@
-use anyhow::{bail, Context, Result};
-use std::{
-    env, fs,
-    io::{BufRead, BufReader, BufWriter, Write},
-    process::Command as StdCmd,
-};
-use tempfile::Builder;
-use yt::{
-    constants::{last_select, HELP_STR},
-    downloader::Downloader,
-    filter_line, YtccListData,
-};
-
-fn main() -> Result<()> {
-    cli_log::init_cli_log!();
-
-    let json_map = {
-        let mut ytcc = StdCmd::new("ytcc");
-        ytcc.args([
-            "--output",
-            "json",
-            "list",
-            "--order-by",
-            "publish_date",
-            "desc",
-        ]);
-
-        serde_json::from_slice::<Vec<YtccListData>>(
-            &ytcc.output().context("Failed to json from ytcc")?.stdout,
-        )
-        .context("Failed to deserialize json output")?
-    };
-
-    let temp_file = Builder::new()
-        .prefix("yt_video_select-")
-        .suffix(".yts")
-        .rand_bytes(6)
-        .tempfile()
-        .context("Failed to get tempfile")?;
-
-    {
-        let mut edit_file = BufWriter::new(&temp_file);
-
-        json_map.iter().for_each(|line| {
-            let line = line.to_string();
-            edit_file
-                .write_all(line.as_bytes())
-                .expect("This write should not fail");
-        });
-
-        edit_file.write_all(HELP_STR.as_bytes())?;
-        edit_file.flush().context("Failed to flush edit file")?;
-
-        let mut nvim = StdCmd::new("nvim");
-        nvim.arg(temp_file.path());
-        let status = nvim.status().context("Falied to run nvim")?;
-        if !status.success() {
-            bail!("nvim exited with error status: {}", status)
-        }
-    }
-
-    let read_file = temp_file.reopen()?;
-    fs::copy(
-        temp_file.path(),
-        last_select().context("Failed to get the persistent selection file path")?,
-    )
-    .context("Failed to persist selection file")?;
-
-    let mut watching = Vec::new();
-    let reader = BufReader::new(&read_file);
-    for line in reader.lines() {
-        let line = line.context("Failed to read line")?;
-
-        if let Some(downloadable) =
-            filter_line(&line).with_context(|| format!("Failed to process line: '{}'", line))?
-        {
-            watching.push(downloadable);
-        }
-    }
-
-    if watching.is_empty() {
-        return Ok(());
-    }
-
-    let downloader = Downloader::new(watching).context("Failed to construct downloader")?;
-    downloader
-        .consume()
-        .context("Failed to consume downloader")?;
-
-    Ok(())
-}
diff --git a/pkgs/by-name/yt/yt/src/bin/ytc/args.rs b/pkgs/by-name/yt/yt/src/bin/ytc/args.rs
deleted file mode 100644
index 8b2d6a61..00000000
--- a/pkgs/by-name/yt/yt/src/bin/ytc/args.rs
+++ /dev/null
@@ -1,26 +0,0 @@
-use clap::{Parser, Subcommand};
-/// A helper for downloading and playing youtube videos
-#[derive(Parser, Debug)]
-#[clap(author, version, about, long_about = None)]
-pub struct Args {
-    #[command(subcommand)]
-    /// The subcommand to execute
-    pub subcommand: Command,
-}
-#[derive(Subcommand, Debug)]
-pub enum Command {
-    #[clap(value_parser)]
-    /// Work based of ytcc ids
-    Id {
-        #[clap(value_parser)]
-        /// A list of ids to play
-        ids: Vec<u32>,
-    },
-    #[clap(value_parser)]
-    /// Work based of raw youtube urls
-    Url {
-        #[clap(value_parser)]
-        /// A list of urls to play
-        urls: Vec<String>,
-    },
-}
diff --git a/pkgs/by-name/yt/yt/src/bin/ytc/main.rs b/pkgs/by-name/yt/yt/src/bin/ytc/main.rs
deleted file mode 100644
index b38157df..00000000
--- a/pkgs/by-name/yt/yt/src/bin/ytc/main.rs
+++ /dev/null
@@ -1,77 +0,0 @@
-use std::{env, process::Command as StdCmd};
-
-use anyhow::{bail, Context, Result};
-use clap::Parser;
-use log::debug;
-use url::Url;
-use yt::{
-    downloader::{Downloadable, Downloader},
-    YtccListData,
-};
-
-use crate::args::{Args, Command};
-
-mod args;
-
-fn main() -> Result<()> {
-    let args = Args::parse();
-    cli_log::init_cli_log!();
-
-    let playspec: Vec<Downloadable> = match args.subcommand {
-        Command::Id { ids } => {
-            let mut output = Vec::with_capacity(ids.len());
-            for id in ids {
-                debug!("Adding {}", id);
-                let mut ytcc = StdCmd::new("ytcc");
-                ytcc.args([
-                    "--output",
-                    "json",
-                    "list",
-                    "--watched",
-                    "--unwatched",
-                    "--attributes",
-                    "url",
-                    "--ids",
-                    id.to_string().as_str(),
-                ]);
-                let json = serde_json::from_slice::<Vec<YtccListData>>(
-                    &ytcc.output().context("Failed to get url from id")?.stdout,
-                )
-                .context("Failed to deserialize json output")?;
-
-                if json.is_empty() {
-                    bail!("Could not find a video with id: {}", id);
-                }
-                assert_eq!(json.len(), 1);
-                let json = json.first().expect("Has only one element");
-
-                debug!("Id resolved to: '{}'", &json.url);
-
-                output.push(Downloadable {
-                    url: Url::parse(&json.url)?,
-                    id: Some(json.id),
-                })
-            }
-            output
-        }
-        Command::Url { urls } => {
-            let mut output = Vec::with_capacity(urls.len());
-            for url in urls {
-                output.push(Downloadable {
-                    url: Url::parse(&url).context("Failed to parse url")?,
-                    id: None,
-                })
-            }
-            output
-        }
-    };
-
-    debug!("Initializing downloader");
-    let downloader = Downloader::new(playspec)?;
-
-    downloader
-        .consume()
-        .context("Failed to consume downloader")?;
-
-    Ok(())
-}
diff --git a/pkgs/by-name/yt/yt/src/bin/yts/args.rs b/pkgs/by-name/yt/yt/src/bin/yts/args.rs
deleted file mode 100644
index 56989421..00000000
--- a/pkgs/by-name/yt/yt/src/bin/yts/args.rs
+++ /dev/null
@@ -1,41 +0,0 @@
-use clap::{Parser, Subcommand};
-/// A helper for selecting which videos to download from ytcc to ytc
-#[derive(Parser, Debug)]
-#[clap(author, version, about, long_about = None)]
-pub struct Args {
-    #[command(subcommand)]
-    /// subcommand to execute
-    pub subcommand: Option<Command>,
-}
-
-#[derive(Subcommand, Debug)]
-pub enum Command {
-    #[clap(value_parser)]
-    /// Which ordering to use
-    Order {
-        #[command(subcommand)]
-        command: OrderCommand,
-    },
-}
-
-#[derive(Subcommand, Debug)]
-pub enum OrderCommand {
-    #[clap(value_parser)]
-    /// Order by date
-    #[group(required = true)]
-    Date {
-        #[arg(value_parser)]
-        /// Order descending
-        desc: bool,
-        #[clap(value_parser)]
-        /// Order ascending
-        asc: bool,
-    },
-    #[clap(value_parser)]
-    /// Pass a raw SQL 'ORDER BY' value
-    Raw {
-        #[clap(value_parser)]
-        /// The raw value(s) to pass
-        value: Vec<String>,
-    },
-}
diff --git a/pkgs/by-name/yt/yt/src/bin/yts/main.rs b/pkgs/by-name/yt/yt/src/bin/yts/main.rs
deleted file mode 100644
index 7398db61..00000000
--- a/pkgs/by-name/yt/yt/src/bin/yts/main.rs
+++ /dev/null
@@ -1,91 +0,0 @@
-use anyhow::{bail, Context, Result};
-use clap::Parser;
-use std::{
-    env,
-    io::{BufRead, BufReader, Write},
-    process::Command as StdCmd,
-};
-use tempfile::NamedTempFile;
-use yt::{constants::HELP_STR, filter_line, YtccListData};
-
-use crate::args::{Args, Command, OrderCommand};
-
-mod args;
-
-fn main() -> Result<()> {
-    let args = Args::parse();
-    cli_log::init_cli_log!();
-
-    let ordering = match args.subcommand.unwrap_or(Command::Order {
-        command: OrderCommand::Date {
-            desc: true,
-            asc: false,
-        },
-    }) {
-        Command::Order { command } => match command {
-            OrderCommand::Date { desc, asc } => {
-                if desc {
-                    vec!["--order-by".into(), "publish_date".into(), "desc".into()]
-                } else if asc {
-                    vec!["--order-by".into(), "publish_date".into(), "asc".into()]
-                } else {
-                    vec!["--order-by".into(), "publish_date".into(), "desc".into()]
-                }
-            }
-            OrderCommand::Raw { value } => [vec!["--order-by".into()], value].concat(),
-        },
-    };
-
-    let json_map = {
-        let mut ytcc = StdCmd::new("ytcc");
-        ytcc.args(["--output", "json", "list"]);
-        ytcc.args(ordering);
-
-        serde_json::from_slice::<Vec<YtccListData>>(
-            &ytcc.output().context("Failed to json from ytcc")?.stdout,
-        )
-        .context("Failed to deserialize json output")?
-    };
-
-    let mut edit_file = NamedTempFile::new().context("Failed to get tempfile")?;
-
-    json_map.iter().for_each(|line| {
-        let line = line.to_string();
-        edit_file
-            .write_all(line.as_bytes())
-            .expect("This write should not fail");
-    });
-
-    write!(&edit_file, "{}", HELP_STR)?;
-    edit_file.flush().context("Failed to flush edit file")?;
-
-    let read_file = edit_file.reopen()?;
-
-    let mut nvim = StdCmd::new("nvim");
-    nvim.arg(edit_file.path());
-
-    let status = nvim.status().context("Falied to run nvim")?;
-    if !status.success() {
-        bail!("Nvim exited with error status: {}", status)
-    }
-
-    let mut watching = Vec::new();
-    let reader = BufReader::new(&read_file);
-    for line in reader.lines() {
-        let line = line.context("Failed to read line")?;
-
-        if let Some(downloadable) =
-            filter_line(&line).with_context(|| format!("Failed to process line: '{}'", line))?
-        {
-            watching.push(downloadable);
-        }
-    }
-
-    let watching: String = watching
-        .iter()
-        .map(|d| d.to_string())
-        .collect::<Vec<String>>()
-        .join("\n");
-    println!("{}", &watching);
-    Ok(())
-}
diff --git a/pkgs/by-name/yt/yt/src/cache/mod.rs b/pkgs/by-name/yt/yt/src/cache/mod.rs
new file mode 100644
index 00000000..b60cda89
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/cache/mod.rs
@@ -0,0 +1,63 @@
+use std::path::Path;
+
+use anyhow::Result;
+use log::info;
+
+use crate::{
+    app::App,
+    storage::video_database::{
+        downloader::set_video_cache_path, getters::get_videos, setters::set_video_status, Video,
+        VideoStatus,
+    },
+};
+
+async fn invalidate_video(app: &App, video: &Video) -> Result<()> {
+    info!("Invalidating cache of video: '{}'", video.title);
+
+    set_video_status(app, &video.extractor_hash, VideoStatus::Watch, None).await?;
+    set_video_cache_path(app, &video, None).await?;
+
+    Ok(())
+}
+
+pub async fn invalidate(app: &App) -> Result<()> {
+    let all_cached_things = get_videos(app, &[VideoStatus::Cached]).await?;
+
+    info!("Got videos to invalidate: '{}'", all_cached_things.len());
+
+    for video in all_cached_things {
+        invalidate_video(app, &video).await?
+    }
+
+    Ok(())
+}
+
+pub async fn maintain(app: &App, all: bool) -> Result<()> {
+    let domain = if all {
+        vec![
+            VideoStatus::Pick,
+            //
+            VideoStatus::Watch,
+            VideoStatus::Cached,
+            VideoStatus::Watched,
+            //
+            VideoStatus::Drop,
+            VideoStatus::Dropped,
+        ]
+    } else {
+        vec![VideoStatus::Watch, VideoStatus::Cached]
+    };
+
+    let cached_videos = get_videos(app, domain.as_slice()).await?;
+
+    for vid in cached_videos {
+        let path: &Path = vid.cache_path.as_ref().expect("This is some");
+
+        info!("Checking if path ('{}') exists", path.display());
+        if !path.exists() {
+            invalidate_video(app, &vid).await?;
+        }
+    }
+
+    Ok(())
+}
diff --git a/pkgs/by-name/yt/yt/src/cli.rs b/pkgs/by-name/yt/yt/src/cli.rs
new file mode 100644
index 00000000..66b1d4c1
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/cli.rs
@@ -0,0 +1,114 @@
+use std::path::PathBuf;
+
+use clap::{ArgAction, Parser, Subcommand};
+use url::Url;
+
+#[derive(Parser, Debug)]
+#[clap(author, version, about, long_about = None)]
+/// An command line interface to select, download and watch videos
+pub struct Args {
+    #[command(subcommand)]
+    /// The subcommand to execute [default: select]
+    pub command: Option<Command>,
+
+    /// Increase message verbosity
+    #[arg(long="verbose", short = 'v', action = ArgAction::Count)]
+    pub verbosity: u8,
+
+    /// Silence all output
+    #[arg(long, short = 'q')]
+    pub quiet: bool,
+}
+
+#[derive(Subcommand, Debug)]
+pub enum Command {
+    /// Download and cache URLs
+    Download {
+        /// The list of URLs to download (empty: use the database)
+        urls: Vec<Url>,
+    },
+
+    /// Watch the already cached (and selected) videos
+    Watch {},
+
+    /// Show, which videos have been selected to be watched (and their cache status)
+    Status {},
+
+    /// Perform various tests
+    Check {
+        #[command(subcommand)]
+        command: CheckCommand,
+    },
+
+    /// Display the comments of the currently playing video
+    Comments {},
+    /// Display the description of the currently playing video
+    Description {},
+
+    /// Manipulate the video cache in the database
+    Cache {
+        #[command(subcommand)]
+        command: CacheCommand,
+    },
+
+    /// Open a `git rebase` like file to select the videos to watch
+    Select,
+
+    /// Subscribe to an URL
+    Subscribe {
+        #[arg(short, long)]
+        /// The human readable name of the subscription
+        name: Option<String>,
+
+        /// The URL to listen to
+        url: Url,
+    },
+
+    /// Unsubscribe from an URL
+    Unsubscribe {
+        /// The human readable name of the subscription
+        name: String,
+    },
+
+    /// Update the video database
+    Update {
+        #[arg(short, long, default_value = "20")]
+        /// The number of videos to stop updating
+        max_backlog: u32,
+
+        #[arg(short, long)]
+        /// The subscriptions to update (can be given multiple times)
+        subscriptions: Vec<String>,
+    },
+
+    /// Update one subscription (this is here to parallelize the normal `update`)
+    #[command(hide = true)]
+    UpdateOnce {
+        /// The name of the subscription to update
+        sub_name: String,
+
+        /// The number of videos to stop updating
+        max_backlog: u32,
+    },
+
+    /// List all subscriptions
+    Subscriptions {},
+}
+
+#[derive(Subcommand, Clone, Debug)]
+pub enum CheckCommand {
+    /// Check if the given info.json is deserializable
+    InfoJson { path: PathBuf },
+}
+
+#[derive(Subcommand, Clone, Copy, Debug)]
+pub enum CacheCommand {
+    /// Invalidate all cache entries
+    Invalidate,
+
+    /// Check every path for validity (removing all invalid cache entries)
+    Maintain {
+        /// Check every video (otherwise only the videos to be watched are checked)
+        all: bool,
+    },
+}
diff --git a/pkgs/by-name/yt/yt/src/comments/comment.rs b/pkgs/by-name/yt/yt/src/comments/comment.rs
new file mode 100644
index 00000000..4c322ae1
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/comments/comment.rs
@@ -0,0 +1,53 @@
+use yt_dlp::wrapper::info_json::Comment;
+
+#[derive(Debug, Clone)]
+pub struct CommentExt {
+    pub value: Comment,
+    pub replies: Vec<CommentExt>,
+}
+
+#[derive(Debug, Default)]
+pub struct Comments {
+    pub(super) vec: Vec<CommentExt>,
+}
+
+impl Comments {
+    pub fn new() -> Self {
+        Self::default()
+    }
+    pub fn push(&mut self, value: CommentExt) {
+        self.vec.push(value);
+    }
+    pub fn get_mut(&mut self, key: &str) -> Option<&mut CommentExt> {
+        self.vec.iter_mut().filter(|c| c.value.id.id == key).last()
+    }
+    pub fn insert(&mut self, key: &str, value: CommentExt) {
+        let parent = self
+            .vec
+            .iter_mut()
+            .filter(|c| c.value.id.id == key)
+            .last()
+            .expect("One of these should exist");
+        parent.push_reply(value);
+    }
+}
+impl CommentExt {
+    pub fn push_reply(&mut self, value: CommentExt) {
+        self.replies.push(value)
+    }
+    pub fn get_mut_reply(&mut self, key: &str) -> Option<&mut CommentExt> {
+        self.replies
+            .iter_mut()
+            .filter(|c| c.value.id.id == key)
+            .last()
+    }
+}
+
+impl From<Comment> for CommentExt {
+    fn from(value: Comment) -> Self {
+        Self {
+            replies: vec![],
+            value,
+        }
+    }
+}
diff --git a/pkgs/by-name/yt/yt/src/comments/display.rs b/pkgs/by-name/yt/yt/src/comments/display.rs
new file mode 100644
index 00000000..bc74b469
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/comments/display.rs
@@ -0,0 +1,107 @@
+use std::fmt::Write;
+
+use chrono::{Local, TimeZone};
+use chrono_humanize::{Accuracy, HumanTime, Tense};
+
+use crate::comments::comment::CommentExt;
+
+use super::comment::Comments;
+
+impl Comments {
+    pub fn render(&self, color: bool) -> String {
+        self.render_help(color).expect("This should never fail.")
+    }
+
+    fn render_help(&self, color: bool) -> Result<String, std::fmt::Error> {
+        let mut f = String::new();
+
+        macro_rules! c {
+            ($color_str:expr, $write:ident, $color:expr) => {
+                if $color {
+                    $write.write_str(concat!("\x1b[", $color_str, "m"))?
+                }
+            };
+        }
+
+        fn format(
+            comment: &CommentExt,
+            f: &mut String,
+            ident_count: u32,
+            color: bool,
+        ) -> std::fmt::Result {
+            let ident = &(0..ident_count).map(|_| " ").collect::<String>();
+            let value = &comment.value;
+
+            f.write_str(ident)?;
+
+            if value.author_is_uploader {
+                c!("91;1", f, color);
+            } else {
+                c!("35", f, color);
+            }
+
+            f.write_str(&value.author)?;
+            c!("0", f, color);
+            if value.edited || value.is_favorited {
+                f.write_str("[")?;
+                if value.edited {
+                    f.write_str("")?;
+                }
+                if value.edited && value.is_favorited {
+                    f.write_str(" ")?;
+                }
+                if value.is_favorited {
+                    f.write_str("")?;
+                }
+                f.write_str("]")?;
+            }
+
+            c!("36;1", f, color);
+            write!(
+                f,
+                " {}",
+                HumanTime::from(
+                    Local
+                        .timestamp_opt(value.timestamp, 0)
+                        .single()
+                        .expect("This should be valid")
+                )
+                .to_text_en(Accuracy::Rough, Tense::Past)
+            )?;
+            c!("0", f, color);
+
+            // c!("31;1", f);
+            // f.write_fmt(format_args!(" [{}]", comment.value.like_count))?;
+            // c!("0", f);
+
+            f.write_str(":\n")?;
+            f.write_str(ident)?;
+
+            f.write_str(&value.text.replace('\n', &format!("\n{}", ident)))?;
+            f.write_str("\n")?;
+
+            if !comment.replies.is_empty() {
+                let mut children = comment.replies.clone();
+                children.sort_by(|a, b| a.value.timestamp.cmp(&b.value.timestamp));
+
+                for child in children {
+                    format(&child, f, ident_count + 4, color)?;
+                }
+            } else {
+                f.write_str("\n")?;
+            }
+
+            Ok(())
+        }
+
+        if !&self.vec.is_empty() {
+            let mut children = self.vec.clone();
+            children.sort_by(|a, b| b.value.like_count.cmp(&a.value.like_count));
+
+            for child in children {
+                format(&child, &mut f, 0, color)?
+            }
+        }
+        Ok(f)
+    }
+}
diff --git a/pkgs/by-name/yt/yt/src/comments/mod.rs b/pkgs/by-name/yt/yt/src/comments/mod.rs
new file mode 100644
index 00000000..5302a985
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/comments/mod.rs
@@ -0,0 +1,187 @@
+use std::{
+    env,
+    fs::{self},
+    io::Write,
+    mem,
+    path::PathBuf,
+    process::{Command, Stdio},
+};
+
+use anyhow::{bail, Context, Result};
+use comment::{CommentExt, Comments};
+use regex::Regex;
+use yt_dlp::wrapper::info_json::{Comment, InfoJson, Parent};
+
+use crate::{
+    app::App,
+    storage::video_database::{
+        getters::{get_currently_playing_video, get_video_info_json},
+        Video,
+    },
+};
+
+mod comment;
+mod display;
+
+fn get_runtime_path(component: &'static str) -> anyhow::Result<PathBuf> {
+    let out: PathBuf = format!(
+        "{}/{}",
+        env::var("XDG_RUNTIME_DIR").expect("This should always exist"),
+        component
+    )
+    .into();
+    fs::create_dir_all(out.parent().expect("Parent should exist"))?;
+    Ok(out)
+}
+
+const STATUS_PATH: &str = "ytcc/running";
+pub fn status_path() -> anyhow::Result<PathBuf> {
+    get_runtime_path(STATUS_PATH)
+}
+
+pub async fn get_comments(app: &App) -> Result<Comments> {
+    let currently_playing_video: Video =
+        if let Some(video) = get_currently_playing_video(&app).await? {
+            video
+        } else {
+            bail!("Could not find a currently playing video!");
+        };
+
+    let mut info_json: InfoJson = get_video_info_json(&currently_playing_video)
+        .await?
+        .expect("A currently *playing* must be cached. And thus the info.json should be available");
+
+    let base_comments = mem::take(&mut info_json.comments).expect("A video should have comments");
+    drop(info_json);
+
+    let mut comments = Comments::new();
+    base_comments.into_iter().for_each(|c| {
+        if let Parent::Id(id) = &c.parent {
+            comments.insert(&(id.clone()), CommentExt::from(c));
+        } else {
+            comments.push(CommentExt::from(c));
+        }
+    });
+
+    comments.vec.iter_mut().for_each(|comment| {
+       let replies = mem::take(&mut comment.replies);
+       let mut output_replies: Vec<CommentExt>  = vec![];
+
+       let re = Regex::new(r"\u{200b}?(@[^\t\s]+)\u{200b}?").unwrap();
+       for reply in replies {
+           if let Some(replyee_match) =  re.captures(&reply.value.text){
+               let full_match = replyee_match.get(0).expect("This always exists");
+               let text = reply.
+                   value.
+                   text[0..full_match.start()]
+                   .to_owned()
+                   +
+                   &reply
+                   .value
+                   .text[full_match.end()..];
+               let text: &str = text.trim().trim_matches('\u{200b}');
+
+               let replyee = replyee_match.get(1).expect("This should exist").as_str();
+
+
+               if let Some(parent) = output_replies
+                   .iter_mut()
+                   // .rev()
+                   .flat_map(|com| &mut com.replies)
+                   .flat_map(|com| &mut com.replies)
+                   .flat_map(|com| &mut com.replies)
+                   .filter(|com| com.value.author == replyee)
+                   .last()
+               {
+                   parent.replies.push(CommentExt::from(Comment {
+                       text: text.to_owned(),
+                       ..reply.value
+                   }))
+               } else if let Some(parent) = output_replies
+                   .iter_mut()
+                   // .rev()
+                   .flat_map(|com| &mut com.replies)
+                   .flat_map(|com| &mut com.replies)
+                   .filter(|com| com.value.author == replyee)
+                   .last()
+               {
+                   parent.replies.push(CommentExt::from(Comment {
+                       text: text.to_owned(),
+                       ..reply.value
+                   }))
+               } else if let Some(parent) = output_replies
+                   .iter_mut()
+                   // .rev()
+                   .flat_map(|com| &mut com.replies)
+                   .filter(|com| com.value.author == replyee)
+                   .last()
+               {
+                   parent.replies.push(CommentExt::from(Comment {
+                       text: text.to_owned(),
+                       ..reply.value
+                   }))
+               } else if let Some(parent) = output_replies.iter_mut()
+                   // .rev()
+                   .filter(|com| com.value.author == replyee)
+                   .last()
+               {
+                   parent.replies.push(CommentExt::from(Comment {
+                       text: text.to_owned(),
+                       ..reply.value
+                   }))
+               } else {
+                   eprintln!(
+                   "Failed to find a parent for ('{}') both directly and via replies! The reply text was:\n'{}'\n",
+                   replyee,
+                   reply.value.text
+               );
+                   output_replies.push(reply);
+               }
+           } else {
+               output_replies.push(reply);
+           }
+       }
+       comment.replies = output_replies;
+    });
+
+    Ok(comments)
+}
+
+pub async fn comments(app: &App) -> Result<()> {
+    let comments = get_comments(app).await?;
+
+    let mut less = Command::new("less")
+        .args(["--raw-control-chars"])
+        .stdin(Stdio::piped())
+        .stderr(Stdio::inherit())
+        .spawn()
+        .context("Failed to run less")?;
+
+    let mut child = Command::new("fmt")
+        .args(["--uniform-spacing", "--split-only", "--width=90"])
+        .stdin(Stdio::piped())
+        .stderr(Stdio::inherit())
+        .stdout(less.stdin.take().expect("Should be open"))
+        .spawn()
+        .context("Failed to run fmt")?;
+
+    let mut stdin = child.stdin.take().context("Failed to open stdin")?;
+    std::thread::spawn(move || {
+        stdin
+            .write_all(comments.render(true).as_bytes())
+            .expect("Should be able to write to stdin of fmt");
+    });
+
+    let _ = less.wait().context("Failed to await less")?;
+
+    Ok(())
+}
+
+#[cfg(test)]
+mod test {
+    #[test]
+    fn test_string_replacement() {
+        let s = "A \n\nB\n\nC".to_owned();
+        assert_eq!("A \n  \n  B\n  \n  C", s.replace('\n', "\n  "))
+    }
+}
diff --git a/pkgs/by-name/yt/yt/src/constants.rs b/pkgs/by-name/yt/yt/src/constants.rs
index 5e233656..17e0f018 100644
--- a/pkgs/by-name/yt/yt/src/constants.rs
+++ b/pkgs/by-name/yt/yt/src/constants.rs
@@ -1,6 +1,8 @@
-use std::{env, fs, path::PathBuf};
+use std::{env::temp_dir, path::PathBuf};
 
-pub const HELP_STR: &str = include_str!("./help.str");
+use anyhow::Context;
+
+pub const HELP_STR: &str = include_str!("./select/selection_file/help.str");
 
 pub const YT_DLP_FLAGS: [&str; 13] = [
     // Ignore errors arising of unavailable sponsor block API
@@ -27,25 +29,45 @@ pub const MPV_FLAGS: [&str; 4] = [
 
 pub const CONCURRENT: u32 = 5;
 
-pub const DOWNLOAD_DIR: &str = "/tmp/ytcc";
+// We download to the temp dir to avoid taxing the disk
+pub fn download_dir() -> PathBuf {
+    const DOWNLOAD_DIR: &str = "/tmp/yt";
+    PathBuf::from(DOWNLOAD_DIR)
+}
 
-fn get_runtime_path(component: &'static str) -> anyhow::Result<PathBuf> {
-    let out: PathBuf = format!(
-        "{}/{}",
-        env::var("XDG_RUNTIME_DIR").expect("This should always exist"),
-        component
-    )
-    .into();
-    fs::create_dir_all(out.parent().expect("Parent should exist"))?;
-    Ok(out)
+const PREFIX: &str = "yt";
+fn get_runtime_path(name: &'static str) -> anyhow::Result<PathBuf> {
+    let xdg_dirs = xdg::BaseDirectories::with_prefix(PREFIX)?;
+    xdg_dirs
+        .place_runtime_file(name)
+        .with_context(|| format!("Failed to place runtime file: '{}'", name))
+}
+fn get_data_path(name: &'static str) -> anyhow::Result<PathBuf> {
+    let xdg_dirs = xdg::BaseDirectories::with_prefix(PREFIX)?;
+    xdg_dirs
+        .place_data_file(name)
+        .with_context(|| format!("Failed to place data file: '{}'", name))
 }
 
-const STATUS_PATH: &str = "ytcc/running";
 pub fn status_path() -> anyhow::Result<PathBuf> {
+    const STATUS_PATH: &str = "running.info.json";
     get_runtime_path(STATUS_PATH)
 }
-
-const LAST_SELECT: &str = "ytcc/selected.yts";
 pub fn last_select() -> anyhow::Result<PathBuf> {
+    const LAST_SELECT: &str = "selected.yts";
     get_runtime_path(LAST_SELECT)
 }
+
+pub fn database() -> anyhow::Result<PathBuf> {
+    const DATABASE: &str = "videos.sqlite";
+    get_data_path(DATABASE)
+}
+pub fn subscriptions() -> anyhow::Result<PathBuf> {
+    const SUBSCRIPTIONS: &str = "subscriptions.json";
+    get_data_path(SUBSCRIPTIONS)
+}
+
+pub fn cache_path() -> PathBuf {
+    let temp_dir = temp_dir();
+    temp_dir.join("ytc")
+}
diff --git a/pkgs/by-name/yt/yt/src/download/download_options.rs b/pkgs/by-name/yt/yt/src/download/download_options.rs
new file mode 100644
index 00000000..4588e774
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/download/download_options.rs
@@ -0,0 +1,97 @@
+use serde_json::json;
+
+use crate::constants;
+
+// {
+//     "ratelimit": conf.ratelimit if conf.ratelimit > 0 else None,
+//     "retries": conf.retries,
+//     "merge_output_format": conf.merge_output_format,
+//     "restrictfilenames": conf.restrict_filenames,
+//     "ignoreerrors": False,
+//     "postprocessors": [{"key": "FFmpegMetadata"}],
+//     "logger": _ytdl_logger
+// }
+
+pub fn download_opts() -> serde_json::Map<String, serde_json::Value> {
+    match json!({
+      "extract_flat": false,
+      "extractor_args": {
+        "youtube": {
+          "comment_sort": [
+            "top"
+          ],
+          "max_comments": [
+            "150",
+            "all",
+            "100"
+          ]
+        }
+      },
+      "ffmpeg_location": env!("FFMPEG_LOCATION"),
+      "format": "bestvideo[height<=?1080]+bestaudio/best",
+      "fragment_retries": 10,
+      "getcomments": true,
+      "ignoreerrors": false,
+      "retries": 10,
+
+      "writeinfojson": true,
+      "writeannotations": true,
+      "writesubtitles": true,
+      "writeautomaticsub": true,
+
+
+      "outtmpl": {
+        "default": constants::download_dir().join("%(channel)s/%(title)s.%(ext)s"),
+        "chapter": "%(title)s - %(section_number)03d %(section_title)s [%(id)s].%(ext)s"
+      },
+      "compat_opts": {},
+      "forceprint": {},
+      "print_to_file": {},
+      "windowsfilenames": false,
+      "restrictfilenames": false,
+      "trim_file_names": false,
+      "postprocessors": [
+        {
+          "api": "https://sponsor.ajay.app",
+          "categories": [
+            "interaction",
+            "intro",
+            "music_offtopic",
+            "sponsor",
+            "outro",
+            "poi_highlight",
+            "preview",
+            "selfpromo",
+            "filler",
+            "chapter"
+          ],
+          "key": "SponsorBlock",
+          "when": "after_filter"
+        },
+        {
+          "force_keyframes": false,
+          "key": "ModifyChapters",
+          "remove_chapters_patterns": [],
+          "remove_ranges": [],
+          "remove_sponsor_segments": [
+            "sponsor"
+          ],
+          "sponsorblock_chapter_title": "[SponsorBlock]: %(category_names)l"
+        },
+        {
+          "add_chapters": true,
+          "add_infojson": null,
+          "add_metadata": false,
+          "key": "FFmpegMetadata"
+        },
+        {
+          "key": "FFmpegConcat",
+          "only_multi_video": true,
+          "when": "playlist"
+        }
+      ]
+    }) {
+        serde_json::Value::Object(obj) => obj,
+        _ => unreachable!("This is an object"),
+    }
+}
diff --git a/pkgs/by-name/yt/yt/src/download/mod.rs b/pkgs/by-name/yt/yt/src/download/mod.rs
new file mode 100644
index 00000000..2dc7c431
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/download/mod.rs
@@ -0,0 +1,152 @@
+use std::time::Duration;
+
+use crate::{
+    app::App,
+    download::download_options::download_opts,
+    storage::video_database::{
+        downloader::{get_next_uncached_video, set_video_cache_path},
+        extractor_hash::ExtractorHash,
+        setters::set_video_status,
+        Video, VideoStatus,
+    },
+};
+
+use anyhow::{Context, Result};
+use log::{debug, info};
+use tokio::{task::JoinHandle, time};
+
+mod download_options;
+
+#[derive(Debug)]
+pub struct CurrentDownload {
+    task_handle: JoinHandle<Result<()>>,
+    extractor_hash: ExtractorHash,
+}
+
+impl CurrentDownload {
+    fn new_from_video(video: Video) -> Self {
+        let extractor_hash = video.extractor_hash.clone();
+
+        let task_handle = tokio::spawn(async move {
+            // FIXME: Remove this app reconstruction <2024-07-29>
+            let new_app = App::new().await?;
+
+            Downloader::actually_cache_video(&new_app, &video)
+                .await
+                .with_context(|| format!("Failed to cache video: '{}'", video.title))?;
+            Ok(())
+        });
+
+        Self {
+            task_handle,
+            extractor_hash,
+        }
+    }
+}
+
+pub struct Downloader {
+    current_download: Option<CurrentDownload>,
+}
+
+impl Downloader {
+    pub fn new() -> Self {
+        Self {
+            current_download: None,
+        }
+    }
+
+    /// The entry point to the Downloader.
+    /// This Downloader will periodically check if the database has changed, and then also
+    /// change which videos it downloads.
+    /// This will run, until the database doesn't contain any watchable videos
+    pub async fn consume(&mut self, app: &App) -> Result<()> {
+        while let Some(next_video) = get_next_uncached_video(app).await? {
+            if let Some(_) = &self.current_download {
+                let current_download = self.current_download.take().expect("Is Some");
+
+                if next_video.extractor_hash != current_download.extractor_hash {
+                    info!(
+                    "Noticed, that the next video is not the video being downloaded, replacing it ('{}' vs. '{}')!",
+                        next_video.extractor_hash.format(app).await?, current_download.extractor_hash.format(app).await?
+                    );
+
+                    // Replace the currently downloading video
+                    current_download.task_handle.abort();
+
+                    let new_current_download = CurrentDownload::new_from_video(next_video);
+
+                    self.current_download = Some(new_current_download);
+                } else {
+                    debug!(
+                        "Currently downloading '{}'",
+                        current_download.extractor_hash.format(app).await?
+                    );
+                    // Reset the taken value
+                    self.current_download = Some(current_download);
+                    time::sleep(Duration::new(1, 0)).await;
+                }
+            } else {
+                info!(
+                    "No video is being downloaded right now, setting it to '{}'",
+                    next_video.title
+                );
+                let new_current_download = CurrentDownload::new_from_video(next_video);
+                self.current_download = Some(new_current_download);
+            }
+
+            // if get_allocated_cache().await? < CONCURRENT {
+            //     .cache_video(next_video).await?;
+            // }
+        }
+
+        info!("Finished downloading!");
+        Ok(())
+    }
+
+    // pub async fn cache_video(&self, input: Video) -> Result<()> {
+    //     info!("Will cache video: '{}'", &input.title);
+    //     if input.cache_path.is_some() {
+    //         // Value is already cached
+    //         info!(
+    //             "Not caching, as it is already a cached video: '{}'",
+    //             &input.title
+    //         );
+    //         return Ok(());
+    //     } else {
+    //         // Store the video to be cached, if resources are available
+    //         set_video_status(
+    //             &input
+    //                 .extractor_hash
+    //                 .parse()
+    //                 .expect("This hash should always be valid"),
+    //             VideoStatus::Caching,
+    //             None,
+    //         )
+    //         .await?;
+    //         self.cache_sender.send(input).await?;
+    //
+    //         Ok(())
+    //     }
+    // }
+
+    async fn actually_cache_video(app: &App, video: &Video) -> Result<()> {
+        let result = yt_dlp::download(&[video.url.clone()], &download_opts())
+            .await
+            .with_context(|| format!("Failed to download video: '{}'", video.title))?;
+
+        assert_eq!(result.len(), 1);
+        let result = &result[0];
+
+        set_video_cache_path(app, video, Some(&result)).await?;
+
+        set_video_status(app, &(video.extractor_hash), VideoStatus::Cached, None).await?;
+
+        info!(
+            "Video '{}' was downlaoded to path: {}",
+            video.title,
+            result.display()
+        );
+
+        Ok(())
+    }
+}
diff --git a/pkgs/by-name/yt/yt/src/downloader.rs b/pkgs/by-name/yt/yt/src/downloader.rs
deleted file mode 100644
index e915700d..00000000
--- a/pkgs/by-name/yt/yt/src/downloader.rs
+++ /dev/null
@@ -1,212 +0,0 @@
-use std::{
-    fs::{self, canonicalize},
-    io::{stderr, stdout, Read},
-    mem,
-    os::unix::fs::symlink,
-    path::PathBuf,
-    process::Command,
-    sync::mpsc::{self, Receiver, Sender},
-    thread::{self, JoinHandle},
-};
-
-use anyhow::{bail, Context, Result};
-use log::{debug, error, warn};
-use url::Url;
-
-use crate::constants::{status_path, CONCURRENT, DOWNLOAD_DIR, MPV_FLAGS, YT_DLP_FLAGS};
-
-#[derive(Debug)]
-pub struct Downloadable {
-    pub url: Url,
-    pub id: Option<u32>,
-}
-
-impl std::fmt::Display for Downloadable {
-    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
-        write!(
-            f,
-            "{}|{}",
-            self.url.as_str().replace('|', ";"),
-            self.id.unwrap_or(0),
-        )
-    }
-}
-
-pub struct Downloader {
-    sent: usize,
-    download_thread: JoinHandle<Result<()>>,
-    orx: Receiver<(PathBuf, Option<u32>)>,
-    itx: Option<Sender<Downloadable>>,
-    playspec: Vec<Downloadable>,
-}
-
-impl Downloader {
-    pub fn new(mut playspec: Vec<Downloadable>) -> anyhow::Result<Downloader> {
-        let (itx, irx): (Sender<Downloadable>, Receiver<Downloadable>) = mpsc::channel();
-        let (otx, orx) = mpsc::channel();
-        let jh = thread::spawn(move || -> Result<()> {
-            while let Ok(pt) = irx.recv() {
-                debug!("Got '{}' to be downloaded", pt);
-                let path = download_url(&pt.url)
-                    .with_context(|| format!("Failed to download url: '{}'", &pt.url))?;
-                otx.send((path, pt.id)).expect("Should not be dropped");
-            }
-            debug!("Finished Downloading everything");
-            Ok(())
-        });
-
-        playspec.reverse();
-        let mut output = Downloader {
-            sent: 0,
-            download_thread: jh,
-            orx,
-            itx: Some(itx),
-            playspec,
-        };
-        if output.playspec.len() <= CONCURRENT as usize {
-            output.add(output.playspec.len() as u32)?;
-        } else {
-            output.add(CONCURRENT)?;
-        }
-        Ok(output)
-    }
-
-    pub fn add(&mut self, number_to_add: u32) -> Result<()> {
-        debug!("Adding {} to be downloaded concurrently", number_to_add);
-        for _ in 0..number_to_add {
-            let pt = self.playspec.pop().expect("This call should be guarded");
-            self.itx.as_ref().expect("Should still be valid").send(pt)?;
-            self.sent += 1;
-        }
-        Ok(())
-    }
-
-    /// Return the next video already downloaded, will block until the download is complete
-    pub fn next(&mut self) -> Option<(PathBuf, Option<u32>)> {
-        debug!("Requesting next output");
-        match self.orx.recv() {
-            Ok(ok) => {
-                debug!("Output downloaded to: {}", ok.0.display());
-                if !self.playspec.is_empty() {
-                    self.add(1).ok()?;
-                } else {
-                    debug!(
-                        "Done sending videos to be downloaded, downoladed: {} videos",
-                        self.sent
-                    );
-                    let itx = mem::take(&mut self.itx);
-                    drop(itx)
-                }
-                debug!("Returning: {}|{}", ok.0.display(), ok.1.unwrap_or(0));
-                Some(ok)
-            }
-            Err(err) => {
-                debug!("Received error while listening: {}", err);
-                None
-            }
-        }
-    }
-
-    pub fn drop(self) -> anyhow::Result<()> {
-        // Check that we really downloaded everything
-        assert_eq!(self.playspec.len(), 0);
-        match self.download_thread.join() {
-            Ok(ok) => ok,
-            Err(err) => panic!("Failed to join downloader thread: '{:#?}'", err),
-        }
-    }
-
-    pub fn consume(mut self) -> anyhow::Result<()> {
-        while let Some((path, id)) = self.next() {
-            debug!("Next path to play is: '{}'", path.display());
-            let mut info_json = canonicalize(&path).context("Failed to canoncialize path")?;
-            info_json.set_extension("info.json");
-
-            if status_path()?.is_symlink() {
-                fs::remove_file(status_path()?).context("Failed to delete old status file")?;
-            } else if !status_path()?.exists() {
-                debug!(
-                    "The status path at '{}' does not exists",
-                    status_path()?.display()
-                );
-            } else {
-                bail!(
-                    "The status path ('{}') is not a symlink but exists!",
-                    status_path()?.display()
-                );
-            }
-
-            symlink(info_json, status_path()?).context("Failed to symlink")?;
-
-            let mut mpv = Command::new("mpv");
-            mpv.stdout(stdout());
-            mpv.stderr(stderr());
-            mpv.args(MPV_FLAGS);
-            // TODO: Set the title to the name of the video, not the path <2024-02-09>
-            // mpv.arg(format!("--title="))
-            mpv.arg(&path);
-
-            let status = mpv.status().context("Failed to run mpv")?;
-            if status.success() {
-                fs::remove_file(&path)?;
-                if let Some(id) = id {
-                    println!("\x1b[32;1mMarking {} as watched!\x1b[0m", id);
-                    let mut ytcc = std::process::Command::new("ytcc");
-                    ytcc.stdout(stdout());
-                    ytcc.stderr(stderr());
-                    ytcc.args(["mark"]);
-                    ytcc.arg(id.to_string());
-                    let status = ytcc.status().context("Failed to run ytcc")?;
-                    if let Some(code) = status.code() {
-                        if code != 0 {
-                            bail!("Ytcc failed with status: {}", code);
-                        }
-                    }
-                }
-                debug!("mpv exited with: '{}'", status);
-            } else {
-                warn!("mpv exited with: '{}'", status);
-            }
-        }
-        self.drop()?;
-        Ok(())
-    }
-}
-
-fn download_url(url: &Url) -> Result<PathBuf> {
-    let output_file = tempfile::NamedTempFile::new().context("Failed to create tempfile")?;
-    output_file
-        .as_file()
-        .set_len(0)
-        .context("Failed to truncate temp-file")?;
-    if !Into::<PathBuf>::into(DOWNLOAD_DIR).exists() {
-        fs::create_dir_all(DOWNLOAD_DIR)
-            .with_context(|| format!("Failed to create download dir at: {}", DOWNLOAD_DIR))?
-    }
-    let mut yt_dlp = Command::new("yt-dlp");
-    yt_dlp.current_dir(DOWNLOAD_DIR);
-    yt_dlp.stdout(stdout());
-    yt_dlp.stderr(stderr());
-    yt_dlp.args(YT_DLP_FLAGS);
-    yt_dlp.args([
-        "--output",
-        "%(channel)s/%(title)s.%(ext)s",
-        url.as_str(),
-        "--print-to-file",
-        "after_move:filepath",
-    ]);
-    yt_dlp.arg(output_file.path().as_os_str());
-
-    let status = yt_dlp.status().context("Failed to run yt-dlp")?;
-    if !status.success() {
-        error!("yt-dlp execution failed with error: '{}'", status);
-    }
-
-    let mut path = String::new();
-    output_file
-        .as_file()
-        .read_to_string(&mut path)
-        .context("Failed to read output file temp file")?;
-    let path = path.trim();
-    Ok(path.into())
-}
diff --git a/pkgs/by-name/yt/yt/src/lib.rs b/pkgs/by-name/yt/yt/src/lib.rs
deleted file mode 100644
index b089c1a2..00000000
--- a/pkgs/by-name/yt/yt/src/lib.rs
+++ /dev/null
@@ -1,185 +0,0 @@
-use anyhow::{bail, Context};
-use downloader::Downloadable;
-use serde::Deserialize;
-use url::Url;
-
-pub mod constants;
-pub mod downloader;
-
-#[derive(Deserialize)]
-pub struct YtccListData {
-    pub url: String,
-    pub title: String,
-    pub description: String,
-    pub publish_date: String,
-    pub watch_date: Option<f64>,
-    pub duration: String,
-    pub thumbnail_url: Option<String>,
-    pub extractor_hash: String,
-    pub id: u32,
-    pub playlists: Vec<YtccPlaylistData>,
-}
-
-impl std::fmt::Display for YtccListData {
-    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
-        write!(
-            f,
-            r#"pick {} "{}" "{}" "{}" "{}" "{}"{}"#,
-            self.id,
-            self.title.replace(['"', '„', '”'], "'"),
-            self.publish_date,
-            self.playlists
-                .iter()
-                .map(|p| p.name.replace('"', "'"))
-                .collect::<Vec<String>>()
-                .join(", "),
-            Duration::from(self.duration.trim()),
-            self.url.replace('"', "'"),
-            "\n"
-        )
-    }
-}
-
-#[derive(Deserialize)]
-pub struct YtccPlaylistData {
-    pub name: String,
-    pub url: String,
-    pub reverse: bool,
-}
-
-pub enum LineCommand {
-    Pick,
-    Drop,
-    Watch,
-    Url,
-}
-
-impl std::str::FromStr for LineCommand {
-    type Err = anyhow::Error;
-    fn from_str(v: &str) -> Result<Self, <Self as std::str::FromStr>::Err> {
-        match v {
-            "pick" | "p" => Ok(Self::Pick),
-            "drop" | "d" => Ok(Self::Drop),
-            "watch" | "w" => Ok(Self::Watch),
-            "url" | "u" => Ok(Self::Url),
-            other => bail!("'{}' is not a recognized command!", other),
-        }
-    }
-}
-
-pub struct Line {
-    pub cmd: LineCommand,
-    pub id: u32,
-    pub url: Url,
-}
-
-/// We expect that each line is correctly formatted, and simply use default ones if they are not
-impl From<&str> for Line {
-    fn from(v: &str) -> Self {
-        let buf: Vec<_> = v.split_whitespace().collect();
-        let url: Url = Url::parse(
-            buf.last()
-                .expect("This should always exists")
-                .trim_matches('"'),
-        )
-        .expect("This parsing should work,as the url is generated");
-
-        Line {
-            cmd: buf
-                .get(0)
-                .unwrap_or(&"pick")
-                .parse()
-                .unwrap_or(LineCommand::Pick),
-            id: buf.get(1).unwrap_or(&"0").parse().unwrap_or(0),
-            url,
-        }
-    }
-}
-
-pub struct Duration {
-    time: u32,
-}
-
-impl From<&str> for Duration {
-    fn from(v: &str) -> Self {
-        let buf: Vec<_> = v.split(':').take(2).collect();
-        Self {
-            time: (buf[0].parse::<u32>().expect("Should be a number") * 60)
-                + buf[1].parse::<u32>().expect("Should be a number"),
-        }
-    }
-}
-
-impl std::fmt::Display for Duration {
-    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
-        const SECOND: u32 = 1;
-        const MINUTE: u32 = 60 * SECOND;
-        const HOUR: u32 = 60 * MINUTE;
-
-        let base_hour = self.time - (self.time % HOUR);
-        let base_min = (self.time % HOUR) - ((self.time % HOUR) % MINUTE);
-        let base_sec = (self.time % HOUR) % MINUTE;
-
-        let h = base_hour / HOUR;
-        let m = base_min / MINUTE;
-        let s = base_sec / SECOND;
-
-        if self.time == 0 {
-            write!(f, "[No Duration]")
-        } else if h > 0 {
-            write!(f, "[{h}h {m}m]")
-        } else {
-            write!(f, "[{m}m {s}s]")
-        }
-    }
-}
-#[cfg(test)]
-mod test {
-    use crate::Duration;
-
-    #[test]
-    fn test_display_duration_1h() {
-        let dur = Duration { time: 60 * 60 };
-        assert_eq!("[1h 0m]".to_owned(), dur.to_string());
-    }
-    #[test]
-    fn test_display_duration_30min() {
-        let dur = Duration { time: 60 * 30 };
-        assert_eq!("[30m 0s]".to_owned(), dur.to_string());
-    }
-}
-
-pub fn ytcc_drop(id: u32) -> anyhow::Result<()> {
-    let mut ytcc = std::process::Command::new("ytcc");
-    ytcc.args(["mark", &format!("{}", id)]);
-    if !ytcc.status().context("Failed to run ytcc")?.success() {
-        bail!("`ytcc mark {}` failed to execute", id)
-    }
-    Ok(())
-}
-
-pub fn filter_line(line: &str) -> anyhow::Result<Option<Downloadable>> {
-    // Filter out comments and empty lines
-    if line.starts_with('#') || line.trim().is_empty() {
-        return Ok(None);
-    }
-
-    let line = Line::from(line);
-    match line.cmd {
-        LineCommand::Pick => Ok(None),
-        LineCommand::Drop => ytcc_drop(line.id)
-            .with_context(|| format!("Failed to drop: {}", line.id))
-            .map(|_| None),
-        LineCommand::Watch => Ok(Some(Downloadable {
-            id: Some(line.id),
-            url: line.url,
-        })),
-        LineCommand::Url => {
-            let mut firefox = std::process::Command::new("firefox");
-            firefox.args(["-P", "timesinks.youtube"]);
-            firefox.arg(line.url.as_str());
-            let _handle = firefox.spawn().context("Failed to run firefox")?;
-            Ok(None)
-        }
-    }
-}
diff --git a/pkgs/by-name/yt/yt/src/main.rs b/pkgs/by-name/yt/yt/src/main.rs
new file mode 100644
index 00000000..b89c2eec
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/main.rs
@@ -0,0 +1,126 @@
+use std::fs;
+
+use anyhow::{bail, Context, Result};
+use app::App;
+use clap::Parser;
+use cli::{CacheCommand, CheckCommand};
+use log::info;
+use yt_dlp::wrapper::info_json::InfoJson;
+
+use crate::{cli::Command, storage::subscriptions::get_subscriptions};
+
+pub mod app;
+pub mod cli;
+
+pub mod cache;
+pub mod comments;
+pub mod constants;
+pub mod download;
+pub mod select;
+pub mod status;
+pub mod storage;
+pub mod subscribe;
+pub mod update;
+pub mod watch;
+
+#[tokio::main]
+async fn main() -> Result<()> {
+    let args = cli::Args::parse();
+    stderrlog::new()
+        .module(module_path!())
+        .modules(&["yt_dlp".to_owned(), "libmpv2".to_owned()])
+        .quiet(args.quiet)
+        .show_module_names(false)
+        .color(stderrlog::ColorChoice::Auto)
+        .verbosity(args.verbosity as usize)
+        .timestamp(stderrlog::Timestamp::Off)
+        .init()
+        .expect("Let's just hope that this does not panic");
+
+    let app = App::new().await?;
+
+    match args.command.unwrap_or(Command::Select) {
+        Command::Download { urls } => {
+            if urls.is_empty() {
+                info!("Downloading urls from database");
+
+                download::Downloader::new().consume(&app).await?;
+            } else {
+                info!("Downloading urls: '{:#?}'", urls);
+
+                todo!()
+            }
+        }
+        Command::Select => {
+            select::select(&app).await?;
+        }
+        Command::Subscribe { name, url } => {
+            subscribe::subscribe(name, url)
+                .await
+                .context("Failed to add a subscription")?;
+        }
+        Command::Unsubscribe { name } => {
+            subscribe::unsubscribe(name)
+                .await
+                .context("Failed to remove a subscription")?;
+        }
+        Command::Update {
+            max_backlog,
+            subscriptions,
+        } => {
+            let all_subs = get_subscriptions()?;
+
+            for sub in &subscriptions {
+                if let None = all_subs.0.get(sub) {
+                    bail!(
+                        "Your specified subscription to update '{}' is not a subscription!",
+                        sub
+                    )
+                }
+            }
+
+            update::update(max_backlog, subscriptions).await?;
+        }
+        Command::UpdateOnce {
+            sub_name,
+            max_backlog,
+        } => {
+            update::update_once(&app, sub_name, max_backlog).await?;
+        }
+
+        Command::Subscriptions {} => {
+            let all_subs = get_subscriptions()?;
+            for (key, val) in all_subs.0 {
+                println!("{}: '{}'", key, val.url);
+            }
+        }
+
+        Command::Watch {} => watch::watch(&app).await?,
+
+        Command::Status {} => status::show(&app).await?,
+
+        Command::Cache { command } => match command {
+            CacheCommand::Invalidate => cache::invalidate(&app).await?,
+            CacheCommand::Maintain { all } => cache::maintain(&app, all).await?,
+        },
+
+        Command::Check { command } => match command {
+            CheckCommand::InfoJson { path } => {
+                let string = fs::read_to_string(&path)
+                    .with_context(|| format!("Failed to read '{}' to string!", path.display()))?;
+
+                let _: InfoJson =
+                    serde_json::from_str(&string).context("Failed to deserialize value")?;
+            }
+        },
+        Command::Comments {} => {
+            comments::comments(&app).await?;
+        }
+        Command::Description {} => {
+            todo!()
+            // description::description(&app).await?;
+        }
+    }
+
+    Ok(())
+}
diff --git a/pkgs/by-name/yt/yt/src/select/mod.rs b/pkgs/by-name/yt/yt/src/select/mod.rs
new file mode 100644
index 00000000..abb389f0
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/select/mod.rs
@@ -0,0 +1,122 @@
+use std::{
+    env, fs,
+    io::{BufRead, BufReader, BufWriter, Write},
+    process::Command,
+};
+
+use crate::{
+    app::App,
+    constants::{last_select, HELP_STR},
+    storage::video_database::{getters::get_videos, setters::set_video_status, VideoStatus},
+};
+
+use anyhow::{bail, Context, Result};
+use futures::future::join_all;
+use tempfile::Builder;
+
+use self::selection_file::{filter_line, LineCommand};
+
+pub mod selection_file;
+
+pub async fn select(app: &App) -> Result<()> {
+    let matching_videos = get_videos(
+        app,
+        // TODO: Flag for deciding about dropped inclusion <2024-06-14>
+        &[
+            VideoStatus::Pick,
+            //
+            VideoStatus::Watch,
+            VideoStatus::Cached,
+            VideoStatus::Watched,
+            //
+            VideoStatus::Drop,
+            VideoStatus::Dropped,
+        ],
+    )
+    .await?;
+
+    // Warmup the cache for the display rendering of the videos.
+    // Otherwise the futures would all try to warm it up at the same time.
+    if let Some(vid) = matching_videos.get(0) {
+        let _ = vid.to_select_file_display(app).await?;
+    }
+
+    let lines: Vec<String> = join_all(
+        matching_videos
+            .iter()
+            .map(|vid| async { vid.to_select_file_display(app).await })
+            .collect::<Vec<_>>(),
+    )
+    .await
+    .into_iter()
+    .collect::<Result<Vec<String>>>()?;
+
+    let temp_file = Builder::new()
+        .prefix("yt_video_select-")
+        .suffix(".yts")
+        .rand_bytes(6)
+        .tempfile()
+        .context("Failed to get tempfile")?;
+
+    {
+        let mut edit_file = BufWriter::new(&temp_file);
+
+        lines.iter().for_each(|line| {
+            edit_file
+                .write_all(line.as_bytes())
+                .expect("This write should not fail");
+        });
+
+        edit_file.write_all(HELP_STR.as_bytes())?;
+        edit_file.flush().context("Failed to flush edit file")?;
+
+        let editor = env::var("EDITOR").unwrap_or("nvim".to_owned());
+
+        let mut nvim = Command::new(editor);
+        nvim.arg(temp_file.path());
+        let status = nvim.status().context("Falied to run nvim")?;
+        if !status.success() {
+            bail!("nvim exited with error status: {}", status)
+        }
+    }
+
+    let read_file = temp_file.reopen()?;
+    fs::copy(
+        temp_file.path(),
+        last_select().context("Failed to get the persistent selection file path")?,
+    )
+    .context("Failed to persist selection file")?;
+
+    let reader = BufReader::new(&read_file);
+
+    let mut priority = 1;
+    for line in reader.lines() {
+        let line = line.context("Failed to read a line")?;
+
+        if let Some(line) = filter_line(app, &line)
+            .await
+            .with_context(|| format!("Failed to process line: '{}'", line))?
+        {
+            match line.cmd {
+                LineCommand::Pick => {
+                    set_video_status(app, &line.hash, VideoStatus::Pick, None).await?
+                }
+                LineCommand::Drop => {
+                    set_video_status(app, &line.hash, VideoStatus::Drop, None).await?
+                }
+                LineCommand::Watch => {
+                    set_video_status(app, &line.hash, VideoStatus::Watch, Some(priority)).await?;
+                    priority += 1;
+                }
+                LineCommand::Url => {
+                    let mut firefox = std::process::Command::new("firefox");
+                    firefox.args(["-P", "timesinks.youtube"]);
+                    firefox.arg(line.url.as_str());
+                    let _handle = firefox.spawn().context("Failed to run firefox")?;
+                }
+            }
+        }
+    }
+
+    Ok(())
+}
diff --git a/pkgs/by-name/yt/yt/src/select/selection_file/display.rs b/pkgs/by-name/yt/yt/src/select/selection_file/display.rs
new file mode 100644
index 00000000..8a58ffdd
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/select/selection_file/display.rs
@@ -0,0 +1,82 @@
+use std::fmt::Write;
+
+use anyhow::Result;
+use chrono::DateTime;
+use log::debug;
+
+use crate::{app::App, select::selection_file::duration::Duration, storage::video_database::Video};
+
+macro_rules! c {
+    ($color:expr, $format:expr) => {
+        format!("\x1b[{}m{}\x1b[0m", $color, $format)
+    };
+}
+
+impl Video {
+    pub async fn to_select_file_display(&self, app: &App) -> Result<String> {
+        let mut f = String::new();
+
+        let publish_date = if let Some(date) = self.publish_date {
+            DateTime::from_timestamp(date, 0)
+                .expect("This should not fail")
+                .format("%Y-%m-%d")
+                .to_string()
+        } else {
+            "[No release date]".to_owned()
+        };
+
+        let parent_subscription_name = if let Some(sub) = &self.parent_subscription_name {
+            sub.replace('"', "'")
+        } else {
+            "[No author]".to_owned()
+        };
+
+        debug!("Formatting video for selection file: {}", self.title);
+        write!(
+            f,
+            r#"{} {} "{}" "{}" "{}" "{}" "{}"{}"#,
+            self.status.as_command(),
+            self.extractor_hash.format(app).await?,
+            self.title.replace(['"', '„', '”'], "'"),
+            publish_date,
+            parent_subscription_name,
+            Duration::from(self.duration),
+            self.url.as_str().replace('"', "'"),
+            "\n"
+        )?;
+
+        Ok(f)
+    }
+
+    pub fn to_color_display(&self) -> String {
+        let mut f = String::new();
+
+        let publish_date = if let Some(date) = self.publish_date {
+            DateTime::from_timestamp(date, 0)
+                .expect("This should not fail")
+                .format("%Y-%m-%d")
+                .to_string()
+        } else {
+            "[No release date]".to_owned()
+        };
+
+        let parent_subscription_name = if let Some(sub) = &self.parent_subscription_name {
+            sub.replace('"', "'")
+        } else {
+            "[No author]".to_owned()
+        };
+
+        write!(
+            f,
+            r#"{} {} {} {} {}"#,
+            c!("31;1", self.status.as_command()),
+            c!("32;1", self.title.replace(['"', '„', '”'], "'")),
+            c!("37;1", publish_date),
+            c!("34;1", parent_subscription_name),
+            c!("35;1", Duration::from(self.duration)),
+        )
+        .expect("This write should always work");
+
+        f
+    }
+}
diff --git a/pkgs/by-name/yt/yt/src/select/selection_file/duration.rs b/pkgs/by-name/yt/yt/src/select/selection_file/duration.rs
new file mode 100644
index 00000000..700d9202
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/select/selection_file/duration.rs
@@ -0,0 +1,60 @@
+pub struct Duration {
+    time: u32,
+}
+
+impl From<&str> for Duration {
+    fn from(v: &str) -> Self {
+        let buf: Vec<_> = v.split(':').take(2).collect();
+        Self {
+            time: (buf[0].parse::<u32>().expect("Should be a number") * 60)
+                + buf[1].parse::<u32>().expect("Should be a number"),
+        }
+    }
+}
+
+impl From<Option<f64>> for Duration {
+    fn from(value: Option<f64>) -> Self {
+        Self {
+            time: value.unwrap_or(0.0).ceil() as u32,
+        }
+    }
+}
+
+impl std::fmt::Display for Duration {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
+        const SECOND: u32 = 1;
+        const MINUTE: u32 = 60 * SECOND;
+        const HOUR: u32 = 60 * MINUTE;
+
+        let base_hour = self.time - (self.time % HOUR);
+        let base_min = (self.time % HOUR) - ((self.time % HOUR) % MINUTE);
+        let base_sec = (self.time % HOUR) % MINUTE;
+
+        let h = base_hour / HOUR;
+        let m = base_min / MINUTE;
+        let s = base_sec / SECOND;
+
+        if self.time == 0 {
+            write!(f, "[No Duration]")
+        } else if h > 0 {
+            write!(f, "[{h}h {m}m]")
+        } else {
+            write!(f, "[{m}m {s}s]")
+        }
+    }
+}
+#[cfg(test)]
+mod test {
+    use super::Duration;
+
+    #[test]
+    fn test_display_duration_1h() {
+        let dur = Duration { time: 60 * 60 };
+        assert_eq!("[1h 0m]".to_owned(), dur.to_string());
+    }
+    #[test]
+    fn test_display_duration_30min() {
+        let dur = Duration { time: 60 * 30 };
+        assert_eq!("[30m 0s]".to_owned(), dur.to_string());
+    }
+}
diff --git a/pkgs/by-name/yt/yt/src/help.str b/pkgs/by-name/yt/yt/src/select/selection_file/help.str
index 130fe42a..130fe42a 100644
--- a/pkgs/by-name/yt/yt/src/help.str
+++ b/pkgs/by-name/yt/yt/src/select/selection_file/help.str
diff --git a/pkgs/by-name/yt/yt/src/select/selection_file/mod.rs b/pkgs/by-name/yt/yt/src/select/selection_file/mod.rs
new file mode 100644
index 00000000..957fcd08
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/select/selection_file/mod.rs
@@ -0,0 +1,79 @@
+//! The data structures needed to express the file, which the user edits
+
+use anyhow::{bail, Context};
+use url::Url;
+
+use crate::{app::App, storage::video_database::extractor_hash::ExtractorHash};
+
+pub mod display;
+pub mod duration;
+
+pub enum LineCommand {
+    Pick,
+    Drop,
+    Watch,
+    Url,
+}
+
+impl std::str::FromStr for LineCommand {
+    type Err = anyhow::Error;
+    fn from_str(v: &str) -> Result<Self, <Self as std::str::FromStr>::Err> {
+        match v {
+            "pick" | "p" => Ok(Self::Pick),
+            "drop" | "d" => Ok(Self::Drop),
+            "watch" | "w" => Ok(Self::Watch),
+            "url" | "u" => Ok(Self::Url),
+            other => bail!("'{}' is not a recognized command!", other),
+        }
+    }
+}
+
+pub struct Line {
+    pub cmd: LineCommand,
+    pub hash: ExtractorHash,
+    pub url: Url,
+}
+
+impl Line {
+    pub async fn from_str(app: &App, s: &str) -> anyhow::Result<Self> {
+        let buf: Vec<_> = s.split_whitespace().collect();
+
+        let url_as_str = buf
+            .last()
+            .with_context(|| format!("The line '{}' misses it's url field!'", s))?
+            .trim_matches('"');
+
+        let url: Url = Url::parse(url_as_str)
+            .with_context(|| format!("The url '{}' could not be parsed!", url_as_str))?;
+
+        Ok(Line {
+            cmd: buf
+                .get(0)
+                .with_context(|| format!("The line '{}' is missing it's command!", s))?
+                .parse()?,
+            hash: ExtractorHash::parse_from_short_version(
+                app,
+                buf.get(1)
+                    .with_context(|| format!("The line '{}' is missing it's blake3 hash!", s))?,
+            )
+            .await
+            .with_context(|| {
+                format!(
+                    "Can't parse '{}' as blake3 hash!",
+                    buf.get(1).expect("Already checked"),
+                )
+            })?,
+            url,
+        })
+    }
+}
+
+pub async fn filter_line(app: &App, line: &str) -> anyhow::Result<Option<Line>> {
+    // Filter out comments and empty lines
+    if line.starts_with('#') || line.trim().is_empty() {
+        return Ok(None);
+    }
+
+    let line: Line = Line::from_str(app, line).await?;
+    Ok(Some(line))
+}
diff --git a/pkgs/by-name/yt/yt/src/status/mod.rs b/pkgs/by-name/yt/yt/src/status/mod.rs
new file mode 100644
index 00000000..82f75c8d
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/status/mod.rs
@@ -0,0 +1,50 @@
+use anyhow::Result;
+
+use crate::{
+    app::App,
+    storage::{
+        subscriptions::get_subscriptions,
+        video_database::{getters::get_videos, VideoStatus},
+    },
+};
+
+pub async fn show(app: &App) -> Result<()> {
+    let pick_videos = get_videos(app, &[VideoStatus::Pick]).await?;
+
+    let watch_videos = get_videos(app, &[VideoStatus::Watch]).await?;
+    let cached_videos = get_videos(app, &[VideoStatus::Cached]).await?;
+    let watched_videos = get_videos(app, &[VideoStatus::Watched]).await?;
+
+    let drop_videos = get_videos(app, &[VideoStatus::Drop]).await?;
+    let dropped_videos = get_videos(app, &[VideoStatus::Dropped]).await?;
+
+    // lengths
+    let picked_videos_len = pick_videos.len();
+
+    let watch_videos_len = watch_videos.len();
+    let cached_videos_len = cached_videos.len();
+    let watched_videos_len = watched_videos.len();
+
+    let drop_videos_len = drop_videos.len();
+    let dropped_videos_len = dropped_videos.len();
+
+    let subscriptions = get_subscriptions()?;
+    let subscriptions_len = subscriptions.0.len();
+
+    println!(
+        "\
+Picked   Videos: {picked_videos_len}
+
+Watch    Videos: {watch_videos_len}
+Cached   Videos: {cached_videos_len}
+Watched  Videos: {watched_videos_len}
+
+Drop     Videos: {drop_videos_len}
+Dropped  Videos: {dropped_videos_len}
+
+
+  Subscriptions: {subscriptions_len}"
+    );
+
+    Ok(())
+}
diff --git a/pkgs/by-name/yt/yt/src/storage/mod.rs b/pkgs/by-name/yt/yt/src/storage/mod.rs
new file mode 100644
index 00000000..87257f00
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/storage/mod.rs
@@ -0,0 +1,2 @@
+pub mod subscriptions;
+pub mod video_database;
diff --git a/pkgs/by-name/yt/yt/src/storage/subscriptions.rs b/pkgs/by-name/yt/yt/src/storage/subscriptions.rs
new file mode 100644
index 00000000..13ec493b
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/storage/subscriptions.rs
@@ -0,0 +1,125 @@
+//! Handle subscriptions
+
+use std::{
+    collections::HashMap,
+    fs::{self, File},
+};
+
+use anyhow::{bail, Context, Result};
+use log::{debug, warn};
+use serde::{Deserialize, Serialize};
+use serde_json::{json, Value};
+use url::Url;
+use yt_dlp::wrapper::info_json::InfoType;
+
+use crate::constants;
+
+#[derive(Deserialize, Serialize, Clone, Debug)]
+pub struct Subscription {
+    /// The human readable name of this subscription
+    pub name: String,
+
+    /// The URL this subscription subscribes to
+    pub url: Url,
+}
+
+impl Subscription {
+    pub fn new(name: String, url: Url) -> Self {
+        Self { name, url }
+    }
+}
+
+/// Check whether an URL could be used as a subscription URL
+pub async fn check_url(url: &Url) -> Result<bool> {
+    let yt_opts = match json!( {
+        "playliststart": 1,
+        "playlistend": 10,
+        "noplaylist": false,
+        "extract_flat": "in_playlist",
+    }) {
+        Value::Object(map) => map,
+        _ => unreachable!("This is hardcoded"),
+    };
+
+    let info = yt_dlp::extract_info(&yt_opts, url, false, false).await?;
+
+    debug!("{:#?}", info);
+
+    Ok(info._type == Some(InfoType::Playlist))
+}
+
+#[derive(Deserialize, Serialize, Default)]
+pub struct Subscriptions(pub(crate) HashMap<String, Subscription>);
+
+/// Get a list of subscriptions
+pub fn get_subscriptions() -> Result<Subscriptions> {
+    let subscriptions_path = constants::subscriptions()?;
+
+    if subscriptions_path.exists() {
+        let subscriptions_file = File::open(&subscriptions_path).with_context(|| {
+            format!(
+                "Failed to open the subscription file at: '{}'",
+                subscriptions_path.display()
+            )
+        })?;
+
+        let subscriptions = serde_json::from_reader(subscriptions_file)
+            .context("Failed to deserialize the subscriptions file.")?;
+
+        Ok(subscriptions)
+    } else {
+        warn!("No subscriptions file found!");
+        return Ok(Subscriptions::default());
+    }
+}
+
+pub fn write_subscriptions(subs: Subscriptions) -> Result<()> {
+    let subscriptions_path = constants::subscriptions()?;
+
+    fs::create_dir_all(subscriptions_path.parent().expect("Should have a parent"))?;
+
+    let subscriptions_file = File::create(&subscriptions_path).with_context(|| {
+        format!(
+            "Failed to create the subscription file at: '{}'",
+            subscriptions_path.display()
+        )
+    })?;
+
+    serde_json::to_writer(subscriptions_file, &subs)
+        .context("Failed to serialize and write the subscriptions file.")?;
+
+    Ok(())
+}
+
+pub async fn remove_subscription(sub: &Subscription) -> Result<()> {
+    let mut present_subscriptions = get_subscriptions()?;
+
+    let string = format!("Unsubscribed from '{}' at '{}'", sub.name, sub.url);
+
+    if let None = present_subscriptions.0.remove(&sub.name) {
+        bail!(
+            "The subscription '{}' was not in your subscription list!",
+            sub.name
+        );
+    }
+
+    write_subscriptions(present_subscriptions)?;
+
+    println!("{}", string);
+
+    Ok(())
+}
+
+pub async fn add_subscription(sub: Subscription) -> Result<()> {
+    let mut present_subscriptions = get_subscriptions()?;
+
+    let string = format!("Subscribed to {} at {}", sub.name, sub.url);
+
+    present_subscriptions.0.insert(sub.name.clone(), sub);
+
+    write_subscriptions(present_subscriptions)?;
+
+    println!("{}", string);
+
+    Ok(())
+}
diff --git a/pkgs/by-name/yt/yt/src/storage/video_database/downloader.rs b/pkgs/by-name/yt/yt/src/storage/video_database/downloader.rs
new file mode 100644
index 00000000..5c472ac5
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/storage/video_database/downloader.rs
@@ -0,0 +1,180 @@
+use std::path::{Path, PathBuf};
+
+use anyhow::Result;
+use log::debug;
+use sqlx::query;
+use url::Url;
+
+use crate::{app::App, storage::video_database::VideoStatus};
+
+use super::{ExtractorHash, Video};
+
+/// Returns to next video which should be downloaded. This respects the priority assigned by select.
+/// It does not return videos, which are already cached.
+pub async fn get_next_uncached_video(app: &App) -> Result<Option<Video>> {
+    let result = query!(
+        r#"
+        SELECT *
+        FROM videos
+        WHERE status = 'Watching' AND cache_path IS NULL
+        ORDER BY priority ASC
+        LIMIT 1;
+    "#
+    )
+    .fetch_one(&app.database)
+    .await;
+
+    if let Err(sqlx::Error::RowNotFound) = result {
+        Ok(None)
+    } else {
+        let base = result?;
+
+        let thumbnail_url = if let Some(url) = &base.thumbnail_url {
+            Some(Url::parse(&url)?)
+        } else {
+            None
+        };
+
+        let status_change = if base.status_change == 1 {
+            true
+        } else {
+            assert_eq!(base.status_change, 0, "Can only be 1 or 0");
+            false
+        };
+
+        let video = Video {
+            cache_path: base.cache_path.as_ref().map(|val| PathBuf::from(val)),
+            description: base.description.clone(),
+            duration: base.duration,
+            extractor_hash: ExtractorHash::new(base.extractor_hash.parse()?),
+            last_status_change: base.last_status_change,
+            parent_subscription_name: base.parent_subscription_name.clone(),
+            priority: base.priority,
+            publish_date: base.publish_date,
+            status: VideoStatus::from_db_integer(base.status),
+            status_change,
+            thumbnail_url,
+            title: base.title.clone(),
+            url: Url::parse(&base.url)?,
+        };
+
+        Ok(Some(video))
+    }
+}
+
+/// Returns to next video which can be watched (i.e. is cached).
+/// This respects the priority assigned by select.
+pub async fn get_next_video_watchable(app: &App) -> Result<Option<Video>> {
+    let result = query!(
+        r#"
+        SELECT *
+        FROM videos
+        WHERE status = 'Watching' AND cache_path IS NOT NULL
+        ORDER BY priority ASC
+        LIMIT 1;
+    "#
+    )
+    .fetch_one(&app.database)
+    .await;
+
+    if let Err(sqlx::Error::RowNotFound) = result {
+        Ok(None)
+    } else {
+        let base = result?;
+
+        let thumbnail_url = if let Some(url) = &base.thumbnail_url {
+            Some(Url::parse(&url)?)
+        } else {
+            None
+        };
+
+        let status_change = if base.status_change == 1 {
+            true
+        } else {
+            assert_eq!(base.status_change, 0, "Can only be 1 or 0");
+            false
+        };
+
+        let video = Video {
+            cache_path: base.cache_path.as_ref().map(|val| PathBuf::from(val)),
+            description: base.description.clone(),
+            duration: base.duration,
+            extractor_hash: ExtractorHash::new(base.extractor_hash.parse()?),
+            last_status_change: base.last_status_change,
+            parent_subscription_name: base.parent_subscription_name.clone(),
+            priority: base.priority,
+            publish_date: base.publish_date,
+            status: VideoStatus::from_db_integer(base.status),
+            status_change,
+            thumbnail_url,
+            title: base.title.clone(),
+            url: Url::parse(&base.url)?,
+        };
+
+        Ok(Some(video))
+    }
+}
+
+/// Update the cached path of a video. Will be set to NULL if the path is None
+pub async fn set_video_cache_path(app: &App, video: &Video, path: Option<&Path>) -> Result<()> {
+    debug!(
+        "Setting cache path from '{}' to '{:#?}'",
+        video.title,
+        path.unwrap_or(&PathBuf::from("None")).display()
+    );
+
+    if let Some(path) = path {
+        debug!(
+            "Setting cache path from '{}' to '{}'",
+            video.title,
+            path.display()
+        );
+
+        let path_str = path.display().to_string();
+        let extractor_hash = video.extractor_hash.0.to_string();
+
+        query!(
+            r#"
+            UPDATE videos
+            SET cache_path = ?
+            WHERE extractor_hash = ?;
+        "#,
+            path_str,
+            extractor_hash
+        )
+        .execute(&app.database)
+        .await?;
+
+        Ok(())
+    } else {
+        let extractor_hash = video.extractor_hash.0.to_string();
+
+        query!(
+            r#"
+            UPDATE videos
+            SET cache_path = NULL
+            WHERE extractor_hash = ?;
+        "#,
+            extractor_hash
+        )
+        .execute(&app.database)
+        .await?;
+
+        Ok(())
+    }
+}
+
+/// Returns the number of cached videos
+pub async fn get_allocated_cache(app: &App) -> Result<u32> {
+    let count = query!(
+        r#"
+        SELECT COUNT(cache_path) as count
+        FROM videos
+        WHERE cache_path IS NOT NULL;
+"#,
+    )
+    .fetch_one(&app.database)
+    .await?;
+
+    Ok(count.count as u32)
+}
diff --git a/pkgs/by-name/yt/yt/src/storage/video_database/extractor_hash.rs b/pkgs/by-name/yt/yt/src/storage/video_database/extractor_hash.rs
new file mode 100644
index 00000000..e90a5277
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/storage/video_database/extractor_hash.rs
@@ -0,0 +1,106 @@
+use std::{collections::HashMap, fmt::Display};
+
+use anyhow::{bail, Result};
+use blake3::Hash;
+use log::debug;
+use tokio::sync::OnceCell;
+
+use crate::{app::App, storage::video_database::getters::get_all_hashes};
+
+static EXTRACTOR_HASH_LENGTH: OnceCell<usize> = OnceCell::const_new();
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct ExtractorHash(pub(super) Hash);
+
+impl Display for ExtractorHash {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        self.0.fmt(f)
+    }
+}
+
+impl ExtractorHash {
+    pub fn new(hash: Hash) -> Self {
+        Self(hash)
+    }
+
+    pub fn parse_from_full_version(s: &str) -> Result<Self> {
+        assert_eq!(s.len(), 64);
+
+        let hash = s.parse()?;
+        Ok(Self::new(hash))
+    }
+
+    pub async fn parse_from_short_version(app: &App, s: &str) -> Result<Self> {
+        let all_hashes = get_all_hashes(app).await?;
+
+        let needed_chars = s.len();
+
+        for hash in all_hashes {
+            if &hash.to_hex()[..needed_chars] == s {
+                return Ok(Self::new(hash));
+            }
+        }
+
+        bail!("Your shortend hash, does not match a real hash (this is probably a bug)!");
+    }
+
+    async fn get_needed_char_len(&self, app: &App) -> Result<usize> {
+        debug!("Calculating the needed hash char length");
+        let all_hashes = get_all_hashes(app).await?;
+
+        let all_char_vec_hashes = all_hashes
+            .into_iter()
+            .map(|hash| hash.to_hex().chars().collect::<Vec<char>>())
+            .collect::<Vec<Vec<_>>>();
+
+        // This value should be updated later, if not rust will panic in the assertion.
+        let mut needed_chars: usize = 1000;
+        'outer: for i in 1..64 {
+            let i_chars: Vec<String> = all_char_vec_hashes
+                .iter()
+                .map(|vec| vec.iter().take(i).collect::<String>())
+                .collect();
+
+            let mut uniqnes_hashmap: HashMap<String, ()> = HashMap::new();
+            for ch in i_chars {
+                if let Some(()) = uniqnes_hashmap.insert(ch, ()) {
+                    // The key was already in the hash map, thus we have a duplicated char and need
+                    // at least one char more
+                    continue 'outer;
+                }
+            }
+
+            needed_chars = i;
+            break 'outer;
+        }
+
+        assert!(needed_chars <= 64, "Hashes are only 64 bytes long");
+
+        Ok(needed_chars)
+    }
+
+    pub async fn format(&self, app: &App) -> Result<String> {
+        let needed_chars = if let Some(needed_chars) = EXTRACTOR_HASH_LENGTH.get() {
+            debug!("Using cached char length: {}", needed_chars);
+            *needed_chars
+        } else {
+            let needed_chars = self.get_needed_char_len(app).await?;
+            debug!("Setting the needed has char lenght.");
+            EXTRACTOR_HASH_LENGTH
+                .set(needed_chars)
+                .expect("This should work at this stage");
+
+            needed_chars
+        };
+
+        debug!("Formatting a hash with char length: {}", needed_chars);
+
+        Ok(self
+            .0
+            .to_hex()
+            .chars()
+            .into_iter()
+            .take(needed_chars)
+            .collect::<String>())
+    }
+}
diff --git a/pkgs/by-name/yt/yt/src/storage/video_database/getters.rs b/pkgs/by-name/yt/yt/src/storage/video_database/getters.rs
new file mode 100644
index 00000000..6685603c
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/storage/video_database/getters.rs
@@ -0,0 +1,176 @@
+//! These functions interact with the storage db in a read-only way. They are added on-demaned (as
+//! you could theoretically just could do everything with the `get_videos` function), as
+//! performance or convince requires.
+use std::{
+    fs::{File},
+    path::PathBuf,
+};
+
+use anyhow::{bail, Context, Result};
+use blake3::Hash;
+use log::debug;
+use sqlx::{query, QueryBuilder, Row, Sqlite};
+use url::Url;
+use yt_dlp::wrapper::info_json::InfoJson;
+
+use crate::{
+    app::App,
+    storage::{
+        subscriptions::Subscription,
+        video_database::{extractor_hash::ExtractorHash, Video},
+    },
+};
+
+use super::VideoStatus;
+
+/// Get the lines to display at the selection file
+pub async fn get_videos(app: &App, allowed_states: &[VideoStatus]) -> Result<Vec<Video>> {
+    let mut qb: QueryBuilder<Sqlite> = QueryBuilder::new(
+        "\
+    SELECT *
+    FROM videos
+    WHERE status IN ",
+    );
+
+    qb.push("(");
+    allowed_states
+        .iter()
+        .enumerate()
+        .for_each(|(index, state)| {
+            qb.push("'");
+            qb.push(state.as_db_integer());
+            qb.push("'");
+
+            if index != allowed_states.len() - 1 {
+                qb.push(",");
+            }
+        });
+    qb.push(")");
+
+    qb.push("\n    ORDER BY priority DESC;");
+
+    debug!("Will run: \"{}\"", qb.sql());
+
+    let videos = qb.build().fetch_all(&app.database).await.with_context(|| {
+        format!(
+            "Failed to query videos with states: '{}'",
+            allowed_states.iter().fold(String::new(), |mut acc, state| {
+                acc.push(' ');
+                acc.push_str(&state.as_str());
+                acc
+            }),
+        )
+    })?;
+
+    let real_videos: Vec<Video> = videos
+        .iter()
+        .map(|base| -> Result<Video> {
+            let thumbnail_url = if let Some(url) = base.get("thumbnail_url") {
+                Some(Url::parse(url)?)
+            } else {
+                None
+            };
+            Ok(Video {
+                cache_path: base
+                    .get::<Option<String>, &str>("cache_path")
+                    .as_ref()
+                    .map(|val| PathBuf::from(val)),
+                description: base.get::<Option<String>, &str>("description").clone(),
+                duration: base.get("duration"),
+                extractor_hash: ExtractorHash::parse_from_full_version(
+                    &base.get::<String, &str>("extractor_hash"),
+                )?,
+                last_status_change: base.get("last_status_change"),
+                parent_subscription_name: base
+                    .get::<Option<String>, &str>("parent_subscription_name")
+                    .clone(),
+                publish_date: base.get("publish_date"),
+                status: VideoStatus::from_db_integer(base.get("status")),
+                thumbnail_url,
+                title: base.get::<String, &str>("title").to_owned(),
+                url: Url::parse(base.get("url"))?,
+                priority: base.get("priority"),
+                status_change: base.get("status_change"),
+            })
+        })
+        .collect::<Result<Vec<Video>>>()?;
+
+    Ok(real_videos)
+}
+
+pub async fn get_video_info_json(video: &Video) -> Result<Option<InfoJson>> {
+    if let Some(mut path) = video.cache_path.clone() {
+        if !path.set_extension("info.json") {
+            bail!(
+                "Failed to change path extension to 'info.json': {}",
+                path.display()
+            );
+        }
+        let info_json_string = File::open(path)?;
+        let info_json: InfoJson = serde_json::from_reader(&info_json_string)?;
+
+        Ok(Some(info_json))
+    } else {
+        Ok(None)
+    }
+}
+
+pub async fn get_currently_playing_video(app: &App) -> Result<Option<Video>> {
+    let mut videos: Vec<Video> = get_changing_videos(app, VideoStatus::Cached).await?;
+
+    if videos.is_empty() {
+        Ok(None)
+    } else {
+        assert_eq!(
+            videos.len(),
+            1,
+            "Only one video can change from cached to watched at once!"
+        );
+
+        Ok(Some(videos.remove(0)))
+    }
+}
+
+pub async fn get_changing_videos(app: &App, old_state: VideoStatus) -> Result<Vec<Video>> {
+    todo!()
+}
+
+pub async fn get_all_hashes(app: &App) -> Result<Vec<Hash>> {
+    let hashes_hex = query!(
+        r#"
+        SELECT extractor_hash
+        FROM videos;
+    "#
+    )
+    .fetch_all(&app.database)
+    .await?;
+
+    Ok(hashes_hex
+        .iter()
+        .map(|hash| {
+            Hash::from_hex(&hash.extractor_hash)
+                .expect("These values started as blake3 hashes, they should stay blake3 hashes")
+        })
+        .collect())
+}
+
+pub async fn get_video_hashes(app: &App, subs: &Subscription) -> Result<Vec<Hash>> {
+    let hashes_hex = query!(
+        r#"
+        SELECT extractor_hash
+        FROM videos
+        WHERE parent_subscription_name = ?;
+    "#,
+        subs.name
+    )
+    .fetch_all(&app.database)
+    .await?;
+
+    Ok(hashes_hex
+        .iter()
+        .map(|hash| {
+            Hash::from_hex(&hash.extractor_hash)
+                .expect("These values started as blake3 hashes, they should stay blake3 hashes")
+        })
+        .collect())
+}
diff --git a/pkgs/by-name/yt/yt/src/storage/video_database/mod.rs b/pkgs/by-name/yt/yt/src/storage/video_database/mod.rs
new file mode 100644
index 00000000..a565fc8d
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/storage/video_database/mod.rs
@@ -0,0 +1,115 @@
+use std::path::PathBuf;
+
+use url::Url;
+
+use crate::storage::video_database::extractor_hash::ExtractorHash;
+
+pub mod downloader;
+pub mod extractor_hash;
+pub mod getters;
+pub mod setters;
+
+#[derive(Debug)]
+pub struct Video {
+    pub cache_path: Option<PathBuf>,
+    pub description: Option<String>,
+    pub duration: Option<f64>,
+    pub extractor_hash: ExtractorHash,
+    pub last_status_change: i64,
+    /// The associated subscription this video was fetched from (null, when the video was `add`ed)
+    pub parent_subscription_name: Option<String>,
+    pub priority: i64,
+    pub publish_date: Option<i64>,
+    pub status: VideoStatus,
+    /// The video is currently changing its state (for example from being `SELECT` to being `CACHE`)
+    pub status_change: bool,
+    pub thumbnail_url: Option<Url>,
+    pub title: String,
+    pub url: Url,
+}
+
+/// # Video Lifetime (words in <brackets> are commands):
+///      <Pick>
+///     /    \
+/// <Watch>   <Drop> -> Dropped // yt select
+///     |
+/// Cache                       // yt cache
+///     |
+/// Watched                     // yt watch
+#[derive(Default, Debug)]
+pub enum VideoStatus {
+    #[default]
+    Pick,
+
+    /// The video has been select to be watched
+    Watch,
+    /// The video has been cached and is ready to be watched
+    Cached,
+    /// The video has been watched
+    Watched,
+
+    /// The video has been select to be dropped
+    Drop,
+    /// The video has been dropped
+    Dropped,
+}
+
+impl VideoStatus {
+    pub fn as_command(&self) -> &str {
+        // NOTE: Keep the serialize able variants synced with the main `select` function <2024-06-14>
+        match self {
+            VideoStatus::Pick => "pick",
+
+            VideoStatus::Watch => "watch",
+            VideoStatus::Cached => "watch",
+            VideoStatus::Watched => "watch",
+
+            VideoStatus::Drop => "drop",
+            VideoStatus::Dropped => "drop",
+        }
+    }
+
+    pub fn as_db_integer(&self) -> i64 {
+        // These numbers should not change their mapping!
+        // Oh, and keep them in sync with the SQLite check constraint.
+        match self {
+            VideoStatus::Pick => 0,
+
+            VideoStatus::Watch => 1,
+            VideoStatus::Cached => 2,
+            VideoStatus::Watched => 3,
+
+            VideoStatus::Drop => 4,
+            VideoStatus::Dropped => 5,
+        }
+    }
+    pub fn from_db_integer(num: i64) -> Self {
+        match num {
+            0 => Self::Pick,
+
+            1 => Self::Watch,
+            2 => Self::Cached,
+            3 => Self::Watched,
+
+            4 => Self::Drop,
+            5 => Self::Dropped,
+            other => unreachable!(
+                "The database returned a enum discriminator, unknown to us: '{}'",
+                other
+            ),
+        }
+    }
+
+    pub fn as_str(&self) -> &'static str {
+        match self {
+            VideoStatus::Pick => "Pick",
+
+            VideoStatus::Watch => "Watch",
+            VideoStatus::Cached => "Cache",
+            VideoStatus::Watched => "Watched",
+
+            VideoStatus::Drop => "Drop",
+            VideoStatus::Dropped => "Dropped",
+        }
+    }
+}
diff --git a/pkgs/by-name/yt/yt/src/storage/video_database/schema.sql b/pkgs/by-name/yt/yt/src/storage/video_database/schema.sql
new file mode 100644
index 00000000..e4d1e514
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/storage/video_database/schema.sql
@@ -0,0 +1,17 @@
+-- The base schema
+-- Keep this table in sync with the `Video` structure
+CREATE TABLE IF NOT EXISTS videos (
+    cache_path                  TEXT UNIQUE,
+    description                 TEXT,
+    duration                    FLOAT,
+    extractor_hash              TEXT UNIQUE NOT NULL PRIMARY KEY,
+    last_status_change          INTEGER        NOT NULL,
+    parent_subscription_name    TEXT,
+    priority                    INTEGER        NOT NULL DEFAULT 0,
+    publish_date                INTEGER,
+    status                      INTEGER        NOT NULL CHECK (status IN (0, 1, 2, 3, 4, 5)),
+    status_change               INTEGER        NOT NULL CHECK (status_change IN (0, 1)),
+    thumbnail_url               TEXT,
+    title                       TEXT        NOT NULL,
+    url                         TEXT UNIQUE NOT NULL
+);
diff --git a/pkgs/by-name/yt/yt/src/storage/video_database/setters.rs b/pkgs/by-name/yt/yt/src/storage/video_database/setters.rs
new file mode 100644
index 00000000..4f1d98cf
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/storage/video_database/setters.rs
@@ -0,0 +1,127 @@
+//! These functions change the database. They are added on a demand basis.
+
+use anyhow::Result;
+use chrono::Utc;
+use sqlx::query;
+
+use crate::{app::App, storage::video_database::extractor_hash::ExtractorHash};
+
+use super::{Video, VideoStatus};
+
+/// Set a new status for a video.
+/// This will only update the status time stamp/priority when the status or the priority has changed .
+pub async fn set_video_status(
+    app: &App,
+    video_hash: &ExtractorHash,
+    new_status: VideoStatus,
+    new_priority: Option<i64>,
+) -> Result<()> {
+    let video_hash = video_hash.0.to_string();
+    let new_status = new_status.as_db_integer();
+
+    let old = query!(
+        r#"
+    SELECT status, priority
+    FROM videos
+    WHERE extractor_hash = ?
+    "#,
+        video_hash
+    )
+    .fetch_one(&app.database)
+    .await?;
+
+    if let Some(new_priority) = new_priority {
+        if old.status == new_status && old.priority == new_priority {
+            return Ok(());
+        }
+
+        let now = Utc::now().timestamp();
+
+        query!(
+            r#"
+        UPDATE videos
+        SET status = ?, last_status_change = ?, priority = ?
+        WHERE extractor_hash = ?;
+        "#,
+            new_status,
+            now,
+            new_priority,
+            video_hash
+        )
+        .execute(&app.database)
+        .await?;
+    } else {
+        if old.status == new_status {
+            return Ok(());
+        }
+
+        let now = Utc::now().timestamp();
+
+        query!(
+            r#"
+        UPDATE videos
+        SET status = ?, last_status_change = ?
+        WHERE extractor_hash = ?;
+        "#,
+            new_status,
+            now,
+            video_hash
+        )
+        .execute(&app.database)
+        .await?;
+    }
+
+    Ok(())
+}
+
+pub async fn set_state_change(
+    app: &App,
+    video_extractor_hash: &ExtractorHash,
+    changing: bool,
+) -> Result<()> {
+    let state_change = if changing { 1 } else { 0 };
+    let video_extractor_hash = video_extractor_hash.to_string();
+
+    query!(
+        r#"
+            UPDATE videos
+            SET status_change = ?
+            WHERE extractor_hash = ?;
+        "#,
+        state_change,
+        video_extractor_hash,
+    )
+    .execute(&app.database)
+    .await?;
+
+    Ok(())
+}
+
+pub async fn add_video(app: &App, video: Video) -> Result<()> {
+    let parent_subscription_name = if let Some(subs) = video.parent_subscription_name {
+        subs
+    } else {
+        "NULL".to_owned()
+    };
+
+    let thumbnail_url = if let Some(thum) = video.thumbnail_url {
+        thum.to_string()
+    } else {
+        "NULL".to_owned()
+    };
+
+    let status = video.status.as_db_integer();
+    let url = video.url.to_string();
+    let extractor_hash = video.extractor_hash.0.to_string();
+
+    query!(
+        r#"
+        INSERT INTO videos (parent_subscription_name, status, last_status_change, title, url, description, duration, publish_date, thumbnail_url, extractor_hash)
+        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
+    "#, parent_subscription_name, status, video.last_status_change, video.title, url, video.description, video.duration, video.publish_date, thumbnail_url, extractor_hash
+    )
+    .execute(&app.database)
+    .await?;
+
+    Ok(())
+}
diff --git a/pkgs/by-name/yt/yt/src/subscribe/mod.rs b/pkgs/by-name/yt/yt/src/subscribe/mod.rs
new file mode 100644
index 00000000..88be038a
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/subscribe/mod.rs
@@ -0,0 +1,132 @@
+use anyhow::{bail, Context, Result};
+use futures::FutureExt;
+use log::warn;
+use serde_json::{json, Value};
+use url::Url;
+use yt_dlp::wrapper::info_json::InfoType;
+
+use crate::storage::subscriptions::{
+    add_subscription, check_url, get_subscriptions, remove_subscription, Subscription,
+};
+
+pub async fn unsubscribe(name: String) -> Result<()> {
+    let present_subscriptions = get_subscriptions()?;
+
+    if let Some(subscription) = present_subscriptions.0.get(&name) {
+        remove_subscription(subscription).await?;
+    } else {
+        bail!("Couldn't find subscription: '{}'", &name);
+    }
+
+    Ok(())
+}
+
+pub async fn subscribe(name: Option<String>, url: Url) -> Result<()> {
+    if !(url.as_str().ends_with("videos")
+        || url.as_str().ends_with("streams")
+        || url.as_str().ends_with("shorts"))
+        && url.as_str().contains("youtube.com")
+    {
+        warn!("Your youtbe url does not seem like it actually tracks a channels playlist (videos, streams, shorts). Adding subscriptions for each of them...");
+
+        let url = Url::parse(&(url.as_str().to_owned() + "/"))
+            .expect("This was an url, it should stay one");
+
+        if let Some(name) = name {
+            let out: Result<()> = async move {
+                actual_subscribe(
+                    Some(name.clone() + " {Videos}"),
+                    url.join("videos/").expect("Works"),
+                )
+                .await
+                .with_context(|| {
+                    format!("Failed to subscribe to '{}'", name.clone() + " {Videos}")
+                })?;
+
+                actual_subscribe(
+                    Some(name.clone() + " {Streams}"),
+                    url.join("streams/").expect("Works"),
+                )
+                .await
+                .with_context(|| {
+                    format!("Failed to subscribe to '{}'", name.clone() + " {Streams}")
+                })?;
+
+                actual_subscribe(
+                    Some(name.clone() + " {Shorts}"),
+                    url.join("shorts/").expect("Works"),
+                )
+                .await
+                .with_context(|| format!("Failed to subscribe to '{}'", name + " {Shorts}"))?;
+
+                Ok(())
+            }
+            .boxed()
+            .await;
+
+            out?
+        } else {
+            actual_subscribe(None, url.join("videos/").expect("Works"))
+                .await
+                .with_context(|| format!("Failed to subscribe to the '{}' variant", "{Videos}"))?;
+
+            actual_subscribe(None, url.join("streams/").expect("Works"))
+                .await
+                .with_context(|| format!("Failed to subscribe to the '{}' variant", "{Streams}"))?;
+
+            actual_subscribe(None, url.join("shorts/").expect("Works"))
+                .await
+                .with_context(|| format!("Failed to subscribe to the '{}' variant", "{Shorts}"))?;
+        }
+    } else {
+        actual_subscribe(name, url).await?;
+    }
+
+    Ok(())
+}
+
+async fn actual_subscribe(name: Option<String>, url: Url) -> Result<()> {
+    let name = if let Some(name) = name {
+        if !check_url(&url).await? {
+            bail!("The url ('{}') does not represent a playlist!", &url)
+        };
+
+        name
+    } else {
+        let yt_opts = match json!( {
+            "playliststart": 1,
+            "playlistend": 10,
+            "noplaylist": false,
+            "extract_flat": "in_playlist",
+        }) {
+            Value::Object(map) => map,
+            _ => unreachable!("This is hardcoded"),
+        };
+
+        let info = yt_dlp::extract_info(&yt_opts, &url, false, false).await?;
+
+        if info._type == Some(InfoType::Playlist) {
+            info.title.expect("This should be some for a playlist")
+        } else {
+            bail!("The url ('{}') does not represent a playlist!", &url)
+        }
+    };
+
+    let present_subscriptions = get_subscriptions()?;
+
+    if let Some(subs) = present_subscriptions.0.get(&name) {
+        bail!(
+            "The subscription '{}' could not be added, \
+                as another one with the same name ('{}') already exists. It links to the Url: '{}'",
+            name,
+            name,
+            subs.url
+        );
+    }
+
+    let sub = Subscription { name, url };
+
+    add_subscription(sub).await?;
+
+    Ok(())
+}
diff --git a/pkgs/by-name/yt/yt/src/update/mod.rs b/pkgs/by-name/yt/yt/src/update/mod.rs
new file mode 100644
index 00000000..2f97361d
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/update/mod.rs
@@ -0,0 +1,226 @@
+use std::{env::current_exe, str::FromStr};
+
+use anyhow::{bail, Context, Ok, Result};
+use chrono::{DateTime, Utc};
+use log::{debug, error, info, warn};
+use serde_json::{json, Value};
+use tokio::{process::Command, task::JoinSet};
+use yt_dlp::unsmuggle_url;
+
+use crate::{
+    app::App,
+    storage::{
+        subscriptions::{get_subscriptions, Subscription},
+        video_database::{
+            extractor_hash::ExtractorHash, getters::get_video_hashes, setters::add_video,
+            Video, VideoStatus,
+        },
+    },
+};
+
+pub async fn update(max_backlog: u32, subs_to_update: Vec<String>) -> Result<()> {
+    let subscriptions = get_subscriptions()?;
+
+    let mut join_set = JoinSet::new();
+
+    for key in subscriptions.0.keys() {
+        if subs_to_update.contains(&key) || subs_to_update.is_empty() {
+            let exe_name = current_exe().context("Failed to get the current executable")?;
+
+            let mut child = Command::new(exe_name)
+                // TODO: Add currying of the verbosity flags <2024-07-28>
+                // .arg("-vvvv")
+                .arg("update-once")
+                .arg(&key)
+                .arg(max_backlog.to_string())
+                .spawn()
+                .context("Failed to call yt update-once")?;
+
+            let new_key = key.clone();
+
+            // PERFORMANCE: Switch back to a somewhat parallellied version <2024-07-29>
+            let output = child.wait().await;
+            join_set.spawn(async move {
+                // let output = child.wait().await;
+                (output, new_key)
+            });
+        } else {
+            info!(
+                "Not updating subscription '{}' as it was not specified",
+                key
+            );
+        }
+    }
+
+    while let Some(res) = join_set.join_next().await {
+        let (output, key) = res?;
+
+        debug!("{} finished its update.", &key);
+        match output {
+            std::result::Result::Ok(status) => {
+                if !status.success() {
+                    // This should already be printed as error, so we only print it here as debug.
+                    debug!("A yt update-once invokation failed for subscription: '{key}'")
+                }
+            }
+            Err(err) => {
+                error!("Failed to update subscription ('{key}') because of io error: '{err}'")
+            }
+        }
+    }
+
+    Ok(())
+}
+
+pub async fn update_once(app: &App, sub_name: String, max_backlog: u32) -> Result<()> {
+    let subs = get_subscriptions()?;
+
+    if let Some(sub) = subs.0.get(&sub_name) {
+        if let Err(err) = update_subscription(app, sub, max_backlog).await {
+            error!("Failed to update subscription ('{sub_name}'): {err}")
+        }
+    } else {
+        bail!(
+            "Your subscription name '{}' is not a subscription (This is probably a bug)!",
+            sub_name
+        );
+    }
+
+    Ok(())
+}
+
+async fn update_subscription(app: &App, sub: &Subscription, max_backlog: u32) -> Result<()> {
+    println!("Updating subscription '{}'...", sub.name);
+
+    let yt_opts = match json!( {
+        "playliststart": 1,
+        "playlistend": max_backlog,
+        // "noplaylist": false,
+        "extractor_args": {
+            "youtubetab": {
+                "approximate_date": [""]
+            }
+        }
+    }) {
+        Value::Object(map) => map,
+        _ => unreachable!("This is hardcoded"),
+    };
+
+    macro_rules! unwrap_option {
+        ($option:expr) => {
+            match $option {
+                Some(x) => x,
+                None => anyhow::bail!(concat!(
+                    "Expected a value, but '",
+                    stringify!($option),
+                    "' is None!"
+                )),
+            }
+        };
+    }
+
+    let videos = yt_dlp::extract_info(&yt_opts, &sub.url, false, true)
+        .await
+        .with_context(|| {
+            format!(
+                "Failed to get info for subscription '{}': '{}'",
+                sub.name, sub.url
+            )
+        })?;
+
+    let hashes = get_video_hashes(app, &sub).await?;
+
+    let real_videos = unwrap_option!(videos.entries)
+        .iter()
+        .map(|entry| -> Result<Option<Video>> {
+            let publish_date = if let Some(date) = &entry.upload_date {
+                let year: u32 = date
+                    .chars()
+                    .take(4)
+                    .collect::<String>()
+                    .parse()
+                    .expect("Should work.");
+                let month: u32 = date
+                    .chars()
+                    .skip(4)
+                    .take(2)
+                    .collect::<String>()
+                    .parse()
+                    .expect("Should work");
+                let day: u32 = date
+                    .chars()
+                    .skip(6)
+                    .take(2)
+                    .collect::<String>()
+                    .parse()
+                    .expect("Should work");
+
+                let date_string = format!("{year:04}-{month:02}-{day:02}T00:00:00Z");
+                Some(
+                    DateTime::<Utc>::from_str(&date_string)
+                        .expect("This should always work")
+                        .timestamp(),
+                )
+            } else {
+                warn!(
+                    "The video '{}' lacks it's upload date!",
+                    unwrap_option!(&entry.title)
+                );
+                None
+            };
+
+            let thumbnail_url = match (&entry.thumbnails, &entry.thumbnail) {
+                (None, None) => None,
+                (None, Some(thumbnail)) => Some(thumbnail.to_owned()),
+
+                // TODO: The algorithm is not exactly the best <2024-05-28>
+                (Some(thumbnails), None) => Some(
+                    thumbnails
+                        .get(0)
+                        .expect("At least one should exist")
+                        .url
+                        .clone(),
+                ),
+                (Some(_), Some(thumnail)) => Some(thumnail.to_owned()),
+            };
+
+            let url = {
+                let smug_url: url::Url = unwrap_option!(entry.webpage_url.clone());
+                unsmuggle_url(smug_url)?
+            };
+
+            let extractor_hash = blake3::hash(url.as_str().as_bytes());
+
+            if hashes.contains(&extractor_hash) {
+                // We already stored the video information
+                Ok(None)
+            } else {
+                let video = Video {
+                    cache_path: None,
+                    description: entry.description.clone(),
+                    duration: entry.duration,
+                    extractor_hash: ExtractorHash::new(extractor_hash),
+                    last_status_change: Utc::now().timestamp(),
+                    parent_subscription_name: Some(sub.name.clone()),
+                    priority: 0,
+                    publish_date,
+                    status: VideoStatus::Pick,
+                    status_change: false,
+                    thumbnail_url,
+                    title: unwrap_option!(entry.title.clone()),
+                    url,
+                };
+
+                println!("{}", video.to_color_display());
+                Ok(Some(video))
+            }
+        })
+        .collect::<Result<Vec<Option<Video>>>>()?;
+
+    for video in real_videos {
+        if let Some(video) = video {
+            add_video(app, video).await?;
+        }
+    }
+    Ok(())
+}
diff --git a/pkgs/by-name/yt/yt/src/watch/mod.rs b/pkgs/by-name/yt/yt/src/watch/mod.rs
new file mode 100644
index 00000000..683d49c1
--- /dev/null
+++ b/pkgs/by-name/yt/yt/src/watch/mod.rs
@@ -0,0 +1,97 @@
+use anyhow::Result;
+use libmpv2::{
+    events::{Event, EventContext},
+    Mpv,
+};
+use log::{debug, info};
+
+use crate::{
+    app::App,
+    cache::maintain,
+    comments::get_comments,
+    storage::video_database::{
+        extractor_hash::ExtractorHash, getters::get_videos, setters::set_state_change, VideoStatus,
+    },
+};
+
+pub async fn watch(app: &App) -> Result<()> {
+    maintain(app, false).await?;
+
+    let mpv = Mpv::with_initializer(|mpv| {
+        // Enable default key bindings, so the user can actually interact with
+        // the player (and e.g. close the window).
+        mpv.set_property("input-default-bindings", "yes")?;
+        mpv.set_property("input-vo-keyboard", "yes")?;
+        // Show the on screen controller.
+        mpv.set_property("osc", "yes")?;
+        Ok(())
+    })?;
+
+    let mut ev_ctx = EventContext::new(mpv.ctx);
+    ev_ctx.disable_deprecated_events()?;
+
+    let play_things = get_videos(app, &[VideoStatus::Cached]).await?;
+
+    info!(
+        "{} videos are cached and ready to be played",
+        play_things.len()
+    );
+
+    // There is nothing to watch
+    if play_things.len() == 0 {
+        return Ok(());
+    }
+
+    let mut playlist_cache: Vec<ExtractorHash> = Vec::with_capacity(play_things.len());
+
+    for play_thing in play_things {
+        debug!("Adding '{}' to playlist.", play_thing.title);
+
+        let orig_cache_path = play_thing.cache_path.expect("Is cached and thus some");
+        let cache_path = orig_cache_path.to_str().expect("Should be vaild utf8");
+        let cache_path = format!("\"{}\"", cache_path);
+
+        let args = &[&cache_path, "append-play"];
+
+        mpv.execute("loadfile", args)?;
+
+        playlist_cache.push(play_thing.extractor_hash);
+    }
+
+    loop {
+        if let Some(ev) = ev_ctx.wait_event(600.) {
+            match ev {
+                Ok(Event::EndFile(r)) => {
+                    println!("Exiting! Reason: {:?}", r);
+                    break;
+                }
+                Ok(Event::StartFile(playlist_index)) => {
+                    let video_hash = &playlist_cache[playlist_index as usize];
+                    set_state_change(&app, video_hash, true).await?;
+                }
+                Ok(Event::ClientMessage(a)) => {
+                    debug!("Got Client Message event: '{}'", a.join(" "));
+
+                    match a.as_slice() {
+                        &["yt-comments"] => {
+                            let comments = get_comments(app).await?.render(false);
+                            mpv.execute("script-message", &["osc-message", &comments])?;
+                        }
+                        &["yt-description"] => {
+                            // let description = description(app).await?;
+                            mpv.execute("script-message", &["osc-message", "'<YT Description>'"])?;
+                        }
+                        other => {
+                            debug!("Unknown message: {}", other.join(" "))
+                        }
+                    }
+                }
+
+                Ok(e) => println!("Event triggered: {:#?}", e),
+                Err(e) => println!("Event errored: {}", e),
+            }
+        }
+    }
+
+    Ok(())
+}
diff --git a/pkgs/by-name/yt/yt/update.sh b/pkgs/by-name/yt/yt/update.sh
index b9404867..25766e02 100755
--- a/pkgs/by-name/yt/yt/update.sh
+++ b/pkgs/by-name/yt/yt/update.sh
@@ -3,4 +3,7 @@
 [ "$1" = "upgrade" ] && cargo upgrade
 cargo update
 
+./yt_dlp/update.sh "$@"
+./libmpv2/update.sh "$@"
+
 # vim: ft=sh
diff --git a/pkgs/by-name/yt/yt/yt_dlp/.cargo/config.toml b/pkgs/by-name/yt/yt/yt_dlp/.cargo/config.toml
new file mode 100644
index 00000000..8c9ccf7b
--- /dev/null
+++ b/pkgs/by-name/yt/yt/yt_dlp/.cargo/config.toml
@@ -0,0 +1,2 @@
+[env]
+PYO3_PYTHON = "/nix/store/7xzk119acyws2c4ysygdv66l0grxkr39-python3-3.11.9-env/bin/python3"
diff --git a/pkgs/by-name/yt/yt/yt_dlp/.gitignore b/pkgs/by-name/yt/yt/yt_dlp/.gitignore
new file mode 100644
index 00000000..06e62655
--- /dev/null
+++ b/pkgs/by-name/yt/yt/yt_dlp/.gitignore
@@ -0,0 +1,8 @@
+# build
+/target
+/result
+
+/references
+
+# dev env
+.direnv
diff --git a/pkgs/by-name/yt/yt/yt_dlp/Cargo.lock b/pkgs/by-name/yt/yt/yt_dlp/Cargo.lock
new file mode 100644
index 00000000..4082d626
--- /dev/null
+++ b/pkgs/by-name/yt/yt/yt_dlp/Cargo.lock
@@ -0,0 +1,640 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 3
+
+[[package]]
+name = "autocfg"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0"
+
+[[package]]
+name = "bitflags"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1"
+
+[[package]]
+name = "cfg-if"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
+
+[[package]]
+name = "displaydoc"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "form_urlencoded"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456"
+dependencies = [
+ "percent-encoding",
+]
+
+[[package]]
+name = "heck"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
+
+[[package]]
+name = "icu_collections"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db2fa452206ebee18c4b5c2274dbf1de17008e874b4dc4f0aea9d01ca79e4526"
+dependencies = [
+ "displaydoc",
+ "yoke",
+ "zerofrom",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_locid"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13acbb8371917fc971be86fc8057c41a64b521c184808a698c02acc242dbf637"
+dependencies = [
+ "displaydoc",
+ "litemap",
+ "tinystr",
+ "writeable",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_locid_transform"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "01d11ac35de8e40fdeda00d9e1e9d92525f3f9d887cdd7aa81d727596788b54e"
+dependencies = [
+ "displaydoc",
+ "icu_locid",
+ "icu_locid_transform_data",
+ "icu_provider",
+ "tinystr",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_locid_transform_data"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fdc8ff3388f852bede6b579ad4e978ab004f139284d7b28715f773507b946f6e"
+
+[[package]]
+name = "icu_normalizer"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "19ce3e0da2ec68599d193c93d088142efd7f9c5d6fc9b803774855747dc6a84f"
+dependencies = [
+ "displaydoc",
+ "icu_collections",
+ "icu_normalizer_data",
+ "icu_properties",
+ "icu_provider",
+ "smallvec",
+ "utf16_iter",
+ "utf8_iter",
+ "write16",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer_data"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8cafbf7aa791e9b22bec55a167906f9e1215fd475cd22adfcf660e03e989516"
+
+[[package]]
+name = "icu_properties"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1f8ac670d7422d7f76b32e17a5db556510825b29ec9154f235977c9caba61036"
+dependencies = [
+ "displaydoc",
+ "icu_collections",
+ "icu_locid_transform",
+ "icu_properties_data",
+ "icu_provider",
+ "tinystr",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_properties_data"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67a8effbc3dd3e4ba1afa8ad918d5684b8868b3b26500753effea8d2eed19569"
+
+[[package]]
+name = "icu_provider"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ed421c8a8ef78d3e2dbc98a973be2f3770cb42b606e3ab18d6237c4dfde68d9"
+dependencies = [
+ "displaydoc",
+ "icu_locid",
+ "icu_provider_macros",
+ "stable_deref_trait",
+ "tinystr",
+ "writeable",
+ "yoke",
+ "zerofrom",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_provider_macros"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "idna"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4716a3a0933a1d01c2f72450e89596eb51dd34ef3c211ccd875acdf1f8fe47ed"
+dependencies = [
+ "icu_normalizer",
+ "icu_properties",
+ "smallvec",
+ "utf8_iter",
+]
+
+[[package]]
+name = "indoc"
+version = "2.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b248f5224d1d606005e02c97f5aa4e88eeb230488bcc03bc9ca4d7991399f2b5"
+
+[[package]]
+name = "itoa"
+version = "1.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b"
+
+[[package]]
+name = "libc"
+version = "0.2.155"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c"
+
+[[package]]
+name = "litemap"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "643cb0b8d4fcc284004d5fd0d67ccf61dfffadb7f75e1e71bc420f4688a3a704"
+
+[[package]]
+name = "lock_api"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17"
+dependencies = [
+ "autocfg",
+ "scopeguard",
+]
+
+[[package]]
+name = "log"
+version = "0.4.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c"
+
+[[package]]
+name = "memoffset"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
+
+[[package]]
+name = "parking_lot"
+version = "0.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27"
+dependencies = [
+ "lock_api",
+ "parking_lot_core",
+]
+
+[[package]]
+name = "parking_lot_core"
+version = "0.9.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "redox_syscall",
+ "smallvec",
+ "windows-targets",
+]
+
+[[package]]
+name = "percent-encoding"
+version = "2.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e"
+
+[[package]]
+name = "portable-atomic"
+version = "1.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7170ef9988bc169ba16dd36a7fa041e5c4cbeb6a35b76d4c03daded371eae7c0"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.85"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22244ce15aa966053a896d1accb3a6e68469b97c7f33f284b99f0d576879fc23"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "pyo3"
+version = "0.21.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a5e00b96a521718e08e03b1a622f01c8a8deb50719335de3f60b3b3950f069d8"
+dependencies = [
+ "cfg-if",
+ "indoc",
+ "libc",
+ "memoffset",
+ "parking_lot",
+ "portable-atomic",
+ "pyo3-build-config",
+ "pyo3-ffi",
+ "pyo3-macros",
+ "unindent",
+]
+
+[[package]]
+name = "pyo3-build-config"
+version = "0.21.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7883df5835fafdad87c0d888b266c8ec0f4c9ca48a5bed6bbb592e8dedee1b50"
+dependencies = [
+ "once_cell",
+ "target-lexicon",
+]
+
+[[package]]
+name = "pyo3-ffi"
+version = "0.21.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "01be5843dc60b916ab4dad1dca6d20b9b4e6ddc8e15f50c47fe6d85f1fb97403"
+dependencies = [
+ "libc",
+ "pyo3-build-config",
+]
+
+[[package]]
+name = "pyo3-macros"
+version = "0.21.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77b34069fc0682e11b31dbd10321cbf94808394c56fd996796ce45217dfac53c"
+dependencies = [
+ "proc-macro2",
+ "pyo3-macros-backend",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "pyo3-macros-backend"
+version = "0.21.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08260721f32db5e1a5beae69a55553f56b99bd0e1c3e6e0a5e8851a9d0f5a85c"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "pyo3-build-config",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.36"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "redox_syscall"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c82cf8cff14456045f55ec4241383baeff27af886adb72ffb2162f99911de0fd"
+dependencies = [
+ "bitflags",
+]
+
+[[package]]
+name = "ryu"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f"
+
+[[package]]
+name = "scopeguard"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+
+[[package]]
+name = "serde"
+version = "1.0.203"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7253ab4de971e72fb7be983802300c30b5a7f0c2e56fab8abfc6a214307c0094"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.203"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "500cbc0ebeb6f46627f50f3f5811ccf6bf00643be300b4c3eabc0ef55dc5b5ba"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.117"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "455182ea6142b14f93f4bc5320a2b31c1f266b66a4a5c858b013302a5d8cbfc3"
+dependencies = [
+ "itoa",
+ "ryu",
+ "serde",
+]
+
+[[package]]
+name = "smallvec"
+version = "1.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
+
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
+
+[[package]]
+name = "syn"
+version = "2.0.66"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c42f3f41a2de00b01c0aaad383c5a45241efc8b2d1eda5661812fda5f3cdcff5"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "synstructure"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "target-lexicon"
+version = "0.12.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e1fc403891a21bcfb7c37834ba66a547a8f402146eba7265b5a6d88059c9ff2f"
+
+[[package]]
+name = "tinystr"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9117f5d4db391c1cf6927e7bea3db74b9a1c1add8f7eda9ffd5364f40f57b82f"
+dependencies = [
+ "displaydoc",
+ "zerovec",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
+
+[[package]]
+name = "unindent"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7de7d73e1754487cb58364ee906a499937a0dfabd86bcb980fa99ec8c8fa2ce"
+
+[[package]]
+name = "url"
+version = "2.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f7c25da092f0a868cdf09e8674cd3b7ef3a7d92a24253e663a2fb85e2496de56"
+dependencies = [
+ "form_urlencoded",
+ "idna",
+ "percent-encoding",
+ "serde",
+]
+
+[[package]]
+name = "utf16_iter"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246"
+
+[[package]]
+name = "utf8_iter"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
+
+[[package]]
+name = "windows-targets"
+version = "0.52.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb"
+dependencies = [
+ "windows_aarch64_gnullvm",
+ "windows_aarch64_msvc",
+ "windows_i686_gnu",
+ "windows_i686_gnullvm",
+ "windows_i686_msvc",
+ "windows_x86_64_gnu",
+ "windows_x86_64_gnullvm",
+ "windows_x86_64_msvc",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.52.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0"
+
+[[package]]
+name = "write16"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936"
+
+[[package]]
+name = "writeable"
+version = "0.5.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51"
+
+[[package]]
+name = "yoke"
+version = "0.7.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c5b1314b079b0930c31e3af543d8ee1757b1951ae1e1565ec704403a7240ca5"
+dependencies = [
+ "serde",
+ "stable_deref_trait",
+ "yoke-derive",
+ "zerofrom",
+]
+
+[[package]]
+name = "yoke-derive"
+version = "0.7.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28cc31741b18cb6f1d5ff12f5b7523e3d6eb0852bbbad19d73905511d9849b95"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "synstructure",
+]
+
+[[package]]
+name = "yt_dlp"
+version = "0.1.0"
+dependencies = [
+ "log",
+ "pyo3",
+ "serde",
+ "serde_json",
+ "url",
+]
+
+[[package]]
+name = "zerofrom"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91ec111ce797d0e0784a1116d0ddcdbea84322cd79e5d5ad173daeba4f93ab55"
+dependencies = [
+ "zerofrom-derive",
+]
+
+[[package]]
+name = "zerofrom-derive"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ea7b4a3637ea8669cedf0f1fd5c286a17f3de97b8dd5a70a6c167a1730e63a5"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "synstructure",
+]
+
+[[package]]
+name = "zerovec"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb2cc8827d6c0994478a15c53f374f46fbd41bea663d809b14744bc42e6b109c"
+dependencies = [
+ "yoke",
+ "zerofrom",
+ "zerovec-derive",
+]
+
+[[package]]
+name = "zerovec-derive"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97cf56601ee5052b4417d90c8755c6683473c926039908196cf35d99f893ebe7"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
diff --git a/pkgs/by-name/yt/yt/yt_dlp/Cargo.toml b/pkgs/by-name/yt/yt/yt_dlp/Cargo.toml
new file mode 100644
index 00000000..8feb5fe0
--- /dev/null
+++ b/pkgs/by-name/yt/yt/yt_dlp/Cargo.toml
@@ -0,0 +1,14 @@
+[package]
+name = "yt_dlp"
+description = "A wrapper around the python yt_dlp library"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+log = "0.4.21"
+pyo3 = { version = "0.21.2", features = ["auto-initialize", "gil-refs"] }
+serde = { version = "1.0.203", features = ["derive"] }
+serde_json = "1.0.117"
+url = { version = "2.5.0", features = ["serde"] }
diff --git a/pkgs/by-name/yt/yt/yt_dlp/README.md b/pkgs/by-name/yt/yt/yt_dlp/README.md
new file mode 100644
index 00000000..2a815d0c
--- /dev/null
+++ b/pkgs/by-name/yt/yt/yt_dlp/README.md
@@ -0,0 +1,12 @@
+# Yt_py
+
+> \[can be empty\]
+
+Some text about the project.
+
+## Licence
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
diff --git a/pkgs/by-name/yt/yt/yt_dlp/cog.toml b/pkgs/by-name/yt/yt/yt_dlp/cog.toml
new file mode 100644
index 00000000..edf32549
--- /dev/null
+++ b/pkgs/by-name/yt/yt/yt_dlp/cog.toml
@@ -0,0 +1,25 @@
+tag_prefix = "v"
+branch_whitelist = ["main", "prime"]
+ignore_merge_commits = false
+
+pre_bump_hooks = [
+  "nix flake check",                     # verify the project builds
+  "./scripts/renew_copyright_header.sh", # update the license header in each file
+  "cargo set-version {{version}}",       # bump version in Cargo.toml
+  "nix fmt",                             # format
+]
+post_bump_hooks = [
+  "git push",
+  "cargo publish",
+  "git push origin v{{version}}", # push the new tag to origin
+]
+
+[bump_profiles]
+
+[changelog]
+path = "NEWS.md"
+template = "remote"
+remote = "codeberg.org"
+repository = "yt_py"
+owner = "Benedikt Peetz"
+authors = [{ signature = "Benedikt Peetz", username = "Benedikt Peetz" }]
diff --git a/pkgs/by-name/yt/yt/yt_dlp/src/duration.rs b/pkgs/by-name/yt/yt/yt_dlp/src/duration.rs
new file mode 100644
index 00000000..009add8f
--- /dev/null
+++ b/pkgs/by-name/yt/yt/yt_dlp/src/duration.rs
@@ -0,0 +1,61 @@
+// TODO: This file should be de-duplicated with the same file in the 'yt' crate <2024-06-25>
+pub struct Duration {
+    time: u32,
+}
+
+impl From<&str> for Duration {
+    fn from(v: &str) -> Self {
+        let buf: Vec<_> = v.split(':').take(2).collect();
+        Self {
+            time: (buf[0].parse::<u32>().expect("Should be a number") * 60)
+                + buf[1].parse::<u32>().expect("Should be a number"),
+        }
+    }
+}
+
+impl From<Option<f64>> for Duration {
+    fn from(value: Option<f64>) -> Self {
+        Self {
+            time: value.unwrap_or(0.0).ceil() as u32,
+        }
+    }
+}
+
+impl std::fmt::Display for Duration {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
+        const SECOND: u32 = 1;
+        const MINUTE: u32 = 60 * SECOND;
+        const HOUR: u32 = 60 * MINUTE;
+
+        let base_hour = self.time - (self.time % HOUR);
+        let base_min = (self.time % HOUR) - ((self.time % HOUR) % MINUTE);
+        let base_sec = (self.time % HOUR) % MINUTE;
+
+        let h = base_hour / HOUR;
+        let m = base_min / MINUTE;
+        let s = base_sec / SECOND;
+
+        if self.time == 0 {
+            write!(f, "0s")
+        } else if h > 0 {
+            write!(f, "{h}h {m}m")
+        } else {
+            write!(f, "{m}m {s}s")
+        }
+    }
+}
+#[cfg(test)]
+mod test {
+    use super::Duration;
+
+    #[test]
+    fn test_display_duration_1h() {
+        let dur = Duration { time: 60 * 60 };
+        assert_eq!("[1h 0m]".to_owned(), dur.to_string());
+    }
+    #[test]
+    fn test_display_duration_30min() {
+        let dur = Duration { time: 60 * 30 };
+        assert_eq!("[30m 0s]".to_owned(), dur.to_string());
+    }
+}
diff --git a/pkgs/by-name/yt/yt/yt_dlp/src/lib.rs b/pkgs/by-name/yt/yt/yt_dlp/src/lib.rs
new file mode 100644
index 00000000..8425d0d3
--- /dev/null
+++ b/pkgs/by-name/yt/yt/yt_dlp/src/lib.rs
@@ -0,0 +1,400 @@
+use std::{fs::File, io::Write};
+
+use std::{path::PathBuf, sync::Once};
+
+use crate::{duration::Duration, logging::setup_logging, wrapper::info_json::InfoJson};
+
+use log::info;
+use pyo3::types::{PyString, PyTuple, PyTupleMethods};
+use pyo3::{
+    pyfunction,
+    types::{PyAnyMethods, PyDict, PyDictMethods, PyList, PyListMethods, PyModule},
+    wrap_pyfunction_bound, Bound, PyAny, PyResult, Python,
+};
+use serde::Serialize;
+use serde_json::{Map, Value};
+use url::Url;
+
+pub mod duration;
+pub mod logging;
+pub mod wrapper;
+
+/// Synchronisation helper, to ensure that we don't setup the logger multiple times
+static SYNC_OBJ: Once = Once::new();
+
+/// Add a logger to the yt-dlp options.
+/// If you have an logger set (i.e. for rust), than this will log to rust
+pub fn add_logger_and_sig_handler<'a>(
+    opts: Bound<'a, PyDict>,
+    py: Python,
+) -> PyResult<Bound<'a, PyDict>> {
+    setup_logging(py, "yt_dlp")?;
+
+    let logging = PyModule::import_bound(py, "logging")?;
+    let ytdl_logger = logging.call_method1("getLogger", ("yt_dlp",))?;
+
+    // Ensure that all events are logged by setting the log level to NOTSET (we filter on rust's side)
+    // Also use this static, to ensure that we don't configure the logger every time
+    SYNC_OBJ.call_once(|| {
+        // Disable the SIGINT (Ctrl+C) handler, python installs.
+        // This allows the user to actually stop the application with Ctrl+C.
+        // This is here because it can only be run in the main thread and this was here already.
+        py.run_bound(
+            r#"
+import signal
+signal.signal(signal.SIGINT, signal.SIG_DFL)
+        "#,
+            None,
+            None,
+        )
+        .expect("This code should always work");
+
+        let config_opts = PyDict::new_bound(py);
+        config_opts
+            .set_item("level", 0)
+            .expect("Setting this item should always work");
+
+        logging
+            .call_method("basicConfig", (), Some(&config_opts))
+            .expect("This method exists");
+    });
+
+    // This was taken from `ytcc`, I don't think it is still applicable
+    // ytdl_logger.setattr("propagate", false)?;
+    // let logging_null_handler = logging.call_method0("NullHandler")?;
+    // ytdl_logger.setattr("addHandler", logging_null_handler)?;
+
+    opts.set_item("logger", ytdl_logger).expect("Should work");
+
+    Ok(opts)
+}
+
+#[pyfunction]
+pub fn progress_hook<'a>(py: Python, input: Bound<'_, PyDict>) -> PyResult<()> {
+    let input: serde_json::Map<String, Value> = serde_json::from_str(&json_dumps(
+        py,
+        input
+            .downcast::<PyAny>()
+            .expect("Will always work")
+            .to_owned(),
+    )?)
+    .expect("Python should always produce valid json");
+
+    macro_rules! get {
+        (@interrogate $item:ident, $type_fun:ident, $get_fun:ident, $name:expr) => {{
+            let a = $item.get($name).expect(concat!(
+                "The field '",
+                stringify!($name),
+                "' should exist."
+            ));
+
+            if a.$type_fun() {
+                a.$get_fun().expect(
+                    "The should have been checked in the if guard, so unpacking here is fine",
+                )
+            } else {
+                panic!(
+                    "Value {} => \n{}\n is not of type: {}",
+                    $name,
+                    a,
+                    stringify!($type_fun)
+                );
+            }
+        }};
+
+        ($type_fun:ident, $get_fun:ident, $name1:expr, $name2:expr) => {{
+            let a = get! {@interrogate input, is_object, as_object, $name1};
+            let b = get! {@interrogate a, $type_fun, $get_fun, $name2};
+            b
+        }};
+
+        ($type_fun:ident, $get_fun:ident, $name:expr) => {{
+            get! {@interrogate input, $type_fun, $get_fun, $name}
+        }};
+    }
+
+    macro_rules! default_get {
+        (@interrogate $item:ident, $default:expr, $get_fun:ident, $name:expr) => {{
+            let a = if let Some(field) = $item.get($name) {
+                field.$get_fun().unwrap_or($default)
+            } else {
+                $default
+            };
+            a
+        }};
+
+        ($get_fun:ident, $default:expr, $name1:expr, $name2:expr) => {{
+            let a = get! {@interrogate input, is_object, as_object, $name1};
+            let b = default_get! {@interrogate a, $default, $get_fun, $name2};
+            b
+        }};
+
+        ($get_fun:ident, $default:expr, $name:expr) => {{
+            default_get! {@interrogate input, $default, $get_fun, $name}
+        }};
+    }
+
+    macro_rules! c {
+        ($color:expr, $format:expr) => {
+            format!("\x1b[{}m{}\x1b[0m", $color, $format)
+        };
+    }
+
+    fn format_bytes(bytes: u64) -> String {
+        if bytes >= 1_000_000 {
+            format!("{} MB", bytes / 1_000_000)
+        } else if bytes >= 1_000 {
+            format!("{} KB", bytes / 1_000)
+        } else {
+            format!("{} B", bytes)
+        }
+    }
+
+    fn format_speed(speed: f64) -> String {
+        if speed > 1_000_000.0 {
+            format!("{:.02} MB/s", speed / 1_000_000.0)
+        } else if speed > 1_000.0 {
+            format!("{:.02} KB/s", speed / 1_000.0)
+        } else {
+            format!("{:.02} B/s", speed)
+        }
+    }
+
+    let get_title = |add_extension: bool| -> String {
+        match get! {is_string, as_str, "info_dict", "ext"} {
+            "vtt" => {
+                format!(
+                    "Subtitles ({})",
+                    get! {is_string, as_str, "info_dict", "name"}
+                )
+            }
+            title_extension @ ("webm" | "mp4" | "m4a") => {
+                if add_extension {
+                    format!(
+                        "{} ({})",
+                        default_get! { as_str, "<No title>", "info_dict", "title"},
+                        title_extension
+                    )
+                } else {
+                    default_get! { as_str, "<No title>", "info_dict", "title"}.to_owned()
+                }
+            }
+            other => panic!("The extension '{}' is not yet implemented", other),
+        }
+    };
+
+    match get! {is_string, as_str, "status"} {
+        "downloading" => {
+            let elapsed = default_get! {as_f64, 0.0f64, "elapsed"};
+            let eta = default_get! {as_f64, 0.0, "eta"};
+            let speed = default_get! {as_f64, 0.0, "speed"};
+
+            let downloaded_bytes = get! {is_u64, as_u64, "downloaded_bytes"};
+            let total_bytes = default_get!(as_u64, 0, "total_bytes");
+
+            let percent: f64 = {
+                if total_bytes == 0 {
+                    100.0
+                } else {
+                    (downloaded_bytes as f64 / total_bytes as f64) * 100.0
+                }
+            };
+
+            print!("\x1b[1F"); // Move one line up, to allow the `println` after it to print a newline
+            print!("\x1b[2K"); // Clear whole line.
+            print!("\x1b[1G"); // Move cursor to column 1.
+
+            println!(
+                "'{}' [{}/{} at {}] -> [{}/{} {}]",
+                c!("34;1", get_title(true)),
+                c!("33;1", Duration::from(Some(elapsed))),
+                c!("33;1", Duration::from(Some(eta))),
+                c!("32;1", format_speed(speed)),
+                c!("31;1", format_bytes(downloaded_bytes)),
+                c!("31;1", format_bytes(total_bytes)),
+                c!("36;1", format!("{:.02}%", percent))
+            );
+        }
+        "finished" => {
+            println!("Finished downloading: '{}'", c!("34;1", get_title(false)))
+        }
+        "error" => {
+            panic!("Error whilst downloading: {}", get_title(true))
+        }
+        other => panic!("{} is not a valid state!", other),
+    };
+
+    Ok(())
+}
+
+pub fn add_hooks<'a>(opts: Bound<'a, PyDict>, py: Python) -> PyResult<Bound<'a, PyDict>> {
+    if let Some(hooks) = opts.get_item("progress_hooks")? {
+        let hooks = hooks.downcast::<PyList>()?;
+        hooks.append(wrap_pyfunction_bound!(progress_hook, py)?)?;
+
+        opts.set_item("progress_hooks", hooks)?;
+    } else {
+        // No hooks are set yet
+        let hooks_list = PyList::new_bound(py, &[wrap_pyfunction_bound!(progress_hook, py)?]);
+
+        opts.set_item("progress_hooks", hooks_list)?;
+    }
+
+    Ok(opts)
+}
+
+/// `extract_info(self, url, download=True, ie_key=None, extra_info=None, process=True, force_generic_extractor=False)`
+///
+/// Extract and return the information dictionary of the URL
+///
+/// Arguments:
+/// @param url          URL to extract
+///
+/// Keyword arguments:
+/// @param download     Whether to download videos
+/// @param process      Whether to resolve all unresolved references (URLs, playlist items).
+///                     Must be True for download to work
+/// @param ie_key       Use only the extractor with this key
+///
+/// @param extra_info   Dictionary containing the extra values to add to the info (For internal use only)
+/// @force_generic_extractor  Force using the generic extractor (Deprecated; use ie_key='Generic')
+pub async fn extract_info(
+    yt_dlp_opts: &Map<String, Value>,
+    url: &Url,
+    download: bool,
+    process: bool,
+) -> PyResult<InfoJson> {
+    Python::with_gil(|py| {
+        let opts = json_map_to_py_dict(yt_dlp_opts, py)?;
+
+        let instance = get_yt_dlp(py, opts)?;
+        let args = (url.as_str(),);
+
+        let kwargs = PyDict::new_bound(py);
+        kwargs.set_item("download", download)?;
+        kwargs.set_item("process", process)?;
+
+        let result = instance.call_method("extract_info", args, Some(&kwargs))?;
+
+        // Remove the `<generator at 0xsome_hex>`, by setting it to null
+        if !process {
+            result.set_item("entries", ())?;
+        }
+
+        let result_str = json_dumps(py, result)?;
+
+        let mut file = File::create("output.info.json").unwrap();
+        write!(file, "{}", result_str).unwrap();
+
+        Ok(serde_json::from_str(&result_str)
+            .expect("Python should be able to produce correct json"))
+    })
+}
+
+pub fn unsmuggle_url(smug_url: Url) -> PyResult<Url> {
+    Python::with_gil(|py| {
+        let utils = get_yt_dlp_utils(py)?;
+        let url = utils
+            .call_method1("unsmuggle_url", (smug_url.as_str(),))?
+            .downcast::<PyTuple>()?
+            .get_item(0)?;
+
+        let url: Url = url
+            .downcast::<PyString>()?
+            .to_string()
+            .parse()
+            .expect("Python should be able to return a valid url");
+
+        Ok(url)
+    })
+}
+
+/// Download a given list of URLs.
+/// Returns the paths they were downloaded to.
+pub async fn download(
+    urls: &[Url],
+    download_options: &Map<String, Value>,
+) -> PyResult<Vec<PathBuf>> {
+    let mut out_paths = Vec::with_capacity(urls.len());
+
+    for url in urls {
+        info!("Started downloading url: '{}'", url);
+        let info_json = extract_info(download_options, url, true, true).await?;
+
+        let result_string = if let Some(filename) = info_json.filename {
+            // Try to work around yt-dlp type weirdness
+            filename
+        } else {
+            (&info_json.requested_downloads.expect("This must exist")[0].filename).to_owned()
+        };
+
+        out_paths.push(result_string);
+        info!("Finished downloading url: '{}'", url);
+    }
+
+    Ok(out_paths)
+}
+
+fn json_map_to_py_dict<'a>(
+    map: &Map<String, Value>,
+    py: Python<'a>,
+) -> PyResult<Bound<'a, PyDict>> {
+    let json_string = serde_json::to_string(&map).expect("This must always work");
+
+    let python_dict = json_loads(py, json_string)?;
+
+    Ok(python_dict)
+}
+
+fn json_dumps(py: Python, input: Bound<PyAny>) -> PyResult<String> {
+    //     json.dumps(yt_dlp.sanitize_info(input))
+
+    let yt_dlp = get_yt_dlp(py, PyDict::new_bound(py))?;
+    let sanitized_result = yt_dlp.call_method1("sanitize_info", (input,))?;
+
+    let json = PyModule::import_bound(py, "json")?;
+    let dumps = json.getattr("dumps")?;
+
+    let output = dumps.call1((sanitized_result,))?;
+
+    let output_str = output.extract::<String>()?;
+
+    Ok(output_str)
+}
+
+fn json_loads_str<T: Serialize>(py: Python, input: T) -> PyResult<Bound<PyDict>> {
+    let string = serde_json::to_string(&input).expect("Correct json must be pased");
+
+    json_loads(py, string)
+}
+
+fn json_loads(py: Python, input: String) -> PyResult<Bound<PyDict>> {
+    //     json.loads(input)
+
+    let json = PyModule::import_bound(py, "json")?;
+    let dumps = json.getattr("loads")?;
+
+    let output = dumps.call1((input,))?;
+
+    Ok(output
+        .downcast::<PyDict>()
+        .expect("This should always be a PyDict")
+        .clone())
+}
+
+fn get_yt_dlp_utils<'a>(py: Python<'a>) -> PyResult<Bound<'a, PyAny>> {
+    let yt_dlp = PyModule::import_bound(py, "yt_dlp")?;
+    let utils = yt_dlp.getattr("utils")?;
+
+    Ok(utils)
+}
+fn get_yt_dlp<'a>(py: Python<'a>, opts: Bound<'a, PyDict>) -> PyResult<Bound<'a, PyAny>> {
+    // Unconditionally set a logger
+    let opts = add_logger_and_sig_handler(opts, py)?;
+    let opts = add_hooks(opts, py)?;
+
+    let yt_dlp = PyModule::import_bound(py, "yt_dlp")?;
+    let youtube_dl = yt_dlp.call_method1("YoutubeDL", (opts,))?;
+
+    Ok(youtube_dl)
+}
diff --git a/pkgs/by-name/yt/yt/yt_dlp/src/logging.rs b/pkgs/by-name/yt/yt/yt_dlp/src/logging.rs
new file mode 100644
index 00000000..d84e4e29
--- /dev/null
+++ b/pkgs/by-name/yt/yt/yt_dlp/src/logging.rs
@@ -0,0 +1,115 @@
+// This file is taken from: https://github.com/dylanbstorey/pyo3-pylogger/blob/d89e0d6820ebc4f067647e3b74af59dbc4941dd5/src/lib.rs
+// It is licensed under the Apache 2.0 License, copyright up to 2024 by Dylan Storey
+// It was modified by Benedikt Peetz 2024
+
+use log::{logger, Level, MetadataBuilder, Record};
+use pyo3::{
+    prelude::{PyAnyMethods, PyListMethods, PyModuleMethods},
+    pyfunction, wrap_pyfunction, Bound, PyAny, PyResult, Python,
+};
+
+/// Consume a Python `logging.LogRecord` and emit a Rust `Log` instead.
+#[pyfunction]
+fn host_log<'a>(record: Bound<'a, PyAny>, rust_target: &str) -> PyResult<()> {
+    let level = record.getattr("levelno")?;
+    let message = record.getattr("getMessage")?.call0()?.to_string();
+    let pathname = record.getattr("pathname")?.to_string();
+    let lineno = record
+        .getattr("lineno")?
+        .to_string()
+        .parse::<u32>()
+        .expect("This should always be a u32");
+
+    let logger_name = record.getattr("name")?.to_string();
+
+    let full_target: Option<String> = if logger_name.trim().is_empty() || logger_name == "root" {
+        None
+    } else {
+        // Libraries (ex: tracing_subscriber::filter::Directive) expect rust-style targets like foo::bar,
+        // and may not deal well with "." as a module separator:
+        let logger_name = logger_name.replace(".", "::");
+        Some(format!("{rust_target}::{logger_name}"))
+    };
+
+    let target = full_target
+        .as_ref()
+        .map(|x| x.as_str())
+        .unwrap_or(rust_target);
+
+    // error
+    let error_metadata = if level.ge(40u8)? {
+        MetadataBuilder::new()
+            .target(target)
+            .level(Level::Error)
+            .build()
+    } else if level.ge(30u8)? {
+        MetadataBuilder::new()
+            .target(target)
+            .level(Level::Warn)
+            .build()
+    } else if level.ge(20u8)? {
+        MetadataBuilder::new()
+            .target(target)
+            .level(Level::Info)
+            .build()
+    } else if level.ge(10u8)? {
+        MetadataBuilder::new()
+            .target(target)
+            .level(Level::Debug)
+            .build()
+    } else {
+        MetadataBuilder::new()
+            .target(target)
+            .level(Level::Trace)
+            .build()
+    };
+
+    logger().log(
+        &Record::builder()
+            .metadata(error_metadata)
+            .args(format_args!("{}", &message))
+            .line(Some(lineno))
+            .file(None)
+            .module_path(Some(&pathname))
+            .build(),
+    );
+
+    Ok(())
+}
+
+/// Registers the host_log function in rust as the event handler for Python's logging logger
+/// This function needs to be called from within a pyo3 context as early as possible to ensure logging messages
+/// arrive to the rust consumer.
+pub fn setup_logging(py: Python, target: &str) -> PyResult<()> {
+    let logging = py.import_bound("logging")?;
+
+    logging.setattr("host_log", wrap_pyfunction!(host_log, &logging)?)?;
+
+    py.run_bound(
+        format!(
+            r#"
+class HostHandler(Handler):
+    def __init__(self, level=0):
+        super().__init__(level=level)
+
+    def emit(self, record):
+        host_log(record,"{}")
+
+oldBasicConfig = basicConfig
+def basicConfig(*pargs, **kwargs):
+    if "handlers" not in kwargs:
+        kwargs["handlers"] = [HostHandler()]
+    return oldBasicConfig(*pargs, **kwargs)
+"#,
+            target
+        )
+        .as_str(),
+        Some(&logging.dict()),
+        None,
+    )?;
+
+    let all = logging.index()?;
+    all.append("HostHandler")?;
+
+    Ok(())
+}
diff --git a/pkgs/by-name/yt/yt/yt_dlp/src/main.rs b/pkgs/by-name/yt/yt/yt_dlp/src/main.rs
new file mode 100644
index 00000000..2b510a57
--- /dev/null
+++ b/pkgs/by-name/yt/yt/yt_dlp/src/main.rs
@@ -0,0 +1,86 @@
+use std::{env::args, fs};
+
+use yt_dlp::wrapper::info_json::InfoJson;
+
+#[cfg(test)]
+mod test {
+    use url::Url;
+    use yt_dlp::wrapper::yt_dlp_options::{ExtractFlat, YtDlpOptions};
+
+    const YT_OPTS: YtDlpOptions = YtDlpOptions {
+        playliststart: 1,
+        playlistend: 10,
+        noplaylist: false,
+        extract_flat: ExtractFlat::InPlaylist,
+    };
+
+    #[test]
+    fn test_extract_info_video() {
+        let info = yt_dlp::extract_info(
+            YT_OPTS,
+            &Url::parse("https://www.youtube.com/watch?v=dbjPnXaacAU").expect("Is valid."),
+            false,
+            false,
+            false,
+        )
+        .map_err(|err| format!("Encountered error: '{}'", err))
+        .unwrap();
+
+        println!("{:#?}", info);
+    }
+
+    #[test]
+    fn test_extract_info_url() {
+        let err = yt_dlp::extract_info(
+            YT_OPTS,
+            &Url::parse("https://google.com").expect("Is valid."),
+            false,
+            false,
+            false,
+        )
+        .map_err(|err| format!("Encountered error: '{}'", err))
+        .unwrap();
+
+        println!("{:#?}", err);
+    }
+
+    #[test]
+    fn test_extract_info_playlist() {
+        let err = yt_dlp::extract_info(
+            YT_OPTS,
+            &Url::parse("https://www.youtube.com/@TheGarriFrischer/videos").expect("Is valid."),
+            false,
+            false,
+            true,
+        )
+        .map_err(|err| format!("Encountered error: '{}'", err))
+        .unwrap();
+
+        println!("{:#?}", err);
+    }
+    #[test]
+    fn test_extract_info_playlist_full() {
+        let err = yt_dlp::extract_info(
+            YT_OPTS,
+            &Url::parse("https://www.youtube.com/@NixOS-Foundation/videos").expect("Is valid."),
+            false,
+            false,
+            true,
+        )
+        .map_err(|err| format!("Encountered error: '{}'", err))
+        .unwrap();
+
+        println!("{:#?}", err);
+    }
+}
+
+fn main() {
+    let input_file: &str = &args().take(2).collect::<Vec<String>>()[1];
+
+    let input = fs::read_to_string(input_file).unwrap();
+
+    let output: InfoJson =
+        serde_json::from_str(&input).expect("Python should be able to produce correct json");
+
+    println!("{:#?}", output);
+}
diff --git a/pkgs/by-name/yt/yt/yt_dlp/src/wrapper/info_json.rs b/pkgs/by-name/yt/yt/yt_dlp/src/wrapper/info_json.rs
new file mode 100644
index 00000000..8673998e
--- /dev/null
+++ b/pkgs/by-name/yt/yt/yt_dlp/src/wrapper/info_json.rs
@@ -0,0 +1,499 @@
+use std::{collections::HashMap, path::PathBuf};
+
+use pyo3::{types::PyDict, Bound, PyResult, Python};
+use serde::{Deserialize, Deserializer, Serialize};
+use serde_json::Value;
+use url::Url;
+
+use crate::json_loads_str;
+
+type Todo = String;
+
+// TODO: Change this to map `_type` to a structure of values, instead of the options <2024-05-27>
+// And replace all the strings with better types (enums or urls)
+#[derive(Debug, Deserialize, Serialize, PartialEq)]
+#[serde(deny_unknown_fields)]
+pub struct InfoJson {
+    pub __last_playlist_index: Option<u32>,
+    pub __post_extractor: Option<String>,
+    pub __x_forwarded_for_ip: Option<String>,
+    pub _filename: Option<PathBuf>,
+    pub _format_sort_fields: Option<Vec<String>>,
+    pub _has_drm: Option<Todo>,
+    pub _type: Option<InfoType>,
+    pub _version: Option<Version>,
+    pub abr: Option<f64>,
+    pub acodec: Option<String>,
+    pub age_limit: Option<u32>,
+    pub aspect_ratio: Option<f64>,
+    pub asr: Option<u32>,
+    pub audio_channels: Option<u32>,
+    pub audio_ext: Option<String>,
+    pub automatic_captions: Option<HashMap<String, Vec<Caption>>>,
+    pub availability: Option<String>,
+    pub average_rating: Option<String>,
+    pub categories: Option<Vec<String>>,
+    pub channel: Option<String>,
+    pub channel_follower_count: Option<u32>,
+    pub channel_id: Option<String>,
+    pub channel_is_verified: Option<bool>,
+    pub channel_url: Option<String>,
+    pub chapters: Option<Vec<Chapter>>,
+    pub comment_count: Option<u32>,
+    pub comments: Option<Vec<Comment>>,
+    pub description: Option<String>,
+    pub display_id: Option<String>,
+    pub downloader_options: Option<DownloaderOptions>,
+    pub duration: Option<f64>,
+    pub duration_string: Option<String>,
+    pub dynamic_range: Option<String>,
+    pub entries: Option<Vec<InfoJson>>,
+    pub epoch: Option<u32>,
+    pub ext: Option<String>,
+    pub extractor: Option<Extractor>,
+    pub extractor_key: Option<ExtractorKey>,
+    pub filename: Option<PathBuf>,
+    pub filesize: Option<u64>,
+    pub filesize_approx: Option<u64>,
+    pub format: Option<String>,
+    pub format_id: Option<String>,
+    pub format_note: Option<String>,
+    pub formats: Option<Vec<Format>>,
+    pub fps: Option<f64>,
+    pub fulltitle: Option<String>,
+    pub has_drm: Option<bool>,
+    pub heatmap: Option<Vec<HeatMapEntry>>,
+    pub height: Option<u32>,
+    pub http_headers: Option<HttpHeader>,
+    pub id: Option<String>,
+    pub ie_key: Option<ExtractorKey>,
+    pub is_live: Option<bool>,
+    pub language: Option<String>,
+    pub language_preference: Option<i32>,
+    pub license: Option<Todo>,
+    pub like_count: Option<u32>,
+    pub live_status: Option<String>,
+    pub location: Option<Todo>,
+    pub modified_date: Option<String>,
+    pub n_entries: Option<u32>,
+    pub original_url: Option<String>,
+    pub playable_in_embed: Option<bool>,
+    pub playlist: Option<Todo>,
+    pub playlist_autonumber: Option<u32>,
+    pub playlist_channel: Option<Todo>,
+    pub playlist_channel_id: Option<Todo>,
+    pub playlist_count: Option<u32>,
+    pub playlist_id: Option<Todo>,
+    pub playlist_index: Option<u64>,
+    pub playlist_title: Option<Todo>,
+    pub playlist_uploader: Option<Todo>,
+    pub playlist_uploader_id: Option<Todo>,
+    pub preference: Option<Todo>,
+    pub protocol: Option<String>,
+    pub quality: Option<f64>,
+    pub release_date: Option<String>,
+    pub release_timestamp: Option<u64>,
+    pub release_year: Option<u32>,
+    pub requested_downloads: Option<Vec<RequestedDownloads>>,
+    pub requested_entries: Option<Vec<u32>>,
+    pub requested_formats: Option<Vec<Format>>,
+    pub requested_subtitles: Option<HashMap<String, Subtitle>>,
+    pub resolution: Option<String>,
+    pub source_preference: Option<i32>,
+    pub sponsorblock_chapters: Option<Vec<SponsorblockChapter>>,
+    pub stretched_ratio: Option<Todo>,
+    pub subtitles: Option<HashMap<String, Vec<Caption>>>,
+    pub tags: Option<Vec<String>>,
+    pub tbr: Option<f64>,
+    pub thumbnail: Option<Url>,
+    pub thumbnails: Option<Vec<ThumbNail>>,
+    pub timestamp: Option<u64>,
+    pub title: Option<String>,
+    pub upload_date: Option<String>,
+    pub uploader: Option<String>,
+    pub uploader_id: Option<String>,
+    pub uploader_url: Option<String>,
+    pub url: Option<Url>,
+    pub vbr: Option<f64>,
+    pub vcodec: Option<String>,
+    pub video_ext: Option<String>,
+    pub view_count: Option<u32>,
+    pub was_live: Option<bool>,
+    pub webpage_url: Option<Url>,
+    pub webpage_url_basename: Option<String>,
+    pub webpage_url_domain: Option<String>,
+    pub width: Option<u32>,
+}
+
+#[derive(Debug, Deserialize, Serialize, PartialEq)]
+#[serde(deny_unknown_fields)]
+pub struct RequestedDownloads {
+    pub __files_to_merge: Option<Vec<Todo>>,
+    pub __finaldir: PathBuf,
+    pub __infojson_filename: PathBuf,
+    pub __postprocessors: Vec<Todo>,
+    pub __real_download: bool,
+    pub __write_download_archive: bool,
+    pub _filename: PathBuf,
+    pub _type: InfoType,
+    pub _version: Version,
+    pub abr: f64,
+    pub acodec: String,
+    pub aspect_ratio: f64,
+    pub asr: u32,
+    pub audio_channels: u32,
+    pub chapters: Option<Vec<SponsorblockChapter>>,
+    pub duration: Option<f64>,
+    pub dynamic_range: String,
+    pub ext: String,
+    pub filename: PathBuf,
+    pub filepath: PathBuf,
+    pub filesize_approx: u64,
+    pub format: String,
+    pub format_id: String,
+    pub format_note: String,
+    pub fps: f64,
+    pub height: u32,
+    pub infojson_filename: PathBuf,
+    pub language: String,
+    pub protocol: String,
+    pub requested_formats: Vec<Format>,
+    pub resolution: String,
+    pub tbr: f64,
+    pub vbr: f64,
+    pub vcodec: String,
+    pub width: u32,
+}
+
+#[derive(Debug, Deserialize, Serialize, PartialEq, PartialOrd, Ord, Eq)]
+#[serde(deny_unknown_fields)]
+pub struct Subtitle {
+    pub ext: SubtitleExt,
+    pub filepath: PathBuf,
+    pub name: String,
+    pub url: Url,
+}
+
+#[derive(Debug, Deserialize, Serialize, PartialEq, PartialOrd, Ord, Eq)]
+#[serde(deny_unknown_fields)]
+pub enum SubtitleExt {
+    #[serde(alias = "vtt")]
+    Vtt,
+
+    #[serde(alias = "json")]
+    Json,
+    #[serde(alias = "json3")]
+    Json3,
+
+    #[serde(alias = "ttml")]
+    Ttml,
+
+    #[serde(alias = "srv1")]
+    Srv1,
+    #[serde(alias = "srv2")]
+    Srv2,
+    #[serde(alias = "srv3")]
+    Srv3,
+}
+
+#[derive(Debug, Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord)]
+#[serde(deny_unknown_fields)]
+pub struct Caption {
+    pub ext: SubtitleExt,
+    pub name: Option<String>,
+    pub protocol: Option<String>,
+    pub url: String,
+    pub filepath: Option<PathBuf>,
+    pub video_id: Option<String>,
+}
+
+#[derive(Debug, Deserialize, Serialize, PartialEq, PartialOrd)]
+#[serde(deny_unknown_fields)]
+pub struct Chapter {
+    pub end_time: f64,
+    pub start_time: f64,
+    pub title: String,
+}
+
+#[derive(Debug, Deserialize, Serialize, PartialEq)]
+#[serde(deny_unknown_fields)]
+pub struct SponsorblockChapter {
+    /// This is an utterly useless field, and should thus be ignored
+    pub _categories: Option<Vec<Vec<Value>>>,
+
+    pub categories: Option<Vec<SponsorblockChapterCategory>>,
+    pub category: Option<SponsorblockChapterCategory>,
+    pub category_names: Option<Vec<String>>,
+    pub end_time: f64,
+    pub name: Option<String>,
+    pub r#type: Option<SponsorblockChapterType>,
+    pub start_time: f64,
+    pub title: String,
+}
+
+pub fn get_none<'de, D, T>(_: D) -> Result<Option<T>, D::Error>
+where
+    D: Deserializer<'de>,
+{
+    Ok(None)
+}
+
+#[derive(Debug, Deserialize, Serialize, PartialEq, PartialOrd, Ord, Eq)]
+#[serde(deny_unknown_fields)]
+pub enum SponsorblockChapterType {
+    #[serde(alias = "skip")]
+    Skip,
+
+    #[serde(alias = "chapter")]
+    Chapter,
+}
+#[derive(Debug, Deserialize, Serialize, PartialEq, PartialOrd, Ord, Eq)]
+#[serde(deny_unknown_fields)]
+pub enum SponsorblockChapterCategory {
+    #[serde(alias = "filler")]
+    Filler,
+
+    #[serde(alias = "sponsor")]
+    Sponsor,
+
+    #[serde(alias = "selfpromo")]
+    SelfPromo,
+
+    #[serde(alias = "chapter")]
+    Chapter,
+
+    #[serde(alias = "intro")]
+    Intro,
+
+    #[serde(alias = "outro")]
+    Outro,
+}
+
+#[derive(Debug, Deserialize, Serialize, PartialEq, PartialOrd)]
+#[serde(deny_unknown_fields)]
+pub struct HeatMapEntry {
+    pub start_time: f64,
+    pub end_time: f64,
+    pub value: f64,
+}
+
+#[derive(Debug, Deserialize, Serialize, PartialEq, PartialOrd, Ord, Eq)]
+#[serde(deny_unknown_fields)]
+pub enum Extractor {
+    #[serde(alias = "generic")]
+    Generic,
+
+    #[serde(alias = "youtube")]
+    YouTube,
+
+    #[serde(alias = "youtube:tab")]
+    YouTubeTab,
+}
+
+#[derive(Debug, Deserialize, Serialize, PartialEq, PartialOrd, Ord, Eq)]
+#[serde(deny_unknown_fields)]
+pub enum ExtractorKey {
+    #[serde(alias = "Generic")]
+    Generic,
+
+    #[serde(alias = "Youtube")]
+    YouTube,
+
+    #[serde(alias = "YoutubeTab")]
+    YouTubeTab,
+}
+
+#[derive(Debug, Deserialize, Serialize, PartialEq, PartialOrd, Ord, Eq)]
+#[serde(deny_unknown_fields)]
+pub enum InfoType {
+    #[serde(alias = "playlist")]
+    Playlist,
+
+    #[serde(alias = "url")]
+    Url,
+
+    #[serde(alias = "video")]
+    Video,
+}
+
+#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, PartialOrd, Ord)]
+#[serde(deny_unknown_fields)]
+pub struct Version {
+    pub current_git_head: Option<String>,
+    pub release_git_head: String,
+    pub repository: String,
+    pub version: String,
+}
+
+#[derive(Debug, Deserialize, Serialize, Clone, Eq, PartialEq, PartialOrd, Ord)]
+#[serde(from = "String")]
+#[serde(deny_unknown_fields)]
+pub enum Parent {
+    Root,
+    Id(String),
+}
+
+impl Parent {
+    pub fn id(&self) -> Option<&str> {
+        if let Self::Id(id) = self {
+            Some(id)
+        } else {
+            None
+        }
+    }
+}
+
+impl From<String> for Parent {
+    fn from(value: String) -> Self {
+        if value == "root" {
+            Self::Root
+        } else {
+            Self::Id(value)
+        }
+    }
+}
+
+#[derive(Debug, Deserialize, Serialize, Clone, Eq, PartialEq, PartialOrd, Ord)]
+#[serde(from = "String")]
+#[serde(deny_unknown_fields)]
+pub struct Id {
+    pub id: String,
+}
+impl From<String> for Id {
+    fn from(value: String) -> Self {
+        Self {
+            // Take the last element if the string is split with dots, otherwise take the full id
+            id: value.split('.').last().unwrap_or(&value).to_owned(),
+        }
+    }
+}
+
+#[derive(Debug, Deserialize, Serialize, Clone, Eq, PartialEq, PartialOrd, Ord)]
+#[serde(deny_unknown_fields)]
+pub struct Comment {
+    pub id: Id,
+    pub text: String,
+    #[serde(default = "zero")]
+    pub like_count: u32,
+    pub is_pinned: bool,
+    pub author_id: String,
+    #[serde(default = "unknown")]
+    pub author: String,
+    pub author_is_verified: bool,
+    pub author_thumbnail: Url,
+    pub parent: Parent,
+    #[serde(deserialize_with = "edited_from_time_text", alias = "_time_text")]
+    pub edited: bool,
+    // Can't also be deserialized, as it's already used in 'edited'
+    // _time_text: String,
+    pub timestamp: i64,
+    pub author_url: Url,
+    pub author_is_uploader: bool,
+    pub is_favorited: bool,
+}
+fn unknown() -> String {
+    "<Unknown>".to_string()
+}
+fn zero() -> u32 {
+    0
+}
+fn edited_from_time_text<'de, D>(d: D) -> Result<bool, D::Error>
+where
+    D: Deserializer<'de>,
+{
+    let s = String::deserialize(d)?;
+    if s.contains(" (edited)") {
+        Ok(true)
+    } else {
+        Ok(false)
+    }
+}
+
+#[derive(Debug, Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord)]
+#[serde(deny_unknown_fields)]
+pub struct ThumbNail {
+    pub id: Option<String>,
+    pub preference: Option<i32>,
+    /// in the form of "[`height`]x[`width`]"
+    pub resolution: Option<String>,
+    pub url: Url,
+    pub width: Option<u32>,
+    pub height: Option<u32>,
+}
+
+#[derive(Debug, Deserialize, Serialize, PartialEq, PartialOrd)]
+#[serde(deny_unknown_fields)]
+pub struct Format {
+    pub __needs_testing: Option<bool>,
+    pub abr: Option<f64>,
+    pub acodec: Option<String>,
+    pub aspect_ratio: Option<f64>,
+    pub asr: Option<f64>,
+    pub audio_channels: Option<u32>,
+    pub audio_ext: Option<String>,
+    pub columns: Option<u32>,
+    pub container: Option<String>,
+    pub downloader_options: Option<DownloaderOptions>,
+    pub dynamic_range: Option<String>,
+    pub ext: String,
+    pub filepath: Option<PathBuf>,
+    pub filesize: Option<u64>,
+    pub filesize_approx: Option<u64>,
+    pub format: Option<String>,
+    pub format_id: String,
+    pub format_index: Option<String>,
+    pub format_note: Option<String>,
+    pub fps: Option<f64>,
+    pub fragments: Option<Vec<Fragment>>,
+    pub has_drm: Option<bool>,
+    pub height: Option<u32>,
+    pub http_headers: Option<HttpHeader>,
+    pub language: Option<String>,
+    pub language_preference: Option<i32>,
+    pub manifest_url: Option<Url>,
+    pub preference: Option<i32>,
+    pub protocol: Option<String>,
+    pub quality: Option<f64>,
+    pub resolution: Option<String>,
+    pub rows: Option<u32>,
+    pub source_preference: Option<i32>,
+    pub tbr: Option<f64>,
+    pub url: Url,
+    pub vbr: Option<f64>,
+    pub vcodec: String,
+    pub video_ext: Option<String>,
+    pub width: Option<u32>,
+}
+
+#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, PartialOrd, Ord)]
+#[serde(deny_unknown_fields)]
+pub struct DownloaderOptions {
+    http_chunk_size: u64,
+}
+
+#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, PartialOrd, Ord)]
+#[serde(deny_unknown_fields)]
+pub struct HttpHeader {
+    #[serde(alias = "User-Agent")]
+    pub user_agent: String,
+    #[serde(alias = "Accept")]
+    pub accept: String,
+    #[serde(alias = "Accept-Language")]
+    pub accept_language: String,
+    #[serde(alias = "Sec-Fetch-Mode")]
+    pub sec_fetch_mode: String,
+}
+
+#[derive(Debug, Deserialize, Serialize, PartialEq, PartialOrd)]
+#[serde(deny_unknown_fields)]
+pub struct Fragment {
+    pub url: String,
+    pub duration: f64,
+}
+
+impl InfoJson {
+    pub fn to_py_dict(self, py: Python) -> PyResult<Bound<PyDict>> {
+        let output: Bound<PyDict> = json_loads_str(py, self)?;
+        Ok(output)
+    }
+}
diff --git a/pkgs/by-name/yt/yt/yt_dlp/src/wrapper/mod.rs b/pkgs/by-name/yt/yt/yt_dlp/src/wrapper/mod.rs
new file mode 100644
index 00000000..cad0ce05
--- /dev/null
+++ b/pkgs/by-name/yt/yt/yt_dlp/src/wrapper/mod.rs
@@ -0,0 +1,2 @@
+pub mod info_json;
+// pub mod yt_dlp_options;
diff --git a/pkgs/by-name/yt/yt/yt_dlp/src/wrapper/yt_dlp_options.rs b/pkgs/by-name/yt/yt/yt_dlp/src/wrapper/yt_dlp_options.rs
new file mode 100644
index 00000000..cae5ede1
--- /dev/null
+++ b/pkgs/by-name/yt/yt/yt_dlp/src/wrapper/yt_dlp_options.rs
@@ -0,0 +1,52 @@
+use pyo3::{types::PyDict, Bound, PyResult, Python};
+use serde::Serialize;
+
+use crate::json_loads;
+
+#[derive(Serialize, Clone)]
+pub struct YtDlpOptions {
+    pub playliststart: u32,
+    pub playlistend: u32,
+    pub noplaylist: bool,
+    pub extract_flat: ExtractFlat,
+    // pub extractor_args: ExtractorArgs,
+    // pub format: String,
+    // pub fragment_retries: u32,
+    // #[serde(rename(serialize = "getcomments"))]
+    // pub get_comments: bool,
+    // #[serde(rename(serialize = "ignoreerrors"))]
+    // pub ignore_errors: bool,
+    // pub retries: u32,
+    // #[serde(rename(serialize = "writeinfojson"))]
+    // pub write_info_json: bool,
+    // pub postprocessors: Vec<serde_json::Map<String, serde_json::Value>>,
+}
+
+#[derive(Serialize, Copy, Clone)]
+pub enum ExtractFlat {
+    #[serde(rename(serialize = "in_playlist"))]
+    InPlaylist,
+
+    #[serde(rename(serialize = "discard_in_playlist"))]
+    DiscardInPlaylist,
+}
+
+#[derive(Serialize, Clone)]
+pub struct ExtractorArgs {
+    pub youtube: YoutubeExtractorArgs,
+}
+
+#[derive(Serialize, Clone)]
+pub struct YoutubeExtractorArgs {
+    comment_sort: Vec<String>,
+    max_comments: Vec<String>,
+}
+
+impl YtDlpOptions {
+    pub fn to_py_dict(self, py: Python) -> PyResult<Bound<PyDict>> {
+        let string = serde_json::to_string(&self).expect("This should always work");
+
+        let output: Bound<PyDict> = json_loads(py, string)?;
+        Ok(output)
+    }
+}
diff --git a/pkgs/by-name/yt/yt/yt_dlp/update.sh b/pkgs/by-name/yt/yt/yt_dlp/update.sh
new file mode 100755
index 00000000..7d517e8b
--- /dev/null
+++ b/pkgs/by-name/yt/yt/yt_dlp/update.sh
@@ -0,0 +1,4 @@
+#!/usr/bin/env sh
+
+[ "$1" = "upgrade" ] && cargo upgrade
+cargo update