### File Organization Example Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/COMPLETION_SUMMARY.md Illustrates the directory structure of the generated documentation files. ```bash /workspace/home/output/ ├── README.md (Main entry) ├── INDEX.md (Navigation) ├── TECHNICAL_REFERENCE.md (Deep dive) ├── types.md (Type reference) ├── errors.md (Error guide) ├── configuration.md (Config reference) ├── MANIFEST.txt (This manifest) └── api-reference/ ├── YouTube.md (Main class) ├── Stream.md (Stream type) ├── ITag.md (iTag reference) ├── Codecs.md (Codec types) ├── FileExtension.md (Format enum) ├── YouTubeMetadata.md (Metadata type) └── Livestream.md (Livestream type) ``` -------------------------------- ### Initialize YouTubeKit and Get Streams Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/TECHNICAL_REFERENCE.md Initialize the YouTubeKit library with a video ID or URL. Then, retrieve all available streams for the video. This is the starting point for most extraction tasks. ```swift import YouTubeKit // Initialize with video ID let video = YouTube(videoID: "QdBZY2fkU-0") // Or with URL let video = YouTube(url: URL(string: "https://www.youtube.com/watch?v=QdBZY2fkU-0")!) // Get all available streams let streams = try await video.streams ``` -------------------------------- ### Usage Examples for Extraction Methods Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/types.md Demonstrates how to initialize a YouTube object with different combinations of extraction methods, including local, remote, or both. ```swift // Use local extraction with remote fallback let video = YouTube(videoID: "QdBZY2fkU-0", methods: [.local, .remote]) // Use only remote extraction let video2 = YouTube(videoID: "QdBZY2fkU-0", methods: [.remote]) // Use only local (will fail on watchOS) let video3 = YouTube(videoID: "QdBZY2fkU-0", methods: [.local]) ``` -------------------------------- ### Load with AVPlayerViewController Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/Livestream.md Example demonstrating how to load and present a livestream using AVPlayerViewController. ```APIDOC ## Load with AVPlayerViewController ```swift import AVKit let livestream = try await YouTube(videoID: livestreamID).livestreams .filter { $0.streamType == .hls } .first if let url = livestream?.url { let player = AVPlayer(url: url) let controller = AVPlayerViewController() controller.player = player controller.showsPlaybackControls = true // Present the controller present(controller, animated: true) { player.play() } } ``` ``` -------------------------------- ### Usage Examples for Codec Comparison Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/Codecs.md Demonstrates how to use the defined equality operators for checking codecs, including direct comparisons and comparisons with optional codecs. ```swift let stream = streams.first // Check base codec without unwrapping if stream?.videoCodec == .h264 { print("H.264 codec") } if stream?.audioCodec != .opus { print("Not Opus audio") } // Works with optional codecs if let videoCodec = stream?.videoCodec, videoCodec == .av1 { print("AV1 video") } ``` -------------------------------- ### Play a livestream Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/Livestream.md Example demonstrating how to retrieve and play an HLS livestream using AVPlayer. ```APIDOC ## Play a livestream ```swift let video = YouTube(videoID: "21X5lGlDOfg") do { let livestreams = try await video.livestreams // Find first HLS livestream if let livestream = livestreams .filter({ $0.streamType == .hls }) .first { let player = AVPlayer(url: livestream.url) // Present player } else { print("No livestream available") } } catch { print("Failed to get livestream: \(error)") } ``` ``` -------------------------------- ### Initialize YouTubeKit and Get Streams Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/README.md Initialize the YouTubeKit with a video ID and retrieve all available streams. This is the primary entry point for accessing video data. ```swift import YouTubeKit let video = YouTube(videoID: "QdBZY2fkU-0") let streams = try await video.streams ``` -------------------------------- ### Initialize and Get Streams Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/README.md Initializes the YouTubeKit with a video ID and retrieves all available video streams. This is a fundamental step for accessing video content. ```APIDOC ## Initialize and Get Streams ### Description Initializes the YouTubeKit with a video ID and retrieves all available video streams. This is a fundamental step for accessing video content. ### Method Swift (Conceptual) ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```swift import YouTubeKit let video = YouTube(videoID: "QdBZY2fkU-0") let streams = try await video.streams ``` ### Response #### Success Response An array of `Stream` objects representing all downloadable video streams. #### Response Example ```swift // streams will be an array of Stream objects ``` ``` -------------------------------- ### Get Best M4A Audio-Only URL Source: https://github.com/alexeichhorn/youtubekit/blob/main/README.md Example for obtaining the best m4a audio-only stream URL for a given YouTube ID. Filters for audio-only streams and the m4a file extension, then selects the highest bitrate. ```swift let stream = try await YouTube(videoID: "9bZkp7q19f0").streams .filterAudioOnly() .filter { $0.fileExtension == .m4a } .highestAudioBitrateStream() let streamURL = stream.url ``` -------------------------------- ### Play YouTube Video in AVPlayer Source: https://github.com/alexeichhorn/youtubekit/blob/main/README.md Example demonstrating how to extract a natively playable video stream and play it using AVPlayer. Filters for video and audio tracks and selects the highest resolution. ```swift let stream = try await YouTube(videoID: "QdBZY2fkU-0").streams .filterVideoAndAudio() .filter { $0.isNativelyPlayable } .highestResolutionStream() let player = AVPlayer(url: stream!.url) // -> Now present the player however you like ``` -------------------------------- ### VideoCodec Usage Example Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/types.md Demonstrates how to use the VideoCodec enum to check and print information about a video stream's codec. This is useful for conditional logic based on codec type. ```swift let stream = streams.first if let videoCodec = stream?.videoCodec { switch videoCodec { case .h264(let version): print("H.264 codec, version: \(version)") case .av1(let version): print("AV1 codec, version: \(version)") case .vp9(let version): print("VP9 codec (requires transcoding)") case .unknown(let codec): print("Unknown codec: \(codec)") } } ``` -------------------------------- ### Get HLS Livestream URL Source: https://github.com/alexeichhorn/youtubekit/blob/main/README.md Example for obtaining the HLS manifest URL for a livestream given a YouTube ID. Filters for streams of type HLS and selects the first one found. ```swift let hlsManifestUrl = try await YouTube(videoID: "21X5lGlDOfg").livestreams .filter { $0.streamType == .hls } .first ``` -------------------------------- ### Configure YouTubeKit for Remote Extraction on watchOS Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/INDEX.md On watchOS, remote extraction is required due to the absence of JavaScriptCore. This example shows how to explicitly configure the YouTube instance to use only the remote method. ```swift let video = YouTube(videoID: videoID, methods: [.remote]) ``` -------------------------------- ### Get Highest Resolution MP4 Video URL Source: https://github.com/alexeichhorn/youtubekit/blob/main/README.md Example for retrieving the MP4 video URL with the highest available resolution for a given YouTube URL. Filters for streams including video and audio and the MP4 file extension, then selects the highest resolution. ```swift let stream = try await YouTube(url: youtubeURL).streams .filter { $0.includesVideoAndAudioTrack && $0.fileExtension == .mp4 } .highestResolutionStream() let streamURL = stream.url ``` -------------------------------- ### Enable OAuth with Token Caching Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/configuration.md Enables OAuth authentication and local token caching for InnerTube requests. Requires separate OAuth credential setup. ```swift let video = YouTube( videoID: videoID, useOAuth: true, allowOAuthCache: true ) // Enables OAuth with token caching for InnerTube requests ``` -------------------------------- ### Get Video Metadata Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/README.md Retrieve metadata for a YouTube video, including its title, description, and thumbnail URL. Load the thumbnail image asynchronously. ```swift if let metadata = try await video.metadata { print("Title: \(metadata.title)") print("Description: \(metadata.description)") if let thumbnail = metadata.thumbnail?.url { // Load thumbnail image } } ``` -------------------------------- ### Filter and Select a Stream Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/TECHNICAL_REFERENCE.md Filter the available streams to find a suitable one for playback. This example selects a video and audio stream that is natively playable and has an MP4 file extension, prioritizing the highest resolution. ```swift // Filter and select a stream let stream = streams .filterVideoAndAudio() .filter { $0.isNativelyPlayable && $0.fileExtension == .mp4 } .highestResolutionStream() // Play the stream if let url = stream?.url { let player = AVPlayer(url: url) } ``` -------------------------------- ### Get Video Metadata and Thumbnail Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/INDEX.md Fetch video metadata including title, description, and thumbnail. If a thumbnail is available, its URL is used to download the image data. ```swift if let metadata = try await YouTube(videoID: videoID).metadata { print("Title: \(metadata.title)") print("Description: \(metadata.description)") if let thumbnail = metadata.thumbnail { let (data, _) = try await URLSession.shared.data(from: thumbnail.url) let image = UIImage(data: data) } } ``` -------------------------------- ### Access YouTube Video Metadata Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/YouTubeMetadata.md Instantiate a YouTube object with a video ID and asynchronously retrieve its metadata. This is the primary way to get video details. ```swift let video = YouTube(videoID: videoID) let metadata = try await video.metadata ``` -------------------------------- ### Get YouTube Video Metadata Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/YouTube.md Retrieves metadata for a video, such as title, description, and thumbnail. This method uses local extraction and may return nil if metadata extraction fails. ```swift public var metadata: YouTubeMetadata? { get async throws } ``` ```swift if let metadata = try await YouTube(videoID: "QdBZY2fkU-0").metadata { print("Title: \(metadata.title)") print("Description: \(metadata.description)") if let thumbnail = metadata.thumbnail { print("Thumbnail: \(thumbnail.url)") } } ``` -------------------------------- ### Initialize YouTube with URL Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/YouTube.md Initializes a YouTube object using a full YouTube URL. Handles proxy configuration, OAuth, and extraction method preferences. ```swift public convenience init( url: URL, proxies: [String: URL] = [:\n useOAuth: Bool = false, allowOAuthCache: Bool = false, methods: [ExtractionMethod] = .default ) ``` ```swift let url = URL(string: "https://www.youtube.com/watch?v=QdBZY2fkU-0")! let video = YouTube(url: url) ``` -------------------------------- ### YouTube Initializer with URL Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/configuration.md Initializes YouTubeKit with a YouTube URL and optional configuration parameters. ```swift public convenience init( url: URL, proxies: [String: URL] = [:] useOAuth: Bool = false, allowOAuthCache: Bool = false, methods: [ExtractionMethod] = .default ) ``` -------------------------------- ### Recommended YouTube Initialization Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/INDEX.md Configure YouTubeKit to prioritize local extraction and fall back to remote extraction if local fails. This provides a balance between performance and compatibility. ```swift YouTube(videoID: videoID, methods: [.local, .remote]) // Tries local first, falls back to remote ``` -------------------------------- ### Check if video is livestream Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/Livestream.md Example showing how to check if a video is currently a livestream. ```APIDOC ## Check if video is livestream ```swift let video = YouTube(videoID: videoID) do { let livestreams = try await video.livestreams if !livestreams.isEmpty { print("This is a livestream") // Use livestream URL } else { print("Not a livestream, get regular streams instead") let streams = try await video.streams } } catch { print("Error: \(error)") } ``` ``` -------------------------------- ### Get Lowest/Highest Resolution Stream Source: https://github.com/alexeichhorn/youtubekit/blob/main/README.md Retrieve the stream with the lowest or highest resolution from the available streams. ```swift let lowestResolution = streams.lowestResolutionStream() let highestResolution = streams.highestResolutionStream() ``` -------------------------------- ### YouTube Initializer Parameters Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/INDEX.md Initialize the YouTube class with a video ID and optional configuration parameters. Supports specifying proxies, OAuth usage, token caching, and extraction methods. ```swift YouTube( videoID: String, // 11-char ID proxies: [String: URL] = [:], // Not implemented useOAuth: Bool = false, // InnerTube auth allowOAuthCache: Bool = false, // Token caching methods: [ExtractionMethod] = .default // Extraction methods ) ``` -------------------------------- ### Get Lowest/Highest Audio Bitrate Stream Source: https://github.com/alexeichhorn/youtubekit/blob/main/README.md Retrieve the stream with the lowest or highest audio bitrate from the available streams. ```swift let lowestAudioBitrate = streams.lowestAudioBitrateStream() let highestAudioBitrate = streams.highestAudioBitrateStream() ``` -------------------------------- ### Create YouTube Object with Video URL Source: https://github.com/alexeichhorn/youtubekit/blob/main/README.md Initialize a YouTube object using a video URL. ```swift let video = YouTube(url: videoURL) ``` -------------------------------- ### Optimal Configuration for Most Apps Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/configuration.md This configuration uses the fastest method (local JavaScript extraction) with a remote fallback for broader compatibility. ```swift let video = YouTube( videoID: videoID, methods: [.local, .remote] ) // Uses fastest method (local JS) with remote fallback ``` -------------------------------- ### Stream Resolution Filtering Extensions Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/types.md Get the lowest or highest resolution stream, or filter streams based on a custom resolution predicate. ```swift func lowestResolutionStream() -> Stream? func highestResolutionStream() -> Stream? func filter(byResolution: (Int?) -> Bool) -> [Stream] ``` -------------------------------- ### Get Video Metadata Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/README.md Retrieves metadata for a YouTube video, including its title, description, and thumbnail URL. This is essential for displaying video information. ```APIDOC ## Get Video Metadata ### Description Retrieves metadata for a YouTube video, including its title, description, and thumbnail URL. This is essential for displaying video information. ### Method Swift (Conceptual) ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```swift if let metadata = try await video.metadata { print("Title: \(metadata.title)") print("Description: \(metadata.description)") if let thumbnail = metadata.thumbnail?.url { // Load thumbnail image } } ``` ### Response #### Success Response A `YouTubeMetadata` object containing the video's title, description, and thumbnail information. #### Response Example ```swift // metadata will be a YouTubeMetadata object ``` ``` -------------------------------- ### Configure Remote Extraction with Default Server Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/TECHNICAL_REFERENCE.md Initializes the YouTube object to use the default public remote extraction server. This method works on all platforms, including watchOS. ```swift // Use default public server let video = YouTube(videoID: videoID, methods: [.remote]) ``` -------------------------------- ### Select Streams by Specific Criteria Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/Stream.md Demonstrates how to filter streams based on various criteria such as exact resolution, resolution range, codec, and whether they contain only video or audio. ```swift let streams = try await YouTube(videoID: videoID).streams // All 1080p streams let highRes = streams.streams(withExactResolution: 1080) // All streams below 1080p let lowRes = streams.filter { $0.videoResolution.map { $0 < 1080 } ?? false } // Best video-only VP9 stream (for combining with audio) let videoOnly = streams .filterVideoOnly() .filter { $0.videoCodec == .vp9 } .highestResolutionStream() // Best audio-only stream let audioOnly = streams .filterAudioOnly() .highestAudioBitrateStream() ``` -------------------------------- ### HTTP Proxy Configuration Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/configuration.md Sets up HTTP and HTTPS proxy URLs for network requests. Note: This parameter is not currently implemented. ```swift let proxies: [String: URL] = [ "http": URL(string: "http://proxy.example.com:8080")!, "https": URL(string: "https://secure-proxy.example.com:8443")! ] let video = YouTube( videoID: videoID, proxies: proxies ) ``` -------------------------------- ### AudioCodec Enum Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/Codecs.md Represents audio codec formats used in YouTube streams. It includes properties to get the base codec and check for native playability. ```APIDOC ## AudioCodec Enum Represents audio codec formats used in YouTube streams. ```swift public enum AudioCodec: Codec, Equatable { case mp4a(version: String) case opus case ec3 case ac3 case unknown(codec: String) } ``` ### Supported Codecs | Case | Full Name | Type | Natively Playable | |------|-----------|------|------------------| | mp4a | AAC | MPEG-4 audio | Yes | | opus | Opus | Modern audio | No | | ac3 | Dolby Digital | Surround audio | Yes* | | ec3 | Dolby Digital Plus | Enhanced surround | Yes* | *ac3 and ec3 are playable on iOS, macOS, tvOS but not on watchOS. ### Parsing Codec strings are parsed as `base.version`, e.g.: - "mp4a.40.2" → `.mp4a(version: "40.2")` (AAC-LC) - "opus" → `.opus` (no version) - "ac-3" → `.ac3` - "ec-3" → `.ec3` ### Properties #### baseCodec ```swift var baseCodec: AudioCodec.BaseCodec? ``` Returns the codec type without version information. ```swift enum BaseCodec { case mp4a case opus case ec3 case ac3 } ``` #### isNativelyPlayable ```swift public var isNativelyPlayable: Bool ``` Returns true if the codec can be natively decoded on the current device. **Playability by Codec:** | Codec | iOS | macOS | tvOS | watchOS | |-------|-----|-------|------|---------| | mp4a (AAC) | ✓ | ✓ | ✓ | ✓ | | opus | ✗ | ✗ | ✗ | ✗ | | ac3 | ✓ | ✓ | ✓ | ✗ | | ec3 | ✓ | ✓ | ✓ | ✗ | **Example:** ```swift // Get audio-only streams that can be natively played let audio = try await YouTube(videoID: videoID).streams .filterAudioOnly() .filter { $0.audioCodec?.isNativelyPlayable ?? false } .highestAudioBitrateStream() ``` ``` -------------------------------- ### VideoCodec Enum Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/Codecs.md Represents video codec formats used in YouTube streams. It includes properties to get the base codec and check for native playability. ```APIDOC ## VideoCodec Enum Represents video codec formats used in YouTube streams. ```swift public enum VideoCodec: Codec { case mp4v(version: String) case av1(version: String) case avc1(version: String) case vp9(version: String) case unknown(codec: String) } ``` ### Supported Codecs | Case | Full Name | Type | Natively Playable | |------|-----------|------|------------------| | avc1 | H.264 / AVC | MPEG-4 Part 10 | Yes (most profiles) | | mp4v | MPEG-4 Part 2 | MPEG-4 | Yes | | av1 | AV1 | Modern codec | Conditional (hardware dependent) | | vp9 | VP9 | WebM codec | No | ### Parsing Codec strings from YouTube are parsed as `base.version`, e.g.: - "avc1.64002A" → `.avc1(version: "64002A")` (H.264 Main Profile Level 4.2) - "av01.0.09M.08" → `.av1(version: "0.09M.08")` - "mp4v.20.9" → `.mp4v(version: "20.9")` - "vp09.00.41.08" → `.vp9(version: "00.41.08")` ### Properties #### baseCodec ```swift var baseCodec: VideoCodec.BaseCodec? ``` Returns the codec type without version information. ```swift enum BaseCodec { case mp4v case av1 case avc1 case vp9 } ``` **Usage:** ```swift let stream = streams.first if stream?.videoCodec?.baseCodec == .avc1 { print("H.264 codec detected") } ``` #### isNativelyPlayable ```swift public var isNativelyPlayable: Bool ``` Returns true if the codec can be natively decoded by AVPlayer on the current device/OS. **Playability by Codec:** | Codec | iOS | macOS | tvOS | watchOS | Notes | |-------|-----|-------|------|---------|-------| | avc1 (H.264) | ✓ | ✓ | ✓ | ✓* | *Most profiles; some fail on watchOS | | mp4v (MPEG-4) | ✓ | ✓ | ✓ | ✓ | Always playable | | av1 | ✓* | ✓* | ✓* | ✗ | *Requires hardware support | | vp9 | ✗ | ✗ | ✗ | ✗ | Requires transcoding | **AV1 Hardware Detection:** On iOS 13.0+, macOS 10.15+, tvOS 13.0+ (excluding watchOS), uses `VideoToolbox.VTIsHardwareDecodeSupported()` to check for AV1 hardware decoding capability. **H.264 Profile Limitation:** On watchOS, H.264 profile "64002A" (High Profile Level 4.2) is not natively playable; other profiles are. **Example:** ```swift let streams = try await YouTube(videoID: videoID).streams // Get only natively playable streams let playable = streams.filter { (stream.videoCodec?.isNativelyPlayable ?? true) && (stream.audioCodec?.isNativelyPlayable ?? true) } let best = playable.highestResolutionStream() if let url = best?.url { let player = AVPlayer(url: url) } ``` ``` -------------------------------- ### Stream Average Bitrate Property Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/Stream.md Get the average bitrate in bits per second (bps), typically used for adaptive streams. This is nil if unavailable. ```swift public let averageBitrate: Int? ``` -------------------------------- ### YouTubeKit Best Practices Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/TECHNICAL_REFERENCE.md Outlines best practices for using the YouTubeKit library, including fallback methods, stream filtering, and error recovery. ```markdown 1. **Use fallback methods**: `[.local, .remote]` for robustness 2. **Check native playability**: Filter streams with `isNativelyPlayable` 3. **Handle age-gated videos**: May require retries 4. **Cache appropriately**: Streams URLs can expire after hours/days 5. **Error recovery**: Provide user feedback for each error type 6. **Privacy**: If using remote extraction, use trusted server 7. **Platforms**: Remember watchOS requires remote extraction ``` -------------------------------- ### YouTube Initializer with Video ID Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/configuration.md Initializes YouTubeKit with a video ID and optional configuration parameters. ```swift public init( videoID: String, proxies: [String: URL] = [:] useOAuth: Bool = false, allowOAuthCache: Bool = false, methods: [ExtractionMethod] = .default ) ``` -------------------------------- ### Stream Audio Codec Property Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/Stream.md Get the audio codec used in the stream, such as AAC or Opus. This property is nil if the stream does not contain an audio track. ```swift public let audioCodec: AudioCodec? ``` -------------------------------- ### Initialize YouTube with Video ID Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/YouTube.md Initializes a YouTube object using a video ID. Supports optional proxies, OAuth, and custom extraction methods. ```swift public init( videoID: String, proxies: [String: URL] = [:\n useOAuth: Bool = false, allowOAuthCache: Bool = false, methods: [ExtractionMethod] = .default ) ``` ```swift let video = YouTube(videoID: "QdBZY2fkU-0") ``` -------------------------------- ### Stream Video Codec Property Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/Stream.md Get the video codec used in the stream, such as H.264 or VP9. This property is nil if the stream does not contain a video track. ```swift public let videoCodec: VideoCodec? ``` -------------------------------- ### Get Best Audio-Only Stream Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/INDEX.md Extract the audio-only stream with the highest bitrate available for a given video. This is useful for applications that only require audio playback. ```swift let stream = try await YouTube(videoID: videoID).streams .filterAudioOnly() .highestAudioBitrateStream() let audioURL = stream?.url ``` -------------------------------- ### Configure Remote Extraction with Custom Server Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/TECHNICAL_REFERENCE.md Initializes the YouTube object to use a custom remote extraction server URL. This allows for private or self-hosted extraction endpoints. ```swift // Use custom server let custom = URL(string: "https://my-server.com")! let video = YouTube(videoID: videoID, methods: [.remote(serverURL: custom)]) ``` -------------------------------- ### Get Best Audio-Only Stream in M4A Format Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/Stream.md Fetches the audio stream with the highest bitrate in M4A format. This is suitable for scenarios where only audio playback is required. ```swift let stream = try await YouTube(videoID: "9bZkp7q19f0").streams .filterAudioOnly() .filter { $0.fileExtension == .m4a } .highestAudioBitrateStream() let audioURL = stream?.url ``` -------------------------------- ### FileExtension Initializer Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/FileExtension.md Creates a FileExtension from a MIME type string. It maps full MIME types to appropriate extensions, falls back to subtype matching if the full type is not found, and returns .unknown for unrecognized MIME types. ```APIDOC ## init(mimeType:) ### Description Creates a FileExtension from a MIME type string. ### Parameters #### Path Parameters - **mimeType** (String) - Description: MIME type (e.g., "video/mp4", "audio/mpeg", "audio/mp4") ### Request Example ```swift let ext1 = FileExtension(mimeType: "video/mp4") // .mp4 let ext2 = FileExtension(mimeType: "audio/mpeg") // .mp3 let ext3 = FileExtension(mimeType: "audio/mp4") // .m4a let ext4 = FileExtension(mimeType: "application/unknown") // .unknown ``` ``` -------------------------------- ### Build Video Info UI with SwiftUI Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/YouTubeMetadata.md A SwiftUI View that asynchronously fetches and displays YouTube video metadata, including title, description, and thumbnail. Uses the .task modifier for data fetching. ```swift struct VideoInfoView: View { @State private var metadata: YouTubeMetadata? @State private var thumbnailImage: UIImage? let videoID: String var body: some View { VStack(alignment: .leading) { if let image = thumbnailImage { Image(uiImage: image) .resizable() .aspectRatio(contentMode: .fit) } if let metadata = metadata { Text(metadata.title) .font(.headline) .lineLimit(2) Text(metadata.description) .font(.caption) .lineLimit(3) .foregroundColor(.secondary) } } .task { do { let video = YouTube(videoID: videoID) metadata = try await video.metadata if let url = metadata?.thumbnail?.url { let (data, _) = try await URLSession.shared.data(from: url) thumbnailImage = UIImage(data: data) } } catch { print("Error: \(error)") } } } } ``` -------------------------------- ### Stream videoResolution Computed Property Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/Stream.md Gets the vertical pixel dimension of the video resolution (e.g., 1080 for 1080p). Returns nil if the stream has no video track. ```swift public var videoResolution: Int? ``` -------------------------------- ### Create YouTube Object with Video ID Source: https://github.com/alexeichhorn/youtubekit/blob/main/README.md Initialize a YouTube object using a video ID. ```swift let video = YouTube(videoID: videoID) ``` -------------------------------- ### YouTube Initializer (URL) Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/YouTube.md Initializes a YouTube video object using a full YouTube URL. This convenience initializer handles extracting the video ID from the URL and supports the same configuration options as the video ID initializer. ```APIDOC ## init(url:proxies:useOAuth:allowOAuthCache:methods:) ### Description Initializes a YouTube video object using a full YouTube URL. This convenience initializer automatically extracts the video ID from the provided URL and configures the object with optional proxies, OAuth settings, and extraction methods. ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Parameters - **url** (URL) - Required - Full YouTube URL (e.g., "https://www.youtube.com/watch?v=QdBZY2fkU-0") - **proxies** ([String: URL]) - Optional - Proxy URLs for HTTP requests. Defaults to []. - **useOAuth** (Bool) - Optional - Whether to use OAuth authentication. Defaults to false. - **allowOAuthCache** (Bool) - Optional - Whether to cache OAuth tokens. Defaults to false. - **methods** ([ExtractionMethod]) - Optional - Extraction methods in priority order. Defaults to .default. ### Request Example ```swift let url = URL(string: "https://www.youtube.com/watch?v=QdBZY2fkU-0")! let video = YouTube(url: url) ``` ### Response (None - Initializer) ### Throws No direct exceptions from init, but video ID extraction may fail for invalid URLs. ``` -------------------------------- ### YouTube Class Reference Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/MANIFEST.txt The main entry point for the YouTubeKit SDK. This class allows initialization with a video ID or URL and provides access to video streams, metadata, and livestreams. It also includes a method to check video availability. ```APIDOC ## YouTube Class ### Description The primary class for interacting with YouTube videos. It serves as the main entry point for the YouTubeKit SDK, allowing users to fetch video details and streams. ### Initializers - **`init(videoID: String)`** Initializes the YouTube object with a given video ID. - **`init(url: URL)`** Initializes the YouTube object with a given YouTube video URL. ### Properties - **`videoID: String`** The unique identifier of the YouTube video. - **`streams: [Stream]`** An array of available `Stream` objects for the video. - **`metadata: YouTubeMetadata`** Metadata associated with the YouTube video, such as title and description. - **`livestreams: [Livestream]`** An array of available livestream objects for the video. ### Methods - **`checkAvailability() -> Bool`** Checks if the video is available. Returns `true` if available, `false` otherwise. ### Nested Types - **`ExtractionMethod`** (enum) Configuration options for stream extraction. ### Caching Behavior Details on how the SDK caches video data to improve performance. ### Complete Examples Refer to the `README.md` and `INDEX.md` for comprehensive usage examples. ``` -------------------------------- ### Initialize FileExtension from MIME Type Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/types.md Demonstrates creating a FileExtension enum case from a MIME type string. It maps common MIME types to their corresponding file extensions, returning .unknown for unrecognized types. ```swift init(mimeType: String) ``` -------------------------------- ### Get YouTube Livestream HLS URL Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/YouTube.md Retrieves the HLS manifest URL for livestream videos. This method currently only supports HLS format and returns a single master playlist URL. ```swift public var livestreams: [Livestream] { get async throws } ``` ```swift let livestream = try await YouTube(videoID: "21X5lGlDOfg").livestreams .filter { $0.streamType == .hls } .first if let hlsURL = livestream?.url { let player = AVPlayer(url: hlsURL) } ``` -------------------------------- ### VideoCodec Enum Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/types.md Represents video codec formats and versions, including associated types for base codec and properties for native playability. It details how codec strings are parsed and provides usage examples. ```APIDOC ## VideoCodec Enum Represents video codec formats and versions. ### Associated Type: BaseCodec ```swift public enum BaseCodec { case mp4v case av1 case avc1 case vp9 } ``` ### Properties | Name | Type | Description | |------|------|-------------| | baseCodec | BaseCodec? | Returns the base codec type without version info | | isNativelyPlayable | Bool | Returns true if the codec can be natively decoded on current device | ### Details **Format:** Codec strings from YouTube are parsed as `name.version`, e.g., "avc1.64002A" where "avc1" is the codec and "64002A" is the version. **Native Playability:** - `avc1` (H.264): Always playable except on watchOS for certain profile versions - `mp4v`: Always playable - `av1`: Playable only on devices with hardware AV1 decoding support - `vp9`: Never natively playable (requires transcoding) ### Usage ```swift let stream = streams.first if let videoCodec = stream?.videoCodec { switch videoCodec { case .h264(let version): print("H.264 codec, version: \(version)") case .av1(let version): print("AV1 codec, version: \(version)") case .vp9(let version): print("VP9 codec (requires transcoding)") case .unknown(let codec): print("Unknown codec: \(codec)") } } ``` ``` -------------------------------- ### Select best natively playable format Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/Codecs.md Filters video and audio streams to find the one with the highest resolution that is natively playable on the current device. This is useful for ensuring smooth playback. ```swift let video = YouTube(videoID: "QdBZY2fkU-0") let streams = try await video.streams let stream = streams .filterVideoAndAudio() .filter { let videoPlayable = $0.videoCodec?.isNativelyPlayable ?? true let audioPlayable = $0.audioCodec?.isNativelyPlayable ?? true return videoPlayable && audioPlayable } .highestResolutionStream() if let url = stream?.url { let player = AVPlayer(url: url) } ``` -------------------------------- ### FileExtension Initializer from MIME Type Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/FileExtension.md Creates a FileExtension instance from a MIME type string. It maps full MIME types, falls back to subtype matching, and returns .unknown for unrecognized types. ```swift init(mimeType: String) ``` ```swift let ext1 = FileExtension(mimeType: "video/mp4") // .mp4 let ext2 = FileExtension(mimeType: "audio/mpeg") // .mp3 let ext3 = FileExtension(mimeType: "audio/mp4") // .m4a let ext4 = FileExtension(mimeType: "application/unknown") // .unknown ``` -------------------------------- ### Determine Save Filename with File Extension Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/FileExtension.md Determines a suitable filename for saving a downloaded stream by appending the appropriate file extension based on the stream's file extension. For example, 'video.mp4' or 'video.webm'. ```swift if let stream = try await YouTube(videoID: videoID).streams .filterVideoAndAudio() .highestResolutionStream() { let filename = "video.\(stream.fileExtension.rawValue)" // filename would be "video.mp4", "video.webm", etc. } ``` -------------------------------- ### YouTube Initializer (Video ID) Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/YouTube.md Initializes a YouTube video object using its unique video ID. Supports optional proxies, OAuth, and custom extraction methods. ```APIDOC ## init(videoID:proxies:useOAuth:allowOAuthCache:methods:) ### Description Initializes a YouTube video object using its 11-character video ID. This initializer allows for configuration of proxies, OAuth usage, and the preferred extraction methods. ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Parameters - **videoID** (String) - Required - 11-character YouTube video ID (e.g., "QdBZY2fkU-0") - **proxies** ([String: URL]) - Optional - Proxy URLs for HTTP requests (currently not installed) - **useOAuth** (Bool) - Optional - Whether to use OAuth authentication for InnerTube requests. Defaults to false. - **allowOAuthCache** (Bool) - Optional - Whether to cache OAuth tokens. Defaults to false. - **methods** ([ExtractionMethod]) - Optional - Extraction methods in priority order (see ExtractionMethod enum). Defaults to .default. ### Request Example ```swift let video = YouTube(videoID: "QdBZY2fkU-0") ``` ### Response (None - Initializer) ### Throws No direct exceptions from init, but errors may be thrown when accessing streams or metadata properties. ``` -------------------------------- ### Offline-First Configuration (iOS/macOS) Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/configuration.md This configuration prioritizes local extraction and will fail if there is no internet connection or if JavaScript extraction fails. It is useful for testing local extraction. ```swift // Fails if no internet or JavaScript fails // Good for testing local extraction let video = YouTube( videoID: videoID, methods: [.local] ) ``` -------------------------------- ### AudioCodec Enum Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/types.md Represents audio codec formats and versions, including associated types for base codec and properties for native playability. It details native support across different platforms and provides usage examples. ```APIDOC ## AudioCodec Enum Represents audio codec formats and versions. ### Associated Type: BaseCodec ```swift public enum BaseCodec { case mp4a case opus case ec3 case ac3 } ``` ### Properties | Name | Type | Description | |------|------|-------------| | baseCodec | BaseCodec? | Returns the base codec type | | isNativelyPlayable | Bool | Returns true if codec is natively supported on current device | ### Details **Format:** Similar to VideoCodec, parsed from codec strings like "mp4a.40.2". **Native Playability:** - `mp4a` (AAC): Always playable - `opus`: Never natively playable - `ac3`: Playable on iOS, macOS, tvOS; not on watchOS - `ec3` (enhanced AC-3): Playable on iOS, macOS, tvOS; not on watchOS ### Usage ```swift let streams = try await YouTube(videoID: videoID).streams let audioStreams = streams.filterAudioOnly() .filter { $0.audioCodec?.isNativelyPlayable ?? false } ``` ``` -------------------------------- ### Stream File Extension Property Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/Stream.md Obtain the recommended file extension for the stream, like 'mp4' or 'webm'. ```swift public let fileExtension: FileExtension ``` -------------------------------- ### Get best AV1 stream with fallback to H.264 Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/Codecs.md Attempts to find the highest resolution AV1 stream that is natively playable. If no AV1 stream is found, it falls back to finding the highest resolution H.264 stream. ```swift let streams = try await YouTube(videoID: videoID).streams let filterVideoAndAudio = streams.filterVideoAndAudio() // Try to get AV1 if supported if let av1Stream = filterVideoAndAudio .filter { $0.videoCodec == .av1 && $0.videoCodec?.isNativelyPlayable == true } .highestResolutionStream() { return av1Stream.url } // Fallback to H.264 if let h264Stream = filterVideoAndAudio .filter { $0.videoCodec == .avc1 } .highestResolutionStream() { return h264Stream.url } ``` -------------------------------- ### YouTubeKit Source Organization Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/TECHNICAL_REFERENCE.md Details the directory structure and main files within the YouTubeKit Swift project. ```markdown Sources/YouTubeKit/ ├── YouTube.swift # Main class ├── Models/ │ ├── Stream.swift # Stream structure + extensions │ ├── ITag.swift # iTag definitions and properties │ ├── FileExtension.swift # File extension enum │ ├── Codecs.swift # VideoCodec and AudioCodec │ ├── Method.swift # ExtractionMethod enum │ ├── Livestream.swift # Livestream structure │ ├── YouTubeMetadata.swift # Metadata structure │ └── StreamQuery.swift # Stream filtering extensions ├── Errors.swift # Error types ├── Extraction.swift # HTML/JS extraction utilities ├── InnerTube.swift # InnerTube API client ├── Cipher.swift # Signature cipher handling ├── SignatureSolver.swift # JavaScript signature solver ├── Parser.swift # HTML parsing utilities ├── Remote/ │ ├── RemoteYouTubeClient.swift # WebSocket client │ ├── Chunking.swift # Message chunking │ ├── AppIdentity.swift # App identification │ └── Models/RemoteStream.swift # Remote stream model └── Extensions/ ├── Foundation.swift # String/Collection utilities ├── RegularExpression.swift # Regex helper ├── Retry.swift # Retry logic ├── WebSocket.swift # WebSocket extensions ├── URLSessionDelegates.swift # Custom session delegates ├── Logging.swift # Logging utilities ├── Concurrency.swift # Async utilities ├── AsyncCompatibility.swift # Older OS compatibility └── Lazy.swift # Lazy evaluation ``` -------------------------------- ### Configure Local Extraction Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/TECHNICAL_REFERENCE.md Initializes the YouTube object to use only local extraction methods. This is suitable for iOS, macOS, tvOS, and visionOS. ```swift let video = YouTube(videoID: videoID, methods: [.local]) ``` -------------------------------- ### Share Video Information Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/YouTubeMetadata.md Constructs a shareable text string containing the video's title, a truncated description, and the YouTube URL. Presents a UIActivityViewController for sharing. ```swift let video = YouTube(videoID: videoID) if let metadata = try await video.metadata { let shareText = """ \(metadata.title) \(metadata.description.prefix(100))... https://youtube.com/watch?v=\(video.videoID) """ let activityVC = UIActivityViewController( activityItems: [shareText], applicationActivities: nil ) present(activityVC, animated: true) } ``` -------------------------------- ### YouTubeKit Related Documentation Links Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/TECHNICAL_REFERENCE.md Provides links to other relevant documentation pages for YouTubeKit, including API, types, errors, and configuration. ```markdown - [API Reference](api-reference/) - Detailed documentation per class/type - [Types Reference](types.md) - All public types and enums - [Errors Reference](errors.md) - Error types and handling - [Configuration Reference](configuration.md) - Constructor options ``` -------------------------------- ### ITag Properties and Initializer Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/ITag.md This snippet details the core properties of the ITag struct, including the raw `itag` value, and the initializer used to create an ITag instance from a numeric ID. It also shows how to access computed properties like `videoResolution` and `audioBitrate`. ```APIDOC ## ITag Structure Represents YouTube's internal format identifier and associated metadata for a stream. ### Properties #### itag ```swift let itag: Int ``` The numeric iTag value (e.g., 22, 18, 137). This value is read-only and set during initialization. ### Initializer #### init(_:) ```swift init?(_ itag: Int) ``` Creates an ITag from a numeric iTag value. | Parameter | |-----------| | itag (Int) - Required - Numeric YouTube iTag value | **Returns:** An ITag instance, or nil if the iTag is not recognized. **Example:** ```swift if let iTag = ITag(22) { print("iTag 22 resolution: \(iTag.videoResolution)p") // Output: iTag 22 resolution: 720p } else { print("Unknown iTag") } ``` ``` -------------------------------- ### Enable Remote Fallback for Extraction Source: https://github.com/alexeichhorn/youtubekit/blob/main/README.md Configure YouTubeKit to use a remote fallback server (youtube-dl) in addition to local extraction. Specify the desired methods in priority order. ```swift let streams = try await YouTube(videoID: "2lAe1CQCOXo", methods: [.local, .remote]).streams ``` -------------------------------- ### Initialize ITag from Integer Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/api-reference/ITag.md Creates an ITag instance from a numeric iTag value. Returns nil if the iTag is not recognized. ```swift init?(_ itag: Int) ``` ```swift if let iTag = ITag(22) { print("iTag 22 resolution: \(iTag.videoResolution)p") // Output: iTag 22 resolution: 720p } else { print("Unknown iTag") } ``` -------------------------------- ### Play a Livestream Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/INDEX.md Retrieve the first available livestream URL for a given video ID and initialize an AVPlayer with it. ```swift if let livestream = try await YouTube(videoID: livestreamID).livestreams.first { let player = AVPlayer(url: livestream.url) } ``` -------------------------------- ### Retrieve and Display YouTube Video Metadata Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/types.md Shows how to fetch YouTube video metadata using its ID and print the title. It also demonstrates how to access the thumbnail URL if available. ```swift if let metadata = try await YouTube(videoID: "QdBZY2fkU-0").metadata { print("Title: \(metadata.title)") if let thumbnail = metadata.thumbnail { // Load thumbnail image from metadata.thumbnail.url } } ``` -------------------------------- ### Stream Bitrate Selection Extensions Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/types.md Select streams based on the lowest or highest audio bitrate. ```swift func lowestAudioBitrateStream() -> Stream? func highestAudioBitrateStream() -> Stream? ``` -------------------------------- ### Pre-check Video Availability Source: https://github.com/alexeichhorn/youtubekit/blob/main/_autodocs/errors.md Check video availability before attempting to load streams, catching specific errors like `videoPrivate`. This approach prevents unnecessary operations and provides immediate feedback on video accessibility. ```swift let video = YouTube(videoID: videoID) do { try await video.checkAvailability() let streams = try await video.streams // Use streams... } catch YouTubeKitError.videoPrivate { showAlert("Video is private") } catch { showAlert("Error: \(error.localizedDescription)") } ```