Skip to content

YouDash brings native YouTube to Apple CarPlay with YouMod ad blocking, responsive layouts, and an on-screen keyboard. Open-source iOS integration. Formerly YouTube Car.

120 KB
Raw Blame
// HUGE thanks to @daisuke1227 for implementing all of this
#import "Headers.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import <math.h>
#import <objc/message.h>
#import <objc/runtime.h>
#import <dlfcn.h>
#import <stdarg.h>
#import <stdlib.h>
#import <YouTubeHeader/YTDefaultSheetController.h>
#import <YouTubeHeader/YTIFormatStream.h>
#import <YouTubeHeader/YTIPlayerResponse.h>
#import <YouTubeHeader/YTPlayerResponse.h>
#import <YouTubeHeader/YTIVideoDetails.h>

@interface YTDefaultSheetController (YouModDownload)
+ (instancetype)sheetControllerWithParentResponder:(id)parentResponder;
- (void)addAction:(YTActionSheetAction *)action;
- (void)presentFromView:(UIView *)view animated:(BOOL)animated completion:(void (^)(void))completion;
- (void)presentFromViewController:(UIViewController *)vc animated:(BOOL)animated completion:(void (^)(void))completion;
@end

@interface YTPlayerViewController (YouModDownload)
- (YTPlayerResponse *)contentPlayerResponse;
@end

@interface YTIPlayerResponse (YouModDownload)
- (id)streamingData;
@end

@interface YTIStreamingData : NSObject
- (NSArray *)adaptiveFormatsArray;
@end

@interface YTIFormatStream (YouModDownload)
- (NSString *)mimeType;
- (BOOL)hasContentLength;
- (unsigned long long)contentLength;
- (unsigned long long)approxDurationMs;
@end

@interface YTIVideoDetails (YouModDownload)
- (NSString *)title;
- (NSString *)author;
- (NSString *)shortDescription;
@end

static UIImage *YouModIconImage(NSInteger iconType) {
    YTIIcon *icon = [%c(YTIIcon) new];
    icon.iconType = iconType;
    UIImage *image = [icon iconImageWithColor:[UIColor labelColor]];
    return [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
}

@interface YouModMenuItem : NSObject
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;
@property (nonatomic, strong) UIImage *iconImage;
@property (nonatomic, copy) void (^handler)(void);
+ (instancetype)itemWithTitle:(NSString *)title subtitle:(NSString *)subtitle handler:(void (^)(void))handler;
+ (instancetype)itemWithTitle:(NSString *)title subtitle:(NSString *)subtitle icon:(UIImage *)icon handler:(void (^)(void))handler;
@end

@implementation YouModMenuItem
+ (instancetype)itemWithTitle:(NSString *)title subtitle:(NSString *)subtitle handler:(void (^)(void))handler {
    return [self itemWithTitle:title subtitle:subtitle icon:nil handler:handler];
}
+ (instancetype)itemWithTitle:(NSString *)title subtitle:(NSString *)subtitle icon:(UIImage *)icon handler:(void (^)(void))handler {
    YouModMenuItem *item = [YouModMenuItem new];
    item.title = title;
    item.subtitle = subtitle;
    item.iconImage = icon;
    item.handler = handler;
    return item;
}
@end

@interface YouModMediaFormat : NSObject
@property (nonatomic, strong) id source;
@property (nonatomic, copy) NSString *urlString;
@property (nonatomic, copy) NSString *qualityLabel;
@property (nonatomic, copy) NSString *mimeType;
@property (nonatomic, copy) NSDictionary *httpHeaders;
@property (nonatomic, assign) unsigned long long contentLength;
@property (nonatomic, assign) unsigned long long durationMs;
@property (nonatomic, assign) NSInteger fps;
@property (nonatomic, assign) BOOL video;
@property (nonatomic, copy) NSString *languageCode;
@property (nonatomic, copy) NSString *languageName;
@property (nonatomic, assign) BOOL drcAudio;
@end

@implementation YouModMediaFormat
@end

@interface YouModAudioOutputFormat : NSObject
@property (nonatomic, copy) NSString *identifier;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;
@property (nonatomic, copy) NSString *fileExtension;
@property (nonatomic, copy) NSArray <NSString *> *ffmpegArguments;
@property (nonatomic, assign) BOOL passthroughWhenCompatible;
@property (nonatomic, assign) BOOL supported;
@end

@implementation YouModAudioOutputFormat
@end

typedef void (^YouModFileDownloadCompletion)(NSURL *fileURL, NSError *error);
typedef void (^YouModMergeCompletion)(BOOL success, NSError *error);
typedef void (^YouModRangeDownloadProgress)(unsigned long long completedBytes);

@interface YouModDownloadChunk : NSObject
@property (nonatomic, assign) unsigned long long offset;
@property (nonatomic, assign) unsigned long long length;
@property (nonatomic, assign) NSUInteger attempts;
@end

@implementation YouModDownloadChunk
@end

@interface YouModRangeDownloader : NSObject
@property (nonatomic, strong) NSURL *url;
@property (nonatomic, strong) NSURL *destinationURL;
@property (nonatomic, copy) NSDictionary *httpHeaders;
@property (nonatomic, assign) unsigned long long expectedBytes;
@property (nonatomic, copy) YouModRangeDownloadProgress progress;
@property (nonatomic, copy) YouModFileDownloadCompletion completion;
@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic, strong) NSFileHandle *fileHandle;
@property (nonatomic, strong) NSMutableArray <YouModDownloadChunk *> *pendingChunks;
@property (nonatomic, strong) NSMutableSet <NSURLSessionDataTask *> *tasks;
@property (nonatomic, strong) dispatch_queue_t stateQueue;
@property (nonatomic, strong) dispatch_queue_t fileQueue;
@property (nonatomic, assign) NSUInteger activeTaskCount;
@property (nonatomic, assign) NSUInteger totalChunkCount;
@property (nonatomic, assign) unsigned long long completedBytes;
@property (nonatomic, assign) BOOL cancelled;
@property (nonatomic, assign) BOOL finished;
- (instancetype)initWithURL:(NSURL *)url destinationURL:(NSURL *)destinationURL expectedBytes:(unsigned long long)expectedBytes headers:(NSDictionary *)headers progress:(YouModRangeDownloadProgress)progress completion:(YouModFileDownloadCompletion)completion;
- (void)start;
- (void)cancel;
@end

@interface YouModDownloadCoordinator : NSObject <NSURLSessionDownloadDelegate>
@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic, strong) NSURLSessionDownloadTask *task;
@property (nonatomic, strong) NSURLSessionDataTask *metadataTask;
@property (nonatomic, strong) YouModRangeDownloader *rangeDownloader;
@property (nonatomic, strong) UIAlertController *progressAlert;
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, weak) UIViewController *presenter;
@property (nonatomic, copy) YouModFileDownloadCompletion fileCompletion;
@property (nonatomic, strong) NSURL *destinationURL;
@property (nonatomic, strong) NSURL *videoTempURL;
@property (nonatomic, strong) NSURL *audioTempURL;
@property (nonatomic, assign) unsigned long long completedBytes;
@property (nonatomic, assign) unsigned long long totalBytes;
@property (nonatomic, assign) unsigned long long currentBytes;
@property (nonatomic, assign) unsigned long long currentExpectedBytes;
@property (nonatomic, assign) BOOL currentResolvedSizeAddedToTotal;
@property (nonatomic, assign) BOOL active;
@property (nonatomic, assign) BOOL finishedCurrentFile;
@property (nonatomic, assign) BOOL cancelled;
@property (nonatomic, copy) NSString *baseProgressTitle;
@property (nonatomic, assign) NSTimeInterval downloadStartTime;
+ (instancetype)sharedCoordinator;
- (void)startVideoDownloadWithVideoFormat:(YouModMediaFormat *)videoFormat audioFormat:(YouModMediaFormat *)audioFormat fileName:(NSString *)fileName videoID:(NSString *)videoID presenter:(UIViewController *)presenter;
- (void)startAudioDownloadWithAudioFormat:(YouModMediaFormat *)audioFormat fileName:(NSString *)fileName videoID:(NSString *)videoID presenter:(UIViewController *)presenter;
- (void)startAudioDownloadWithAudioFormat:(YouModMediaFormat *)audioFormat fileName:(NSString *)fileName videoID:(NSString *)videoID outputFormat:(YouModAudioOutputFormat *)outputFormat presenter:(UIViewController *)presenter;
- (void)startDirectVideoDownloadWithVideoFormat:(YouModMediaFormat *)videoFormat audioFormat:(YouModMediaFormat *)audioFormat fileName:(NSString *)fileName videoID:(NSString *)videoID presenter:(UIViewController *)presenter;
- (void)startDirectSingleVideoDownloadWithFormat:(YouModMediaFormat *)format fileName:(NSString *)fileName videoID:(NSString *)videoID presenter:(UIViewController *)presenter;
- (void)startDirectAudioDownloadWithAudioFormat:(YouModMediaFormat *)audioFormat fileName:(NSString *)fileName videoID:(NSString *)videoID presenter:(UIViewController *)presenter;
- (void)startDirectAudioDownloadWithAudioFormat:(YouModMediaFormat *)audioFormat fileName:(NSString *)fileName videoID:(NSString *)videoID outputFormat:(YouModAudioOutputFormat *)outputFormat presenter:(UIViewController *)presenter;
- (void)mergeVideoURL:(NSURL *)videoURL audioURL:(NSURL *)audioURL fileName:(NSString *)fileName outputExtension:(NSString *)outputExtension durationMs:(unsigned long long)durationMs presenter:(UIViewController *)presenter;
- (void)mergeVideoWithAVFoundationVideoURL:(NSURL *)videoURL audioURL:(NSURL *)audioURL outputURL:(NSURL *)outputURL durationMs:(unsigned long long)durationMs presenter:(UIViewController *)presenter fallbackError:(NSError *)fallbackError;
- (void)trimSingleVideoURL:(NSURL *)inputURL outputURL:(NSURL *)outputURL durationMs:(unsigned long long)durationMs presenter:(UIViewController *)presenter;
- (void)convertAudioURL:(NSURL *)inputURL outputURL:(NSURL *)outputURL outputFormat:(YouModAudioOutputFormat *)outputFormat durationMs:(unsigned long long)durationMs presenter:(UIViewController *)presenter;
@end

static const unsigned long long YouModFastDownloadMinimumBytes = 256ULL * 1024ULL;
static const unsigned long long YouModFastDownloadChunkBytes = 4ULL * 1024ULL * 1024ULL;
static const NSUInteger YouModFastDownloadConcurrency = 8;
static const NSUInteger YouModFastDownloadMaxAttempts = 3;

static BOOL YouModHTTPHeadersContainField(NSDictionary *headers, NSString *field) {
    for (id key in headers) {
        if ([key isKindOfClass:NSString.class] && [(NSString *)key caseInsensitiveCompare:field] == NSOrderedSame)
            return YES;
    }
    return NO;
}

static NSString *YouModYouTubeCookiesString(void) {
    NSMutableArray *cookieStrings = [NSMutableArray array];
    for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
        if ([cookie.domain containsString:@"youtube.com"]) {
            [cookieStrings addObject:[NSString stringWithFormat:@"%@=%@", cookie.name, cookie.value]];
        }
    }
    return [cookieStrings componentsJoinedByString:@"; "];
}

static NSString *YouModNativeUserAgent(void) {
    NSString *version = @"21.18.4";
    NSString *sysVersion = [[UIDevice currentDevice].systemVersion stringByReplacingOccurrencesOfString:@"." withString:@"_"] ?: @"18_7";
    return [NSString stringWithFormat:@"com.google.ios.youtube/%@ (iPhone; CPU iPhone OS %@ like Mac OS X)", version, sysVersion];
}

static void YouModApplyDownloadHeaders(NSMutableURLRequest *request, NSDictionary *headers) {
    for (id key in headers) {
        id value = headers[key];
        if ([key isKindOfClass:NSString.class] && [value isKindOfClass:NSString.class])
            [request setValue:value forHTTPHeaderField:key];
    }
    if (!YouModHTTPHeadersContainField(headers, @"User-Agent"))
        [request setValue:YouModNativeUserAgent() forHTTPHeaderField:@"User-Agent"];
    if (!YouModHTTPHeadersContainField(headers, @"Origin"))
        [request setValue:@"https://www.youtube.com" forHTTPHeaderField:@"Origin"];
    if (!YouModHTTPHeadersContainField(headers, @"Referer"))
        [request setValue:@"https://www.youtube.com/" forHTTPHeaderField:@"Referer"];
    if (!YouModHTTPHeadersContainField(headers, @"Cookie")) {
        NSString *cookies = YouModYouTubeCookiesString();
        if (cookies.length > 0) [request setValue:cookies forHTTPHeaderField:@"Cookie"];
    }
    extern NSString *YouModGlobalAuthHeader;
    if (YouModGlobalAuthHeader && !YouModHTTPHeadersContainField(headers, @"Authorization")) {
        [request setValue:YouModGlobalAuthHeader forHTTPHeaderField:@"Authorization"];
    }
    [request setValue:@"identity" forHTTPHeaderField:@"Accept-Encoding"];
}

@implementation YouModRangeDownloader

- (instancetype)initWithURL:(NSURL *)url destinationURL:(NSURL *)destinationURL expectedBytes:(unsigned long long)expectedBytes headers:(NSDictionary *)headers progress:(YouModRangeDownloadProgress)progress completion:(YouModFileDownloadCompletion)completion {
    self = [super init];
    if (self) {
        _url = url;
        _destinationURL = destinationURL;
        _httpHeaders = [headers copy];
        _expectedBytes = expectedBytes;
        _progress = [progress copy];
        _completion = [completion copy];
        _pendingChunks = [NSMutableArray array];
        _tasks = [NSMutableSet set];
        _stateQueue = dispatch_queue_create("com.youmod.download.range.state", DISPATCH_QUEUE_SERIAL);
        _fileQueue = dispatch_queue_create("com.youmod.download.range.file", DISPATCH_QUEUE_SERIAL);

        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        configuration.HTTPMaximumConnectionsPerHost = YouModFastDownloadConcurrency;
        configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
        configuration.timeoutIntervalForResource = 300;
        NSMutableDictionary *additionalHeaders = [NSMutableDictionary dictionary];
        for (id key in headers) {
            id value = headers[key];
            if ([key isKindOfClass:NSString.class] && [value isKindOfClass:NSString.class])
                additionalHeaders[key] = value;
        }
        if (!YouModHTTPHeadersContainField(additionalHeaders, @"User-Agent"))
            additionalHeaders[@"User-Agent"] = YouModNativeUserAgent();
        if (!YouModHTTPHeadersContainField(additionalHeaders, @"Origin"))
            additionalHeaders[@"Origin"] = @"https://www.youtube.com";
        if (!YouModHTTPHeadersContainField(additionalHeaders, @"Referer"))
            additionalHeaders[@"Referer"] = @"https://www.youtube.com/";
        if (!YouModHTTPHeadersContainField(additionalHeaders, @"Cookie")) {
            NSString *cookies = YouModYouTubeCookiesString();
            if (cookies.length > 0) additionalHeaders[@"Cookie"] = cookies;
        }
        extern NSString *YouModGlobalAuthHeader;
        if (YouModGlobalAuthHeader && !YouModHTTPHeadersContainField(additionalHeaders, @"Authorization")) {
            additionalHeaders[@"Authorization"] = YouModGlobalAuthHeader;
        }
        additionalHeaders[@"Accept-Encoding"] = @"identity";
        configuration.HTTPAdditionalHeaders = additionalHeaders;
        _session = [NSURLSession sessionWithConfiguration:configuration];
    }
    return self;
}

- (NSError *)errorWithCode:(NSInteger)code message:(NSString *)message {
    return [NSError errorWithDomain:@"YouMod" code:code userInfo:@{NSLocalizedDescriptionKey: message ?: @"Download failed"}];
}

- (BOOL)prepareDestinationWithError:(NSError **)error {
    [NSFileManager.defaultManager removeItemAtURL:self.destinationURL error:nil];
    if (![NSFileManager.defaultManager createFileAtPath:self.destinationURL.path contents:nil attributes:nil]) {
        if (error) *error = [self errorWithCode:20 message:@"Cannot create file"];
        return NO;
    }

    self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:self.destinationURL.path];
    if (!self.fileHandle) {
        if (error) *error = [self errorWithCode:21 message:@"Cannot open file"];
        return NO;
    }

    @try {
        [self.fileHandle truncateFileAtOffset:self.expectedBytes];
    } @catch (NSException *exception) {
        if (error) *error = [self errorWithCode:22 message:exception.reason ?: @"Cannot allocate file"];
        return NO;
    }
    return YES;
}

- (void)start {
    dispatch_async(self.stateQueue, ^{
        if (self.expectedBytes == 0) {
            [self finishWithErrorLocked:[self errorWithCode:23 message:@"Unknown stream size"]];
            return;
        }

        NSError *error = nil;
        if (![self prepareDestinationWithError:&error]) {
            [self finishWithErrorLocked:error];
            return;
        }

        unsigned long long chunkSize = self.expectedBytes / YouModFastDownloadConcurrency;
        if (chunkSize < 256ULL * 1024ULL) chunkSize = 256ULL * 1024ULL;
        if (chunkSize > YouModFastDownloadChunkBytes) chunkSize = YouModFastDownloadChunkBytes;

        for (unsigned long long offset = 0; offset < self.expectedBytes; offset += chunkSize) {
            YouModDownloadChunk *chunk = [YouModDownloadChunk new];
            chunk.offset = offset;
            unsigned long long remaining = self.expectedBytes - offset;
            chunk.length = remaining < chunkSize ? remaining : chunkSize;
            [self.pendingChunks addObject:chunk];
        }
        self.totalChunkCount = self.pendingChunks.count;
        [self scheduleChunksLocked];
    });
}

- (void)cancel {
    dispatch_async(self.stateQueue, ^{
        if (self.finished) return;
        self.cancelled = YES;
        self.finished = YES;
        for (NSURLSessionDataTask *task in self.tasks) [task cancel];
        [self.tasks removeAllObjects];
        [self.session invalidateAndCancel];
        dispatch_async(self.fileQueue, ^{
            @try {
                [self.fileHandle closeFile];
            } @catch (__unused NSException *exception) {
            }
            [NSFileManager.defaultManager removeItemAtURL:self.destinationURL error:nil];
        });
    });
}

- (void)scheduleChunksLocked {
    if (self.finished || self.cancelled) return;
    while (self.activeTaskCount < YouModFastDownloadConcurrency && self.pendingChunks.count > 0) {
        YouModDownloadChunk *chunk = self.pendingChunks.firstObject;
        [self.pendingChunks removeObjectAtIndex:0];
        [self startChunkLocked:chunk];
    }

    if (self.activeTaskCount == 0 && self.pendingChunks.count == 0) {
        [self finishSuccessfullyLocked];
    }
}

- (void)startChunkLocked:(YouModDownloadChunk *)chunk {
    unsigned long long end = chunk.offset + chunk.length - 1;
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:self.url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
    YouModApplyDownloadHeaders(request, self.httpHeaders);
    [request setValue:[NSString stringWithFormat:@"bytes=%llu-%llu", chunk.offset, end] forHTTPHeaderField:@"Range"];

    __weak typeof(self) weakSelf = self;
    __block NSURLSessionDataTask *task = nil;
    task = [self.session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        __strong typeof(weakSelf) self = weakSelf;
        if (!self) return;
        [self completeChunk:chunk task:task data:data response:response error:error];
    }];
    [self.tasks addObject:task];
    self.activeTaskCount++;
    [task resume];
}

- (NSError *)validationErrorForChunk:(YouModDownloadChunk *)chunk data:(NSData *)data response:(NSURLResponse *)response error:(NSError *)error {
    if (error) return error;

    NSHTTPURLResponse *httpResponse = [response isKindOfClass:NSHTTPURLResponse.class] ? (NSHTTPURLResponse *)response : nil;
    NSInteger statusCode = httpResponse.statusCode;
    BOOL statusOK = statusCode == 206 || (self.totalChunkCount == 1 && statusCode == 200);
    if (httpResponse && !statusOK)
        return [self errorWithCode:24 message:@"Range request rejected by server"];

    if (data.length != chunk.length)
        return [self errorWithCode:25 message:@"Incomplete chunk"];

    return nil;
}

- (void)completeChunk:(YouModDownloadChunk *)chunk task:(NSURLSessionDataTask *)task data:(NSData *)data response:(NSURLResponse *)response error:(NSError *)error {
    dispatch_async(self.stateQueue, ^{
        if (self.activeTaskCount > 0) self.activeTaskCount--;
        if (task) [self.tasks removeObject:task];
        if (self.finished || self.cancelled) return;

        NSError *validationError = [self validationErrorForChunk:chunk data:data response:response error:error];
        if (validationError) {
            if (validationError.code == 24) {
                [self finishWithErrorLocked:validationError];
                return;
            }
            if (chunk.attempts + 1 < YouModFastDownloadMaxAttempts) {
                chunk.attempts++;
                [self.pendingChunks insertObject:chunk atIndex:0];
                [self scheduleChunksLocked];
            } else {
                [self finishWithErrorLocked:validationError];
            }
            return;
        }

        NSData *chunkData = [data copy];
        dispatch_async(self.fileQueue, ^{
            NSError *writeError = nil;
            @try {
                [self.fileHandle seekToFileOffset:chunk.offset];
                [self.fileHandle writeData:chunkData];
            } @catch (NSException *exception) {
                writeError = [self errorWithCode:26 message:exception.reason ?: @"Write failed"];
            }

            dispatch_async(self.stateQueue, ^{
                if (self.finished || self.cancelled) return;
                if (writeError) {
                    [self finishWithErrorLocked:writeError];
                    return;
                }

                self.completedBytes += chunkData.length;
                if (self.progress) {
                    unsigned long long completed = self.completedBytes;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.progress(completed);
                    });
                }
                [self scheduleChunksLocked];
            });
        });
    });
}

- (void)finishSuccessfullyLocked {
    if (self.finished) return;
    self.finished = YES;
    [self.session finishTasksAndInvalidate];
    dispatch_async(self.fileQueue, ^{
        @try {
            [self.fileHandle closeFile];
        } @catch (__unused NSException *exception) {
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.completion) self.completion(self.destinationURL, nil);
        });
    });
}

- (void)finishWithErrorLocked:(NSError *)error {
    if (self.finished) return;
    self.finished = YES;
    for (NSURLSessionDataTask *task in self.tasks) [task cancel];
    [self.tasks removeAllObjects];
    [self.session invalidateAndCancel];
    dispatch_async(self.fileQueue, ^{
        @try {
            [self.fileHandle closeFile];
        } @catch (__unused NSException *exception) {
        }
        [NSFileManager.defaultManager removeItemAtURL:self.destinationURL error:nil];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.completion) self.completion(nil, error ?: [self errorWithCode:27 message:@"Download failed"]);
        });
    });
}

@end

static __weak YTPlayerViewController *YouModCurrentPlayerViewController;

void YouModDownloadSetCurrentPlayer(YTPlayerViewController *player) {
    YouModCurrentPlayerViewController = player;
}

static NSString *YouModStringFromSelector(id object, SEL selector) {
    if (!object) return nil;
    id value = nil;
    if ([object respondsToSelector:selector]) {
        value = ((id (*)(id, SEL))objc_msgSend)(object, selector);
    } else {
        @try {
            value = [object valueForKey:NSStringFromSelector(selector)];
        } @catch (__unused NSException *exception) {
            value = nil;
        }
    }
    if ([value isKindOfClass:NSString.class]) return value;
    if ([value isKindOfClass:NSURL.class]) return [(NSURL *)value absoluteString];
    if ([value respondsToSelector:@selector(stringValue)]) return [value stringValue];
    return [value respondsToSelector:@selector(description)] ? [value description] : nil;
}

static id YouModObjectFromSelector(id object, SEL selector) {
    if (!object) return nil;
    if ([object respondsToSelector:selector]) {
        return ((id (*)(id, SEL))objc_msgSend)(object, selector);
    }
    @try {
        return [object valueForKey:NSStringFromSelector(selector)];
    } @catch (__unused NSException *exception) {
        return nil;
    }
}

static unsigned long long YouModUnsignedLongLongFromSelector(id object, SEL selector) {
    if (!object) return 0;
    if ([object respondsToSelector:selector]) {
        return ((unsigned long long (*)(id, SEL))objc_msgSend)(object, selector);
    }
    @try {
        id value = [object valueForKey:NSStringFromSelector(selector)];
        if ([value respondsToSelector:@selector(unsignedLongLongValue)])
            return [value unsignedLongLongValue];
    } @catch (__unused NSException *exception) {
    }
    return 0;
}

static BOOL YouModBoolFromSelector(id object, SEL selector) {
    if (!object) return NO;
    if ([object respondsToSelector:selector]) {
        return ((BOOL (*)(id, SEL))objc_msgSend)(object, selector);
    }
    @try {
        id value = [object valueForKey:NSStringFromSelector(selector)];
        if ([value respondsToSelector:@selector(boolValue)])
            return [value boolValue];
    } @catch (__unused NSException *exception) {
    }
    return NO;
}

static NSInteger YouModIntegerFromSelector(id object, SEL selector) {
    if (!object) return 0;
    if ([object respondsToSelector:selector]) {
        return ((NSInteger (*)(id, SEL))objc_msgSend)(object, selector);
    }
    @try {
        id value = [object valueForKey:NSStringFromSelector(selector)];
        if ([value respondsToSelector:@selector(integerValue)])
            return [value integerValue];
    } @catch (__unused NSException *exception) {
    }
    return 0;
}

static UIViewController *YouModTopViewController(UIViewController *root) {
    if (!root) {
        UIWindow *keyWindow = nil;
        for (UIWindow *window in UIApplication.sharedApplication.windows) {
            if (window.isKeyWindow) {
                keyWindow = window;
                break;
            }
        }
        root = keyWindow.rootViewController;
    }
    while (root.presentedViewController) root = root.presentedViewController;
    if ([root isKindOfClass:UINavigationController.class])
        return YouModTopViewController(((UINavigationController *)root).topViewController);
    if ([root isKindOfClass:UITabBarController.class])
        return YouModTopViewController(((UITabBarController *)root).selectedViewController);
    return root;
}

static void YouModSendToast(NSString *message, id responder) {
    Class toastClass = NSClassFromString(@"YTToastResponderEvent");
    id event = [toastClass eventWithMessage:message firstResponder:responder ?: YouModTopViewController(nil)];
    if ([event respondsToSelector:@selector(send)]) {
        [event send];
        return;
    }

    UIViewController *presenter = YouModTopViewController([responder isKindOfClass:UIViewController.class] ? responder : nil);
    if (!presenter) return;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    [presenter presentViewController:alert animated:YES completion:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [alert dismissViewControllerAnimated:YES completion:nil];
        });
    }];
}

static NSString *YouModByteCount(unsigned long long bytes) {
    if (bytes == 0) return nil;
    NSByteCountFormatter *formatter = [NSByteCountFormatter new];
    formatter.countStyle = NSByteCountFormatterCountStyleFile;
    return [formatter stringFromByteCount:(long long)bytes];
}

static NSString *YouModGenerateCPN(void) {
    static NSString *const alphabet = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    NSMutableString *nonce = [NSMutableString stringWithCapacity:16];
    for (NSUInteger i = 0; i < 16; i++)
        [nonce appendFormat:@"%C", [alphabet characterAtIndex:arc4random_uniform((uint32_t)alphabet.length)]];
    return nonce;
}

static NSString *YouModURLStringBypassingThrottle(NSString *urlString) {
    if (urlString.length == 0) return urlString;
    NSURLComponents *components = [NSURLComponents componentsWithString:urlString];
    if (components) {
        NSMutableArray *queryItems = [components.queryItems mutableCopy] ?: [NSMutableArray array];
        NSMutableArray *filtered = [NSMutableArray array];
        for (NSURLQueryItem *item in queryItems) {
            if (![item.name isEqualToString:@"n"])
                [filtered addObject:item];
        }
        BOOL hasRateBypass = NO;
        for (NSURLQueryItem *item in filtered) {
            if ([item.name isEqualToString:@"ratebypass"]) { hasRateBypass = YES; break; }
        }
        if (!hasRateBypass)
            [filtered addObject:[NSURLQueryItem queryItemWithName:@"ratebypass" value:@"yes"]];
        components.queryItems = filtered;
        NSString *result = components.string;
        if (result.length > 0) return result;
    }
    return urlString;
}

static NSString *YouModURLStringWithCPN(NSString *urlString) {
    if (urlString.length == 0) return urlString;
    urlString = YouModURLStringBypassingThrottle(urlString);
    if ([urlString containsString:@"cpn="]) return urlString;
    Class ytDataUtils = NSClassFromString(@"YTDataUtils");
    NSString *cpn = ((id (*)(Class, SEL))objc_msgSend)(ytDataUtils, @selector(generateClientSideNonce));
    if (![cpn isKindOfClass:NSString.class] || cpn.length == 0)
        cpn = YouModGenerateCPN();
    NSString *separator = [urlString containsString:@"?"] ? @"&" : @"?";
    return [NSString stringWithFormat:@"%@%@cpn=%@", urlString, separator, cpn];
}

static NSString *YouModSanitizedFileName(NSString *name) {
    if (name.length == 0) return @"YouTube Video";
    NSMutableCharacterSet *invalid = [NSMutableCharacterSet characterSetWithCharactersInString:@"/\\?%*|\"<>:"];
    [invalid formUnionWithCharacterSet:NSCharacterSet.newlineCharacterSet];
    NSArray *parts = [name componentsSeparatedByCharactersInSet:invalid];
    NSString *clean = [[parts componentsJoinedByString:@" "] stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
    while ([clean containsString:@"  "]) clean = [clean stringByReplacingOccurrencesOfString:@"  " withString:@" "];
    if (clean.length > 120) clean = [clean substringToIndex:120];
    return clean.length ? clean : @"YouTube Video";
}

static NSURL *YouModDownloadsDirectoryURL(void) {
    NSURL *documentsURL = [NSFileManager.defaultManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask].firstObject;
    NSURL *downloadsURL = [documentsURL URLByAppendingPathComponent:@"YouMod Downloads" isDirectory:YES];
    [NSFileManager.defaultManager createDirectoryAtURL:downloadsURL withIntermediateDirectories:YES attributes:nil error:nil];
    return downloadsURL;
}

static NSString *YouModLastDownloadDiagnostic;

static NSURL *YouModDiagnosticLogURL(void) {
    return [YouModDownloadsDirectoryURL() URLByAppendingPathComponent:@"youmod-download-diagnostics.txt"];
}

static void YouModRecordDownloadDiagnostic(NSString *context, NSString *details) {
    if (context.length == 0 && details.length == 0) return;

    NSDateFormatter *formatter = [NSDateFormatter new];
    formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss ZZZZZ";
    NSString *timestamp = [formatter stringFromDate:NSDate.date];
    NSString *entry = [NSString stringWithFormat:@"[%@]\n%@\n%@\n\n", timestamp ?: @"", context ?: @"", details ?: @""];
    YouModLastDownloadDiagnostic = entry;

    NSURL *logURL = YouModDiagnosticLogURL();
    NSData *data = [entry dataUsingEncoding:NSUTF8StringEncoding];
    if (![NSFileManager.defaultManager fileExistsAtPath:logURL.path])
        [NSFileManager.defaultManager createFileAtPath:logURL.path contents:nil attributes:nil];

    NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:logURL.path];
    if (!handle) return;
    @try {
        [handle seekToEndOfFile];
        [handle writeData:data];
        [handle closeFile];
    } @catch (__unused NSException *exception) {
    }
}

static NSString *YouModDownloadDiagnosticText(void) {
    if (YouModLastDownloadDiagnostic.length) return YouModLastDownloadDiagnostic;
    NSString *log = [NSString stringWithContentsOfURL:YouModDiagnosticLogURL() encoding:NSUTF8StringEncoding error:nil];
    if (log.length == 0) return nil;
    NSUInteger maxLength = 12000;
    return log.length > maxLength ? [log substringFromIndex:log.length - maxLength] : log;
}

static void YouModCopyDownloadDiagnostics(UIViewController *presenter) {
    NSString *diagnostic = YouModDownloadDiagnosticText();
    if (diagnostic.length == 0) {
        YouModSendToast(@"No download diagnostics yet.", presenter);
        return;
    }
    UIPasteboard.generalPasteboard.string = diagnostic;
    YouModSendToast(@"Copied download diagnostics", presenter);
}

static NSURL *YouModUniqueFileURL(NSString *fileName, NSString *extension) {
    NSString *safeName = YouModSanitizedFileName(fileName);
    NSURL *directoryURL = YouModDownloadsDirectoryURL();
    NSURL *candidate = [directoryURL URLByAppendingPathComponent:[safeName stringByAppendingPathExtension:extension]];
    NSUInteger index = 2;
    while ([NSFileManager.defaultManager fileExistsAtPath:candidate.path]) {
        NSString *indexed = [NSString stringWithFormat:@"%@ %lu", safeName, (unsigned long)index++];
        candidate = [directoryURL URLByAppendingPathComponent:[indexed stringByAppendingPathExtension:extension]];
    }
    return candidate;
}

static NSURL *YouModTemporaryFileURL(NSString *extension) {
    NSString *name = [[NSUUID UUID].UUIDString stringByAppendingPathExtension:extension];
    return [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:name]];
}

static NSInteger YouModResolutionFromQuality(NSString *quality);
static NSInteger YouModFPSFromQuality(NSString *quality);
static NSInteger YouModNormalizedFPS(NSInteger fps);
static NSInteger YouModDisplayHeightForVideoHeight(NSInteger height);
static NSString *YouModQualityLabel(NSInteger height, NSInteger fps, NSString *fallback);
static BOOL YouModFFmpegKitAvailable(void);

static unsigned long long YouModDurationMsForURL(NSURL *url) {
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];
    if (!CMTIME_IS_NUMERIC(asset.duration) || !CMTIME_IS_VALID(asset.duration)) return 0;
    Float64 seconds = CMTimeGetSeconds(asset.duration);
    if (!isfinite(seconds) || seconds <= 0.0) return 0;
    return (unsigned long long)llround(seconds * 1000.0);
}

static NSString *YouModDurationSecondsArgument(unsigned long long durationMs) {
    return [NSString stringWithFormat:@"%.3f", (double)durationMs / 1000.0];
}

static BOOL YouModCMTimeIsUsable(CMTime time) {
    if (!CMTIME_IS_VALID(time) || !CMTIME_IS_NUMERIC(time) || CMTIME_IS_INDEFINITE(time)) return NO;
    Float64 seconds = CMTimeGetSeconds(time);
    return isfinite(seconds) && seconds > 0.0;
}

static CMTime YouModMinUsableDuration(CMTime first, CMTime second) {
    BOOL firstOK = YouModCMTimeIsUsable(first);
    BOOL secondOK = YouModCMTimeIsUsable(second);
    if (firstOK && secondOK) return CMTIME_COMPARE_INLINE(first, <, second) ? first : second;
    if (firstOK) return first;
    if (secondOK) return second;
    return kCMTimeInvalid;
}

static CMTime YouModExportDuration(AVAsset *videoAsset, AVAsset *audioAsset, unsigned long long expectedDurationMs) {
    CMTime duration = kCMTimeInvalid;
    if (expectedDurationMs > 0)
        duration = CMTimeMakeWithSeconds((double)expectedDurationMs / 1000.0, 600);

    CMTime videoDuration = YouModMinUsableDuration(videoAsset.duration, [[videoAsset tracksWithMediaType:AVMediaTypeVideo] firstObject].timeRange.duration);
    CMTime audioDuration = audioAsset ? YouModMinUsableDuration(audioAsset.duration, [[audioAsset tracksWithMediaType:AVMediaTypeAudio] firstObject].timeRange.duration) : kCMTimeInvalid;
    CMTime mediaDuration = audioAsset ? YouModMinUsableDuration(videoDuration, audioDuration) : videoDuration;

    if (!YouModCMTimeIsUsable(duration)) return mediaDuration;
    if (YouModCMTimeIsUsable(mediaDuration) && CMTIME_COMPARE_INLINE(duration, >, mediaDuration))
        return mediaDuration;
    return duration;
}

static NSMutableArray <NSString *> *YouModFFmpegKitLoadEntries(void) {
    static NSMutableArray <NSString *> *entries = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        entries = [NSMutableArray array];
    });
    return entries;
}

static void YouModAppendFFmpegKitLoadEntry(NSString *format, ...) {
    if (format.length == 0) return;

    va_list arguments;
    va_start(arguments, format);
    NSString *entry = [[NSString alloc] initWithFormat:format arguments:arguments];
    va_end(arguments);
    if (entry.length == 0) return;

    NSMutableArray <NSString *> *entries = YouModFFmpegKitLoadEntries();
    @synchronized(entries) {
        [entries addObject:entry];
        if (entries.count > 220)
            [entries removeObjectsInRange:NSMakeRange(0, entries.count - 220)];
    }
}

static NSArray <NSString *> *YouModFFmpegKitSearchDirectories(void) {
    NSMutableOrderedSet <NSString *> *directories = [NSMutableOrderedSet orderedSet];
    
    // Path to YouMod.bundle/Frameworks inside the main app bundle
    NSString *bundlePath = [[NSBundle.mainBundle resourcePath] stringByAppendingPathComponent:@"YouMod.bundle"];
    NSString *frameworksInsideBundle = [bundlePath stringByAppendingPathComponent:@"Frameworks"];
    
    // Safety check: only add if the directory actually exists
    BOOL isDir = NO;
    if ([[NSFileManager defaultManager] fileExistsAtPath:frameworksInsideBundle isDirectory:&isDir] && isDir) {
        [directories addObject:frameworksInsideBundle];
    }

    return directories.array;
}

static void YouModDlopenPath(NSString *path, BOOL requireExistingFile) {
    if (path.length == 0) return;
    if (requireExistingFile && ![NSFileManager.defaultManager fileExistsAtPath:path]) {
        YouModAppendFFmpegKitLoadEntry(@"missing %@", path);
        return;
    }

    dlerror();
    void *handle = dlopen(path.fileSystemRepresentation, RTLD_NOW | RTLD_GLOBAL);
    const char *error = dlerror();
    if (handle) {
        YouModAppendFFmpegKitLoadEntry(@"loaded %@", path);
    } else {
        YouModAppendFFmpegKitLoadEntry(@"failed %@\n  dlerror=%@", path, error ? [NSString stringWithUTF8String:error] : @"unknown");
    }
}

static void YouModDlopenPathIfPresent(NSString *path) {
    YouModDlopenPath(path, YES);
}

static void YouModLoadFrameworkBinary(NSString *directory, NSString *frameworkName, NSString *binaryName) {
    if (directory.length == 0 || frameworkName.length == 0 || binaryName.length == 0) return;
    YouModDlopenPathIfPresent([[directory stringByAppendingPathComponent:[frameworkName stringByAppendingString:@".framework"]] stringByAppendingPathComponent:binaryName]);
    YouModDlopenPathIfPresent([[directory stringByAppendingPathComponent:[frameworkName stringByAppendingString:@".framework"]] stringByAppendingPathComponent:frameworkName]);
}

static void YouModLoadFFmpegKitIfNeeded(void) {
    static BOOL attempted = NO;
    if (NSClassFromString(@"FFmpegKit")) return;
    if (attempted) return;
    attempted = YES;

    YouModAppendFFmpegKitLoadEntry(@"[YouMod] Starting bundled FFmpegKit load...");

    // Order is important: load dependencies (avutil, etc.) before the main toolkit
    NSArray <NSArray <NSString *> *> *frameworks = @[
        @[@"libavutil", @"libavutil"],
        @[@"libswresample", @"libswresample"],
        @[@"libswscale", @"libswscale"],
        @[@"libavcodec", @"libavcodec"],
        @[@"libavformat", @"libavformat"],
        @[@"libavfilter", @"libavfilter"],
        @[@"libavdevice", @"libavdevice"],
        @[@"ffmpegkit", @"ffmpegkit"],
        @[@"FFmpegKit", @"FFmpegKit"],
    ];

    NSArray *searchDirs = YouModFFmpegKitSearchDirectories();
    if (searchDirs.count == 0) {
        YouModAppendFFmpegKitLoadEntry(@"[YouMod] Error: Bundled Frameworks directory not found.");
        return;
    }

    // Only iterate through our controlled bundle directory
    for (NSString *directory in searchDirs) {
        for (NSArray <NSString *> *framework in frameworks) {
            // This helper uses dlopen on the direct path within our bundle
            YouModLoadFrameworkBinary(directory, framework.firstObject, framework.lastObject);
        }
        
        if (NSClassFromString(@"FFmpegKit")) {
            YouModAppendFFmpegKitLoadEntry(@"[YouMod] Success: FFmpegKit loaded from bundle.");
            return;
        }
    }

    YouModAppendFFmpegKitLoadEntry(@"[YouMod] Critical: FFmpegKit could not be found in YouMod.bundle.");
}

static Class YouModFFmpegKitClass(void) {
    Class ffmpegKitClass = NSClassFromString(@"FFmpegKit");
    if (!ffmpegKitClass) {
        YouModLoadFFmpegKitIfNeeded();
        ffmpegKitClass = NSClassFromString(@"FFmpegKit");
    }
    return ffmpegKitClass;
}

static BOOL YouModFFmpegKitAvailable(void) {
    Class ffmpegKitClass = YouModFFmpegKitClass();
    return ffmpegKitClass && [ffmpegKitClass respondsToSelector:@selector(executeWithArgumentsAsync:withCompleteCallback:withLogCallback:withStatisticsCallback:)];
}

static NSString *YouModFFmpegKitDiagnosticText(YouModAudioOutputFormat *outputFormat, YouModMediaFormat *sourceFormat, NSString *videoID) {
    YouModLoadFFmpegKitIfNeeded();

    Class ffmpegKitClass = NSClassFromString(@"FFmpegKit");
    SEL executeSelector = @selector(executeWithArgumentsAsync:withCompleteCallback:withLogCallback:withStatisticsCallback:);
    NSMutableArray <NSString *> *lines = [NSMutableArray array];
    NSBundle *mainBundle = NSBundle.mainBundle;
    NSString *resourcePath = mainBundle.resourcePath ?: @"";
    NSString *privateFrameworksPath = mainBundle.privateFrameworksPath ?: @"";
    NSString *executablePath = mainBundle.executablePath ?: @"";
    NSString *bundlePath = [resourcePath stringByAppendingPathComponent:@"YouMod.bundle"];
    NSString *packageFrameworkPath = [resourcePath stringByAppendingPathComponent:@"YouMod.bundle/Frameworks"];

    [lines addObject:@"FFmpegKit lookup"];
    [lines addObject:[NSString stringWithFormat:@"videoID=%@", videoID ?: @""]];
    [lines addObject:[NSString stringWithFormat:@"requestedFormat=%@ (%@)", outputFormat.title ?: @"", outputFormat.identifier ?: @""]];
    [lines addObject:[NSString stringWithFormat:@"sourceMime=%@", sourceFormat.mimeType ?: @""]];
    [lines addObject:[NSString stringWithFormat:@"sourceQuality=%@", sourceFormat.qualityLabel ?: @""]];
    [lines addObject:[NSString stringWithFormat:@"sourceBytes=%llu", sourceFormat.contentLength]];
    [lines addObject:[NSString stringWithFormat:@"mainBundle=%@", mainBundle.bundlePath ?: @""]];
    [lines addObject:[NSString stringWithFormat:@"resourcePath=%@", resourcePath]];
    [lines addObject:[NSString stringWithFormat:@"privateFrameworksPath=%@", privateFrameworksPath]];
    [lines addObject:[NSString stringWithFormat:@"executablePath=%@", executablePath]];
    [lines addObject:[NSString stringWithFormat:@"YouMod.bundle exists=%@", [NSFileManager.defaultManager fileExistsAtPath:bundlePath] ? @"YES" : @"NO"]];
    [lines addObject:[NSString stringWithFormat:@"YouMod.bundle/Frameworks exists=%@", [NSFileManager.defaultManager fileExistsAtPath:packageFrameworkPath] ? @"YES" : @"NO"]];
    [lines addObject:[NSString stringWithFormat:@"FFmpegKit class=%@", ffmpegKitClass ? @"YES" : @"NO"]];
    [lines addObject:[NSString stringWithFormat:@"FFmpegKit execute selector=%@", [ffmpegKitClass respondsToSelector:executeSelector] ? @"YES" : @"NO"]];
    [lines addObject:[NSString stringWithFormat:@"ReturnCode class=%@", NSClassFromString(@"ReturnCode") ? @"YES" : @"NO"]];
    [lines addObject:@"searchDirectories:"];
    for (NSString *directory in YouModFFmpegKitSearchDirectories()) {
        BOOL isDirectory = NO;
        BOOL exists = [NSFileManager.defaultManager fileExistsAtPath:directory isDirectory:&isDirectory];
        [lines addObject:[NSString stringWithFormat:@"  %@ exists=%@ directory=%@", directory, exists ? @"YES" : @"NO", isDirectory ? @"YES" : @"NO"]];
    }

    NSMutableArray <NSString *> *entries = YouModFFmpegKitLoadEntries();
    [lines addObject:@"dlopenAttempts:"];
    @synchronized(entries) {
        [lines addObjectsFromArray:entries];
    }
    return [lines componentsJoinedByString:@"\n"];
}

static void YouModCancelFFmpegKit(void) {
    Class ffmpegKitClass = YouModFFmpegKitClass();
    if ([ffmpegKitClass respondsToSelector:@selector(cancel)])
        ((void (*)(Class, SEL))objc_msgSend)(ffmpegKitClass, @selector(cancel));
}

static NSError *YouModFFmpegErrorFromSession(id session) {
    NSString *failure = YouModStringFromSelector(session, @selector(getFailStackTrace));
    NSString *message = failure.length ? failure : @"FFmpeg failed";
    return [NSError errorWithDomain:@"YouMod" code:7 userInfo:@{NSLocalizedDescriptionKey: message}];
}

static BOOL YouModPathExtensionIsPhotosVideo(NSString *extension) {
    NSString *lower = extension.lowercaseString ?: @"";
    return [@[@"mp4", @"m4v", @"mov"] containsObject:lower];
}

static BOOL YouModStartFFmpegKitMerge(NSURL *videoURL, NSURL *audioURL, NSURL *outputURL, unsigned long long durationMs, void (^progress)(float progress), YouModMergeCompletion completion) {
    Class ffmpegKitClass = YouModFFmpegKitClass();
    SEL executeSelector = @selector(executeWithArgumentsAsync:withCompleteCallback:withLogCallback:withStatisticsCallback:);
    if (![ffmpegKitClass respondsToSelector:executeSelector]) return NO;

    NSMutableArray *arguments = [@[
        @"-y",
        @"-i", videoURL.path,
        @"-i", audioURL.path,
        @"-map", @"0:v:0",
        @"-map", @"1:a:0",
    ] mutableCopy];
    if (durationMs > 0)
        [arguments addObjectsFromArray:@[@"-t", YouModDurationSecondsArgument(durationMs)]];
    [arguments addObjectsFromArray:@[
        @"-c", @"copy",
        @"-shortest",
        @"-avoid_negative_ts", @"make_zero",
    ]];
    if (YouModPathExtensionIsPhotosVideo(outputURL.pathExtension))
        [arguments addObjectsFromArray:@[@"-movflags", @"+faststart"]];
    [arguments addObject:outputURL.path];

    id completeBlock = [^(id session) {
        Class returnCodeClass = NSClassFromString(@"ReturnCode");
        id returnCode = YouModObjectFromSelector(session, @selector(getReturnCode));
        BOOL success = NO;
        if ([returnCodeClass respondsToSelector:@selector(isSuccess:)])
            success = ((BOOL (*)(Class, SEL, id))objc_msgSend)(returnCodeClass, @selector(isSuccess:), returnCode);

        NSError *error = success ? nil : YouModFFmpegErrorFromSession(session);
        dispatch_async(dispatch_get_main_queue(), ^{
            if (success && [NSFileManager.defaultManager fileExistsAtPath:outputURL.path]) {
                completion(YES, nil);
            } else {
                completion(NO, error ?: [NSError errorWithDomain:@"YouMod" code:7 userInfo:@{NSLocalizedDescriptionKey: @"Merge failed"}]);
            }
        });
    } copy];

    id statisticsBlock = durationMs ? [^(id statistics) {
        if (!progress || ![statistics respondsToSelector:@selector(getTime)]) return;
        double timeMs = ((double (*)(id, SEL))objc_msgSend)(statistics, @selector(getTime));
        if (!isfinite(timeMs) || timeMs <= 0.0) return;
        float mergeProgress = 0.985f + (0.01f * fminf((float)(timeMs / (double)durationMs), 1.0f));
        dispatch_async(dispatch_get_main_queue(), ^{
            progress(mergeProgress);
        });
    } copy] : nil;

    ((id (*)(Class, SEL, NSArray *, id, id, id))objc_msgSend)(ffmpegKitClass, executeSelector, arguments, completeBlock, nil, statisticsBlock);
    return YES;
}

static BOOL YouModStartFFmpegKitAudioConvert(NSURL *inputURL, NSURL *outputURL, YouModAudioOutputFormat *outputFormat, unsigned long long durationMs, void (^progress)(float progress), YouModMergeCompletion completion) {
    Class ffmpegKitClass = YouModFFmpegKitClass();
    SEL executeSelector = @selector(executeWithArgumentsAsync:withCompleteCallback:withLogCallback:withStatisticsCallback:);
    if (![ffmpegKitClass respondsToSelector:executeSelector] || outputFormat.ffmpegArguments.count == 0) return NO;

    NSMutableArray *arguments = [@[@"-y", @"-i", inputURL.path] mutableCopy];
    [arguments addObjectsFromArray:outputFormat.ffmpegArguments];
    [arguments addObject:outputURL.path];

    id completeBlock = [^(id session) {
        Class returnCodeClass = NSClassFromString(@"ReturnCode");
        id returnCode = YouModObjectFromSelector(session, @selector(getReturnCode));
        BOOL success = NO;
        if ([returnCodeClass respondsToSelector:@selector(isSuccess:)])
            success = ((BOOL (*)(Class, SEL, id))objc_msgSend)(returnCodeClass, @selector(isSuccess:), returnCode);

        NSError *error = success ? nil : YouModFFmpegErrorFromSession(session);
        dispatch_async(dispatch_get_main_queue(), ^{
            if (success && [NSFileManager.defaultManager fileExistsAtPath:outputURL.path]) {
                completion(YES, nil);
            } else {
                completion(NO, error ?: [NSError errorWithDomain:@"YouMod" code:13 userInfo:@{NSLocalizedDescriptionKey: @"Conversion failed"}]);
            }
        });
    } copy];

    id statisticsBlock = durationMs ? [^(id statistics) {
        if (!progress || ![statistics respondsToSelector:@selector(getTime)]) return;
        double timeMs = ((double (*)(id, SEL))objc_msgSend)(statistics, @selector(getTime));
        if (!isfinite(timeMs) || timeMs <= 0.0) return;
        float convertProgress = 0.985f + (0.01f * fminf((float)(timeMs / (double)durationMs), 1.0f));
        dispatch_async(dispatch_get_main_queue(), ^{
            progress(convertProgress);
        });
    } copy] : nil;

    ((id (*)(Class, SEL, NSArray *, id, id, id))objc_msgSend)(ffmpegKitClass, executeSelector, arguments, completeBlock, nil, statisticsBlock);
    return YES;
}

static NSString *YouModMimeDetail(NSString *mimeType) {
    NSString *lower = mimeType.lowercaseString ?: @"";
    if ([lower containsString:@"mp4"]) return @"MP4";
    if ([lower containsString:@"webm"]) return @"WebM";
    if ([lower containsString:@"mp3"]) return @"MP3";
    if ([lower containsString:@"aac"]) return @"AAC";
    return mimeType.length ? mimeType : @"Stream";
}

static NSString *YouModFileExtensionForFormat(YouModMediaFormat *format, NSString *fallbackExtension) {
    NSString *lower = format.mimeType.lowercaseString ?: @"";
    if ([lower containsString:@"webm"]) return @"webm";
    if ([lower containsString:@"matroska"]) return @"mkv";
    if ([lower containsString:@"quicktime"]) return @"mov";
    if ([lower containsString:@"m4a"]) return @"m4a";
    if ([lower containsString:@"mp4"]) return @"mp4";
    return fallbackExtension ?: @"mp4";
}

static BOOL YouModFormatLooksMP4Family(YouModMediaFormat *format) {
    NSString *mime = format.mimeType.lowercaseString ?: @"";
    NSString *extension = YouModFileExtensionForFormat(format, @"").lowercaseString ?: @"";
    return [mime containsString:@"mp4"] || [mime containsString:@"m4a"] || [mime containsString:@"quicktime"] || [@[@"mp4", @"m4a", @"m4v", @"mov"] containsObject:extension];
}

static BOOL YouModFormatLooksWebM(YouModMediaFormat *format) {
    NSString *mime = format.mimeType.lowercaseString ?: @"";
    NSString *extension = YouModFileExtensionForFormat(format, @"").lowercaseString ?: @"";
    return [mime containsString:@"webm"] || [extension isEqualToString:@"webm"];
}

static NSString *YouModMergedVideoOutputExtension(YouModMediaFormat *videoFormat, YouModMediaFormat *audioFormat) {
    if (YouModFormatLooksMP4Family(videoFormat) && YouModFormatLooksMP4Family(audioFormat)) return @"mp4";
    if (YouModFormatLooksWebM(videoFormat) && YouModFormatLooksWebM(audioFormat)) return @"webm";
    return @"mkv";
}

static BOOL YouModVideoFileCanUseAVFoundation(NSURL *fileURL) {
    return YouModPathExtensionIsPhotosVideo(fileURL.pathExtension);
}

static BOOL YouModVideoFileCanSaveToPhotos(NSURL *fileURL) {
    return YouModPathExtensionIsPhotosVideo(fileURL.pathExtension);
}

static YouModAudioOutputFormat *YouModAudioOutputFormatMake(NSString *identifier, NSString *title, NSString *subtitle, NSString *fileExtension, NSArray <NSString *> *ffmpegArguments, BOOL passthroughWhenCompatible, BOOL supported) {
    YouModAudioOutputFormat *format = [YouModAudioOutputFormat new];
    format.identifier = identifier;
    format.title = title;
    format.subtitle = subtitle;
    format.fileExtension = fileExtension;
    format.ffmpegArguments = ffmpegArguments;
    format.passthroughWhenCompatible = passthroughWhenCompatible;
    format.supported = supported;
    return format;
}

static NSArray <YouModAudioOutputFormat *> *YouModAudioOutputFormats(void) {
    static NSArray <YouModAudioOutputFormat *> *formats = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        formats = @[
            YouModAudioOutputFormatMake(@"m4a", @"M4A", @"AAC container, passthrough when possible", @"m4a", @[@"-map", @"0:a:0", @"-vn", @"-c:a", @"aac", @"-b:a", @"192k", @"-movflags", @"+faststart"], YES, YES),
            YouModAudioOutputFormatMake(@"aac", @"AAC", @"Lossy (192k)", @"aac", @[@"-map", @"0:a:0", @"-vn", @"-c:a", @"aac", @"-b:a", @"192k", @"-f", @"adts"], YES, YES),
            YouModAudioOutputFormatMake(@"mp3", @"MP3", @"Lossy, widely compatible", @"mp3", @[@"-map", @"0:a:0", @"-vn", @"-c:a", @"libmp3lame", @"-q:a", @"2"], NO, YES),
            YouModAudioOutputFormatMake(@"opus", @"Opus", @"Lossy, small file size", @"opus", @[@"-map", @"0:a:0", @"-vn", @"-c:a", @"libopus", @"-b:a", @"160k", @"-vbr", @"on"], NO, YES),
            YouModAudioOutputFormatMake(@"ogg", @"OGG", @"Vorbis lossy", @"ogg", @[@"-map", @"0:a:0", @"-vn", @"-c:a", @"libvorbis", @"-q:a", @"6"], NO, YES),
            YouModAudioOutputFormatMake(@"flac", @"FLAC", @"Lossless compressed", @"flac", @[@"-map", @"0:a:0", @"-vn", @"-c:a", @"flac", @"-compression_level", @"8"], NO, YES),
            YouModAudioOutputFormatMake(@"alac", @"ALAC", @"Apple lossless (M4A)", @"m4a", @[@"-map", @"0:a:0", @"-vn", @"-c:a", @"alac", @"-movflags", @"+faststart"], NO, YES),
            YouModAudioOutputFormatMake(@"wav", @"WAV", @"Uncompressed PCM", @"wav", @[@"-map", @"0:a:0", @"-vn", @"-c:a", @"pcm_s24le"], NO, YES),
            YouModAudioOutputFormatMake(@"aiff", @"AIFF", @"Apple PCM", @"aiff", @[@"-map", @"0:a:0", @"-vn", @"-c:a", @"pcm_s24be"], NO, YES),
        ];
    });
    return formats;
}

static YouModAudioOutputFormat *YouModDefaultAudioOutputFormat(void) {
    return [YouModAudioOutputFormats() firstObject];
}

static BOOL YouModAudioOutputFormatCanPassthrough(YouModAudioOutputFormat *outputFormat, YouModMediaFormat *sourceFormat) {
    if (!outputFormat.passthroughWhenCompatible) return NO;
    NSString *identifier = outputFormat.identifier.lowercaseString ?: @"";
    NSString *mime = sourceFormat.mimeType.lowercaseString ?: @"";
    NSString *extension = YouModFileExtensionForFormat(sourceFormat, @"").lowercaseString ?: @"";
    if ([identifier isEqualToString:@"m4a"] || [identifier isEqualToString:@"aac"])
        return [extension isEqualToString:@"m4a"] || [mime containsString:@"mp4"] || [mime containsString:@"m4a"];
    return NO;
}

static NSString *YouModAudioOutputFileExtension(YouModAudioOutputFormat *outputFormat, YouModMediaFormat *sourceFormat, BOOL passthrough) {
    NSString *identifier = outputFormat.identifier.lowercaseString ?: @"";
    NSString *mime = sourceFormat.mimeType.lowercaseString ?: @"";
    if (passthrough && ([identifier isEqualToString:@"m4a"] || [identifier isEqualToString:@"aac"]) && ([mime containsString:@"mp4"] || [mime containsString:@"m4a"]))
        return @"m4a";
    return outputFormat.fileExtension ?: YouModFileExtensionForFormat(sourceFormat, @"m4a");
}

static NSString *YouModAudioOutputSubtitle(YouModAudioOutputFormat *outputFormat) {
    return [NSString stringWithFormat:@"%@", outputFormat.subtitle];
}

static NSString *YouModFormatSubtitle(YouModMediaFormat *format) {
    NSMutableArray *parts = [NSMutableArray array];
    NSString *language = format.languageName.length ? format.languageName : format.languageCode;
    if (language.length) [parts addObject:language];
    if (format.drcAudio) [parts addObject:@"DRC"];
    NSString *detail = YouModMimeDetail(format.mimeType);
    if (detail.length) [parts addObject:detail];
    NSString *size = YouModByteCount(format.contentLength);
    if (size.length) [parts addObject:size];
    return [parts componentsJoinedByString:@" - "];
}

static NSString *YouModVideoIDForPlayer(YTPlayerViewController *player) {
    NSString *videoID = [player contentVideoID];
    if (videoID.length == 0)
        videoID = [player currentVideoID];
    return videoID;
}

static NSArray *YouModPlayerResponsesForPlayer(YTPlayerViewController *player) {
    NSMutableArray *responses = [NSMutableArray array];
    id response = YouModObjectFromSelector(player, @selector(contentPlayerResponse));
    if (response) [responses addObject:response];

    id activeVideo = YouModObjectFromSelector(player, @selector(activeVideo));
    response = YouModObjectFromSelector(activeVideo, @selector(contentPlayerResponse));
    if (response && ![responses containsObject:response]) [responses addObject:response];
    return responses.copy;
}

// Where is this going to?
static NSArray *YouModCaptionTracksForPlayer(YTPlayerViewController *player) {
    for (id response in YouModPlayerResponsesForPlayer(player)) {
        id playerData = YouModObjectFromSelector(response, @selector(playerData)) ?: response;
        id captions = YouModObjectFromSelector(playerData, @selector(captions));
        id tracklistRenderer = YouModObjectFromSelector(captions, @selector(playerCaptionsTracklistRenderer));
        NSArray *tracks = YouModObjectFromSelector(tracklistRenderer, @selector(captionTracksArray));
        if (tracks.count > 0) return tracks;
    }
    return nil;
}

static id YouModPlayerDataForPlayer(YTPlayerViewController *player) {
    id response = YouModPlayerResponsesForPlayer(player).firstObject;
    id playerData = YouModObjectFromSelector(response, @selector(playerData));
    return playerData ?: response;
}

static NSString *YouModTitleForPlayer(YTPlayerViewController *player) {
    id playerData = YouModPlayerDataForPlayer(player);
    id details = YouModObjectFromSelector(playerData, @selector(videoDetails));
    NSString *title = YouModStringFromSelector(details, @selector(title));
    NSString *author = YouModStringFromSelector(details, @selector(author));
    if (author.length && title.length) {
        return [NSString stringWithFormat:@"%@ - %@", author, title];
    } else if (title.length) {
        return title;
    }
    NSString *videoID = YouModVideoIDForPlayer(player);
    return videoID.length ? [NSString stringWithFormat:@"YouTube %@", videoID] : @"YouTube Video";
}

static NSArray *YouModAdaptiveFormatObjectsForPlayer(YTPlayerViewController *player) {
    NSMutableArray *formats = [NSMutableArray array];
    NSMutableSet *seenPointers = [NSMutableSet set];

    void (^appendFormats)(NSArray *) = ^(NSArray *candidateFormats) {
        if (![candidateFormats isKindOfClass:NSArray.class]) return;
        for (id format in candidateFormats) {
            NSString *key = [NSString stringWithFormat:@"%p", format];
            if ([seenPointers containsObject:key]) continue;
            [seenPointers addObject:key];
            [formats addObject:format];
        }
    };

    id activeVideo = YouModObjectFromSelector(player, @selector(activeVideo));
    id streamingData = YouModObjectFromSelector(activeVideo, @selector(streamingData));
    appendFormats(YouModObjectFromSelector(streamingData, @selector(adaptiveStreams)));
    appendFormats(YouModObjectFromSelector(activeVideo, @selector(selectableVideoFormats)));

    for (id response in YouModPlayerResponsesForPlayer(player)) {
        id playerData = YouModObjectFromSelector(response, @selector(playerData)) ?: response;
        id responseStreamingData = YouModObjectFromSelector(playerData, @selector(streamingData));
        appendFormats(YouModObjectFromSelector(responseStreamingData, @selector(adaptiveFormatsArray)));
    }

    return formats.copy;
}

static YouModMediaFormat *YouModMediaFormatFromStream(id stream, BOOL video) {
    id formatStream = YouModObjectFromSelector(stream, @selector(formatStream));
    NSString *url = YouModStringFromSelector(stream, @selector(URL));
    if (url.length == 0) url = YouModStringFromSelector(formatStream, @selector(URL));
    if (url.length == 0) url = YouModStringFromSelector(stream, @selector(url));
    if (url.length == 0) url = YouModStringFromSelector(formatStream, @selector(url));
    if (url.length == 0) return nil;

    NSString *mimeType = YouModStringFromSelector(stream, @selector(mimeType));
    if (mimeType.length == 0) mimeType = YouModStringFromSelector(formatStream, @selector(mimeType));
    NSString *lowerMime = mimeType.lowercaseString ?: @"";
    BOOL streamSaysVideo = YouModBoolFromSelector(stream, @selector(isVideo)) || YouModBoolFromSelector(formatStream, @selector(isVideo));
    BOOL streamSaysAudio = YouModBoolFromSelector(stream, @selector(isAudio)) || YouModBoolFromSelector(formatStream, @selector(isAudio));
    NSInteger itag = YouModIntegerFromSelector(stream, @selector(itag));
    if (itag == 0) itag = YouModIntegerFromSelector(formatStream, @selector(itag));

    NSSet *mp4VideoItags = [NSSet setWithObjects:@18, @22, @37, @38, @59, @78, @133, @134, @135, @136, @137, @160, @212, @264, @266, @298, @299, nil];
    NSSet *m4aAudioItags = [NSSet setWithObjects:@139, @140, @141, @256, @258, @325, @328, nil];
    BOOL itagMatches = video ? [mp4VideoItags containsObject:@(itag)] : [m4aAudioItags containsObject:@(itag)];
    BOOL typeMatches = video ? ([lowerMime containsString:@"video/"] || streamSaysVideo || itagMatches) : ([lowerMime containsString:@"audio/"] || streamSaysAudio || itagMatches);
    if (!typeMatches) return nil;

    BOOL mimeLooksMP4 = [lowerMime containsString:@"mp4"] || [lowerMime containsString:@"m4a"];
    BOOL canRemuxWithFFmpeg = YouModFFmpegKitAvailable();
    if (mimeType.length && !mimeLooksMP4 && !itagMatches && !canRemuxWithFFmpeg) return nil;

    YouModMediaFormat *format = [YouModMediaFormat new];
    format.source = stream;
    format.video = video;
    format.urlString = YouModURLStringWithCPN(url);
    format.mimeType = mimeType.length ? mimeType : (video ? @"video/mp4" : @"audio/mp4");
    NSInteger height = YouModIntegerFromSelector(stream, @selector(height));
    if (height == 0) height = YouModIntegerFromSelector(formatStream, @selector(height));
    NSInteger fps = YouModIntegerFromSelector(stream, @selector(fps));
    if (fps == 0) fps = YouModIntegerFromSelector(formatStream, @selector(fps));
    if (fps == 0) fps = YouModIntegerFromSelector(stream, @selector(framesPerSecond));
    if (fps == 0) fps = YouModIntegerFromSelector(formatStream, @selector(framesPerSecond));
    if (fps == 0) fps = YouModIntegerFromSelector(stream, @selector(frameRate));
    if (fps == 0) fps = YouModIntegerFromSelector(formatStream, @selector(frameRate));
    fps = YouModNormalizedFPS(fps);
    format.fps = fps;
    format.qualityLabel = YouModStringFromSelector(stream, @selector(qualityLabel));
    if (format.qualityLabel.length == 0) format.qualityLabel = YouModStringFromSelector(formatStream, @selector(qualityLabel));
    if (video) {
        NSInteger labelHeight = YouModResolutionFromQuality(format.qualityLabel);
        NSInteger labelFPS = YouModFPSFromQuality(format.qualityLabel);
        if (labelHeight == 960) format.qualityLabel = YouModQualityLabel(labelHeight, fps ?: labelFPS, nil);
        else if (labelFPS == 0 && fps > 0) format.qualityLabel = YouModQualityLabel(height, fps, format.qualityLabel);
        if (format.qualityLabel.length == 0) format.qualityLabel = YouModQualityLabel(height, fps, nil);
    }
    if (format.qualityLabel.length == 0 && !video) format.qualityLabel = @"Audio";
    if (!video) {
        NSString *languageCode = YouModStringFromSelector(stream, @selector(languageCode));
        if (languageCode.length == 0) languageCode = YouModStringFromSelector(formatStream, @selector(languageCode));
        if (languageCode.length == 0) languageCode = YouModStringFromSelector(stream, @selector(language));
        if (languageCode.length == 0) languageCode = YouModStringFromSelector(formatStream, @selector(language));
        format.languageCode = languageCode;

        NSString *languageName = YouModStringFromSelector(stream, @selector(languageName));
        if (languageName.length == 0) languageName = YouModStringFromSelector(formatStream, @selector(languageName));
        if (languageName.length == 0) languageName = YouModStringFromSelector(stream, @selector(displayName));
        if (languageName.length == 0) languageName = YouModStringFromSelector(formatStream, @selector(displayName));
        format.languageName = languageName.length ? languageName : languageCode;

        NSMutableArray *audioTraits = [NSMutableArray array];
        for (NSString *value in @[
            mimeType ?: @"",
            format.qualityLabel ?: @"",
            YouModStringFromSelector(stream, @selector(audioTrack)) ?: @"",
            YouModStringFromSelector(formatStream, @selector(audioTrack)) ?: @"",
            YouModStringFromSelector(stream, @selector(audioTrackType)) ?: @"",
            YouModStringFromSelector(formatStream, @selector(audioTrackType)) ?: @"",
            YouModStringFromSelector(stream, @selector(audioTrackDisplayName)) ?: @"",
            YouModStringFromSelector(formatStream, @selector(audioTrackDisplayName)) ?: @"",
        ]) {
            if (value.length) [audioTraits addObject:value];
        }
        format.drcAudio = [[audioTraits componentsJoinedByString:@" "] localizedCaseInsensitiveContainsString:@"drc"];
    }
    if (YouModBoolFromSelector(stream, @selector(hasContentLength)) || [stream respondsToSelector:@selector(contentLength)])
        format.contentLength = YouModUnsignedLongLongFromSelector(stream, @selector(contentLength));
    if (format.contentLength == 0 && (YouModBoolFromSelector(formatStream, @selector(hasContentLength)) || [formatStream respondsToSelector:@selector(contentLength)]))
        format.contentLength = YouModUnsignedLongLongFromSelector(formatStream, @selector(contentLength));
    format.durationMs = YouModUnsignedLongLongFromSelector(stream, @selector(approxDurationMs));
    if (format.durationMs == 0) format.durationMs = YouModUnsignedLongLongFromSelector(formatStream, @selector(approxDurationMs));

    NSMutableDictionary *headers = [NSMutableDictionary dictionary];
    NSDictionary *streamHeaders = YouModObjectFromSelector(stream, @selector(httpHeaders));
    if (![streamHeaders isKindOfClass:NSDictionary.class]) streamHeaders = YouModObjectFromSelector(formatStream, @selector(httpHeaders));
    if (![streamHeaders isKindOfClass:NSDictionary.class]) streamHeaders = YouModObjectFromSelector(stream, @selector(headers));
    if (![streamHeaders isKindOfClass:NSDictionary.class]) streamHeaders = YouModObjectFromSelector(formatStream, @selector(headers));
    if ([streamHeaders isKindOfClass:NSDictionary.class]) {
        for (id key in streamHeaders) {
            id value = streamHeaders[key];
            if ([key isKindOfClass:NSString.class] && [value isKindOfClass:NSString.class])
                headers[key] = value;
        }
    }
    if (!YouModHTTPHeadersContainField(headers, @"Origin"))
        headers[@"Origin"] = @"https://www.youtube.com";
    if (!YouModHTTPHeadersContainField(headers, @"Referer"))
        headers[@"Referer"] = @"https://www.youtube.com/";
    format.httpHeaders = headers;
    return format;
}

static NSInteger YouModResolutionFromQuality(NSString *quality) {
    NSScanner *scanner = [NSScanner scannerWithString:quality ?: @""];
    NSInteger value = 0;
    [scanner scanInteger:&value];
    return value;
}

static NSInteger YouModFPSFromQuality(NSString *quality) {
    NSString *lower = quality.lowercaseString ?: @"";
    NSRange pRange = [lower rangeOfString:@"p"];
    if (pRange.location != NSNotFound && pRange.location + 1 < lower.length) {
        NSString *afterP = [lower substringFromIndex:pRange.location + 1];
        NSScanner *scanner = [NSScanner scannerWithString:afterP];
        NSInteger fps = 0;
        if ([scanner scanInteger:&fps] && fps > 0) return fps;
    }
    if ([lower containsString:@"60fps"] || [lower containsString:@"60 fps"]) return 60;
    if ([lower containsString:@"30fps"] || [lower containsString:@"30 fps"]) return 30;
    return 0;
}

static NSInteger YouModNormalizedFPS(NSInteger fps) {
    if (fps >= 50 && fps <= 61) return 60;
    if (fps >= 24 && fps <= 31) return 30;
    return fps;
}

static NSInteger YouModDisplayHeightForVideoHeight(NSInteger height) {
    if (height >= 900 && height < 1080) return 1080;
    return height;
}

static NSString *YouModQualityLabel(NSInteger height, NSInteger fps, NSString *fallback) {
    height = YouModDisplayHeightForVideoHeight(height);
    fps = YouModNormalizedFPS(fps);
    if (height > 0 && fps > 0) return [NSString stringWithFormat:@"%ldp%ld", (long)height, (long)fps];
    if (height > 0) return [NSString stringWithFormat:@"%ldp", (long)height];
    if (fallback.length && fps > 0 && ![fallback.lowercaseString containsString:@"fps"])
        return [NSString stringWithFormat:@"%@ %ldfps", fallback, (long)fps];
    return fallback;
}

static NSArray <YouModMediaFormat *> *YouModFormatsForPlayer(YTPlayerViewController *player, BOOL video) {
    NSMutableArray *formats = [NSMutableArray array];
    for (id stream in YouModAdaptiveFormatObjectsForPlayer(player)) {
        YouModMediaFormat *format = YouModMediaFormatFromStream(stream, video);
        if (format) [formats addObject:format];
    }

    [formats sortUsingComparator:^NSComparisonResult(YouModMediaFormat *left, YouModMediaFormat *right) {
        if (video) {
            NSInteger leftRes = YouModResolutionFromQuality(left.qualityLabel);
            NSInteger rightRes = YouModResolutionFromQuality(right.qualityLabel);
            if (leftRes != rightRes) return leftRes > rightRes ? NSOrderedAscending : NSOrderedDescending;
            NSInteger leftFPS = left.fps ?: YouModFPSFromQuality(left.qualityLabel);
            NSInteger rightFPS = right.fps ?: YouModFPSFromQuality(right.qualityLabel);
            if (leftFPS != rightFPS) return leftFPS > rightFPS ? NSOrderedAscending : NSOrderedDescending;
        }
        
        BOOL leftMP4 = YouModFormatLooksMP4Family(left);
        BOOL rightMP4 = YouModFormatLooksMP4Family(right);
        if (leftMP4 != rightMP4) return leftMP4 ? NSOrderedAscending : NSOrderedDescending;
        
        if (!video && IS_ENABLED(DownloadPreferDRCAudio) && left.drcAudio != right.drcAudio)
            return left.drcAudio ? NSOrderedAscending : NSOrderedDescending;
        if (left.contentLength != right.contentLength)
            return left.contentLength > right.contentLength ? NSOrderedAscending : NSOrderedDescending;
        return NSOrderedSame;
    }];

    NSMutableArray *unique = [NSMutableArray array];
    NSMutableSet *seen = [NSMutableSet set];
    for (YouModMediaFormat *format in formats) {
        NSInteger fps = format.fps ?: YouModFPSFromQuality(format.qualityLabel);
        NSString *key = video
            ? [NSString stringWithFormat:@"%@-%ld-%@", format.qualityLabel ?: @"", (long)fps, YouModMimeDetail(format.mimeType)]
            : [NSString stringWithFormat:@"%@-%@-%@-%@", format.qualityLabel ?: @"", format.languageCode ?: @"", format.drcAudio ? @"drc" : @"std", YouModMimeDetail(format.mimeType)];
        if ([seen containsObject:key]) continue;
        [seen addObject:key];
        [unique addObject:format];
    }
    return unique.copy;
}

static YouModMediaFormat *YouModBestAudioFormatForPlayer(YTPlayerViewController *player) {
    NSArray <YouModMediaFormat *> *audioFormats = YouModFormatsForPlayer(player, NO);
    return audioFormats.firstObject;
}

static UIViewController *YouModPresenterForSender(UIView *sender, YTPlayerViewController *player) {
    UIViewController *presenter = nil;
    if ([sender respondsToSelector:@selector(_viewControllerForAncestor)])
        presenter = [sender _viewControllerForAncestor];
    if (!presenter) presenter = player;
    return YouModTopViewController(presenter);
}

static YTPlayerViewController *YouModPlayerFromViewController(UIViewController *vc) {
    Class playerClass = NSClassFromString(@"YTPlayerViewController");
    UIViewController *cursor = vc;
    while (cursor) {
        if (playerClass && [cursor isKindOfClass:playerClass]) return (YTPlayerViewController *)cursor;
        id player = YouModObjectFromSelector(cursor, @selector(playerViewController));
        if (playerClass && [player isKindOfClass:playerClass]) return (YTPlayerViewController *)player;
        cursor = cursor.parentViewController;
    }
    return YouModCurrentPlayerViewController;
}

static NSURL *YouModThumbnailURLForVideoID(NSString *videoID) {
    if (videoID.length == 0) return nil;
    NSString *urlString = [NSString stringWithFormat:@"https://i.ytimg.com/vi/%@/maxresdefault.jpg", videoID];
    return [NSURL URLWithString:urlString];
}

static void YouModRequestPhotoAccess(void (^completion)(BOOL granted)) {
    if (@available(iOS 14.0, *)) {
        [PHPhotoLibrary requestAuthorizationForAccessLevel:PHAccessLevelAddOnly handler:^(PHAuthorizationStatus status) {
            completion(status == PHAuthorizationStatusAuthorized || status == PHAuthorizationStatusLimited);
        }];
    } else {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            completion(status == PHAuthorizationStatusAuthorized);
        }];
    }
}

static void YouModSaveVideoToPhotos(NSURL *fileURL, UIViewController *presenter, void (^completion)(BOOL success, NSError *error)) {
    YouModRequestPhotoAccess(^(BOOL granted) {
        if (!granted) {
            NSError *error = [NSError errorWithDomain:@"YouMod" code:1 userInfo:@{NSLocalizedDescriptionKey: @"Photos access denied"}];
            completion(NO, error);
            return;
        }
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            [PHAssetCreationRequest creationRequestForAssetFromVideoAtFileURL:fileURL];
        } completionHandler:^(BOOL success, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(success, error);
            });
        }];
    });
}

static void YouModShareFile(NSURL *fileURL, UIViewController *presenter) {
    if (!fileURL || !presenter) return;
    UIActivityViewController *activity = [[UIActivityViewController alloc] initWithActivityItems:@[fileURL] applicationActivities:nil];
    // Fix for iPad and specific presentation alignment
    if (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad) {
        activity.popoverPresentationController.sourceView = presenter.view;
        // Position at the bottom center of the screen
        activity.popoverPresentationController.sourceRect = CGRectMake(presenter.view.bounds.size.width / 2, presenter.view.bounds.size.height, 0, 0);
        activity.popoverPresentationController.permittedArrowDirections = 0; // No arrow pointing to a button
    } else {
        // On iPhone, UIActivityViewController naturally comes from the bottom center
        activity.popoverPresentationController.sourceView = presenter.view;
    }
    [presenter presentViewController:activity animated:YES completion:nil];
}

static void YouModPresentMenu(NSString *title, NSArray <YouModMenuItem *> *items, UIViewController *presenter, UIView *sender) {
    presenter = YouModTopViewController(presenter);
    Class sheetClass = NSClassFromString(@"YTDefaultSheetController");
    if (sheetClass && [sheetClass respondsToSelector:@selector(sheetControllerWithParentResponder:)]) {
        YTDefaultSheetController *sheet = [sheetClass sheetControllerWithParentResponder:presenter];
        Class actionClass = NSClassFromString(@"YTActionSheetAction");
        for (YouModMenuItem *item in items) {
            id action = nil;
            if ([actionClass respondsToSelector:@selector(actionWithTitle:subtitle:iconImage:handler:)]) {
                action = ((id (*)(Class, SEL, NSString *, NSString *, UIImage *, id))objc_msgSend)(actionClass, @selector(actionWithTitle:subtitle:iconImage:handler:), item.title, item.subtitle, item.iconImage, ^(__unused id action) {
                    if (item.handler) item.handler();
                });
            } else {
                action = ((id (*)(Class, SEL, NSString *, NSInteger, id))objc_msgSend)(actionClass, @selector(actionWithTitle:style:handler:), item.title, 0, ^(__unused id action) {
                    if (item.handler) item.handler();
                });
            }
            if (action) [sheet addAction:action];
        }
        if (sender && [sheet respondsToSelector:@selector(presentFromView:animated:completion:)])
            [sheet presentFromView:sender animated:YES completion:nil];
        else
            [sheet presentFromViewController:presenter animated:YES completion:nil];
        return;
    }

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    for (YouModMenuItem *item in items) {
        NSString *rowTitle = item.subtitle.length ? [NSString stringWithFormat:@"%@\n%@", item.title, item.subtitle] : item.title;
        [alert addAction:[UIAlertAction actionWithTitle:rowTitle style:UIAlertActionStyleDefault handler:^(__unused UIAlertAction *action) {
            if (item.handler) item.handler();
        }]];
    }
    [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];
    alert.popoverPresentationController.sourceView = sender ?: presenter.view;
    [presenter presentViewController:alert animated:YES completion:nil];
}

@implementation YouModDownloadCoordinator

+ (instancetype)sharedCoordinator {
    static YouModDownloadCoordinator *coordinator;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        coordinator = [YouModDownloadCoordinator new];
    });
    return coordinator;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        configuration.HTTPAdditionalHeaders = @{
            @"User-Agent": @"Mozilla/5.0",
            @"Origin": @"https://www.youtube.com",
            @"Referer": @"https://www.youtube.com/",
        };
        configuration.HTTPMaximumConnectionsPerHost = YouModFastDownloadConcurrency;
        configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
        configuration.timeoutIntervalForResource = 300;
        _session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return self;
}

- (void)showProgressWithTitle:(NSString *)title presenter:(UIViewController *)presenter {
    self.presenter = presenter;
    self.baseProgressTitle = title;
    self.downloadStartTime = [NSDate timeIntervalSinceReferenceDate];
    self.progressAlert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"%@ - 0%%", title] message:@"\n" preferredStyle:UIAlertControllerStyleAlert];
    self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    self.progressView.progress = 0.0;
    self.progressView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.progressAlert.view addSubview:self.progressView];
    [NSLayoutConstraint activateConstraints:@[
        [self.progressView.leadingAnchor constraintEqualToAnchor:self.progressAlert.view.leadingAnchor constant:24.0],
        [self.progressView.trailingAnchor constraintEqualToAnchor:self.progressAlert.view.trailingAnchor constant:-24.0],
        [self.progressView.bottomAnchor constraintEqualToAnchor:self.progressAlert.view.bottomAnchor constant:-56.0],
    ]];
    __weak typeof(self) weakSelf = self;
    [self.progressAlert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(__unused UIAlertAction *action) {
        [weakSelf cancelWithMessage:@"Download cancelled"];
    }]];
    [presenter presentViewController:self.progressAlert animated:YES completion:nil];
}

- (void)updateProgressTitle:(NSString *)title progress:(float)progress {
    self.progressAlert.title = [NSString stringWithFormat:@"%@ - %ld%%", title, (long)lrintf(progress * 100.0f)];
    self.progressAlert.message = @"\n";
    [self.progressView setProgress:progress animated:YES];
}

- (void)cancelWithMessage:(NSString *)message {
    [self.task cancel];
    [self.metadataTask cancel];
    [self.rangeDownloader cancel];
    YouModCancelFFmpegKit();
    self.task = nil;
    self.metadataTask = nil;
    self.rangeDownloader = nil;
    self.fileCompletion = nil;
    self.active = NO;
    self.cancelled = YES;
    [self cleanupTemporaryFiles];
    if (message.length) YouModSendToast(message, self.presenter);
}

- (void)cleanupTemporaryFiles {
    if (self.videoTempURL) [NSFileManager.defaultManager removeItemAtURL:self.videoTempURL error:nil];
    if (self.audioTempURL) [NSFileManager.defaultManager removeItemAtURL:self.audioTempURL error:nil];
    self.videoTempURL = nil;
    self.audioTempURL = nil;
}

- (void)downloadURL:(NSURL *)url toURL:(NSURL *)destinationURL expectedBytes:(unsigned long long)expectedBytes headers:(NSDictionary *)headers completion:(YouModFileDownloadCompletion)completion {
    self.currentResolvedSizeAddedToTotal = NO;
    self.currentExpectedBytes = expectedBytes;
    self.currentBytes = 0;
    if (expectedBytes == 0) {
        __weak typeof(self) weakSelf = self;
        [self resolveExpectedBytesForURL:url headers:headers completion:^(unsigned long long bytes) {
            __strong typeof(weakSelf) self = weakSelf;
            if (!self || self.cancelled) return;
            if (bytes > 0) [self adjustCurrentExpectedBytesIfNeeded:bytes];
            [self beginDownloadURL:url toURL:destinationURL expectedBytes:bytes headers:headers allowFast:YES completion:completion];
        }];
        return;
    }
    [self beginDownloadURL:url toURL:destinationURL expectedBytes:expectedBytes headers:headers allowFast:YES completion:completion];
}

- (void)beginDownloadURL:(NSURL *)url toURL:(NSURL *)destinationURL expectedBytes:(unsigned long long)expectedBytes headers:(NSDictionary *)headers allowFast:(BOOL)allowFast completion:(YouModFileDownloadCompletion)completion {
    self.destinationURL = destinationURL;
    self.currentExpectedBytes = expectedBytes;
    self.currentBytes = 0;
    self.finishedCurrentFile = NO;
    self.fileCompletion = completion;
    [NSFileManager.defaultManager removeItemAtURL:destinationURL error:nil];

    if (allowFast && expectedBytes == 0) allowFast = NO;

    if (allowFast && expectedBytes >= YouModFastDownloadMinimumBytes) {
        __weak typeof(self) weakSelf = self;
        self.rangeDownloader = [[YouModRangeDownloader alloc] initWithURL:url destinationURL:destinationURL expectedBytes:expectedBytes headers:headers progress:^(unsigned long long completedBytes) {
            __strong typeof(weakSelf) self = weakSelf;
            if (!self || self.cancelled) return;
            self.currentBytes = completedBytes;
            [self updateDownloadProgressWithCurrentBytes:completedBytes expectedBytes:expectedBytes];
        } completion:^(NSURL *fileURL, NSError *error) {
            __strong typeof(weakSelf) self = weakSelf;
            if (!self || self.cancelled) return;
            self.rangeDownloader = nil;
            if (error) {
                [self beginDownloadURL:url toURL:destinationURL expectedBytes:expectedBytes headers:headers allowFast:NO completion:completion];
                return;
            }
            if (completion) completion(fileURL, nil);
        }];
        [self.rangeDownloader start];
        return;
    }

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
    YouModApplyDownloadHeaders(request, headers);
    self.task = [self.session downloadTaskWithRequest:request];
    [self.task resume];
}

- (void)resolveExpectedBytesForURL:(NSURL *)url headers:(NSDictionary *)headers completion:(void (^)(unsigned long long bytes))completion {
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15.0];
    request.HTTPMethod = @"HEAD";
    YouModApplyDownloadHeaders(request, headers);

    __weak typeof(self) weakSelf = self;
    self.metadataTask = [NSURLSession.sharedSession dataTaskWithRequest:request completionHandler:^(__unused NSData *data, NSURLResponse *response, __unused NSError *error) {
        __strong typeof(weakSelf) self = weakSelf;
        if (!self) return;

        unsigned long long bytes = 0;
        if (response.expectedContentLength > 0) {
            bytes = (unsigned long long)response.expectedContentLength;
        } else if ([response isKindOfClass:NSHTTPURLResponse.class]) {
            id header = ((NSHTTPURLResponse *)response).allHeaderFields[@"Content-Length"];
            if ([header respondsToSelector:@selector(unsignedLongLongValue)])
                bytes = [header unsignedLongLongValue];
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            self.metadataTask = nil;
            completion(bytes);
        });
    }];
    [self.metadataTask resume];
}

- (void)updateDownloadProgressWithCurrentBytes:(unsigned long long)currentBytes expectedBytes:(unsigned long long)expectedBytes {
    unsigned long long total = self.totalBytes ?: expectedBytes;
    float progress = total ? (float)(self.completedBytes + currentBytes) / (float)total : 0.0f;
    progress = fminf(fmaxf(progress, 0.0f), 0.985f);
    
    NSTimeInterval now = [NSDate timeIntervalSinceReferenceDate];
    NSTimeInterval elapsed = now - self.downloadStartTime;
    double speedMBps = 0;
    if (elapsed > 0) {
        speedMBps = ((double)(self.completedBytes + currentBytes) / 1048576.0) / elapsed;
    }
    double totalMB = (double)total / 1048576.0;
    
    self.progressAlert.title = [NSString stringWithFormat:@"%@ - %ld%%", self.baseProgressTitle ?: @"Downloading", (long)lrintf(progress * 100.0f)];
    if (total > 0) {
        self.progressAlert.message = [NSString stringWithFormat:@"%.1f MB/s - %.1f MB\n", speedMBps, totalMB];
    } else {
        self.progressAlert.message = [NSString stringWithFormat:@"%.1f MB/s\n", speedMBps];
    }
    [self.progressView setProgress:progress animated:YES];
}

- (void)adjustCurrentExpectedBytesIfNeeded:(unsigned long long)newExpectedBytes {
    unsigned long long oldExpectedBytes = self.currentExpectedBytes;
    if (newExpectedBytes <= oldExpectedBytes) return;

    self.currentExpectedBytes = newExpectedBytes;
    if (oldExpectedBytes > 0) {
        self.totalBytes += newExpectedBytes - oldExpectedBytes;
    } else if (!self.currentResolvedSizeAddedToTotal) {
        self.totalBytes += newExpectedBytes;
        self.currentResolvedSizeAddedToTotal = YES;
    }
}

- (void)startVideoDownloadWithVideoFormat:(YouModMediaFormat *)videoFormat audioFormat:(YouModMediaFormat *)audioFormat fileName:(NSString *)fileName videoID:(NSString *)videoID presenter:(UIViewController *)presenter {
    if (self.active) {
        YouModSendToast(@"Already downloading", presenter);
        return;
    }
    [self startDirectVideoDownloadWithVideoFormat:videoFormat audioFormat:audioFormat fileName:fileName videoID:videoID presenter:presenter];
}

- (void)startDirectVideoDownloadWithVideoFormat:(YouModMediaFormat *)videoFormat audioFormat:(YouModMediaFormat *)audioFormat fileName:(NSString *)fileName videoID:(NSString *)videoID presenter:(UIViewController *)presenter {
    NSURL *videoURL = [NSURL URLWithString:videoFormat.urlString];
    NSURL *audioURL = [NSURL URLWithString:audioFormat.urlString];
    if (!videoURL || !audioURL) {
        YouModSendToast(@"No stream URL found", presenter);
        return;
    }

    self.active = YES;
    self.cancelled = NO;
    self.completedBytes = 0;
    self.totalBytes = videoFormat.contentLength + audioFormat.contentLength;
    self.videoTempURL = YouModTemporaryFileURL(YouModFileExtensionForFormat(videoFormat, @"mp4"));
    self.audioTempURL = YouModTemporaryFileURL(YouModFileExtensionForFormat(audioFormat, @"m4a"));
    NSString *outputExtension = YouModMergedVideoOutputExtension(videoFormat, audioFormat);
    [self showProgressWithTitle:@"Downloading video" presenter:presenter];

    __weak typeof(self) weakSelf = self;
    [self downloadURL:videoURL toURL:self.videoTempURL expectedBytes:videoFormat.contentLength headers:videoFormat.httpHeaders completion:^(NSURL *videoFileURL, NSError *videoError) {
        __strong typeof(weakSelf) self = weakSelf;
        if (!self || videoError) {
            [self failWithError:videoError ?: [NSError errorWithDomain:@"YouMod" code:2 userInfo:@{NSLocalizedDescriptionKey: @"Video download failed"}]];
            return;
        }

        self.completedBytes += MAX(videoFormat.contentLength, self.currentBytes);
        [self updateProgressTitle:@"Downloading audio" progress:(self.totalBytes ? (float)self.completedBytes / (float)self.totalBytes : 0.5f)];
        [self downloadURL:audioURL toURL:self.audioTempURL expectedBytes:audioFormat.contentLength headers:audioFormat.httpHeaders completion:^(NSURL *audioFileURL, NSError *audioError) {
            __strong typeof(weakSelf) self = weakSelf;
            if (!self || audioError) {
                [self failWithError:audioError ?: [NSError errorWithDomain:@"YouMod" code:3 userInfo:@{NSLocalizedDescriptionKey: @"Audio download failed"}]];
                return;
            }
            unsigned long long durationMs = videoFormat.durationMs ?: audioFormat.durationMs;
            [self mergeVideoURL:videoFileURL audioURL:audioFileURL fileName:fileName outputExtension:outputExtension durationMs:durationMs presenter:presenter];
        }];
    }];
}

- (void)startDirectSingleVideoDownloadWithFormat:(YouModMediaFormat *)format fileName:(NSString *)fileName videoID:(NSString *)videoID presenter:(UIViewController *)presenter {
    NSURL *videoURL = [NSURL URLWithString:format.urlString];
    if (!videoURL) {
        YouModSendToast(@"No stream URL found", presenter);
        return;
    }

    self.active = YES;
    self.cancelled = NO;
    self.completedBytes = 0;
    self.totalBytes = format.contentLength;
    NSString *extension = YouModFileExtensionForFormat(format, @"mp4");
    BOOL canFinalizeWithAVFoundation = format.durationMs > 0 && YouModPathExtensionIsPhotosVideo(extension);
    NSURL *finalURL = YouModUniqueFileURL(fileName, extension);
    NSURL *downloadURL = canFinalizeWithAVFoundation ? YouModTemporaryFileURL(extension) : finalURL;
    self.videoTempURL = canFinalizeWithAVFoundation ? downloadURL : nil;
    [self showProgressWithTitle:@"Downloading video" presenter:presenter];

    __weak typeof(self) weakSelf = self;
    [self downloadURL:videoURL toURL:downloadURL expectedBytes:format.contentLength headers:format.httpHeaders completion:^(NSURL *fileURL, NSError *error) {
        __strong typeof(weakSelf) self = weakSelf;
        if (!self || error) {
            [self failWithError:error ?: [NSError errorWithDomain:@"YouMod" code:8 userInfo:@{NSLocalizedDescriptionKey: @"Video download failed"}]];
            return;
        }
        if (canFinalizeWithAVFoundation) {
            [self trimSingleVideoURL:fileURL outputURL:finalURL durationMs:format.durationMs presenter:presenter];
            return;
        }
        [self completeWithFileURL:fileURL isVideo:YES presenter:presenter];
    }];
}

- (void)startAudioDownloadWithAudioFormat:(YouModMediaFormat *)audioFormat fileName:(NSString *)fileName videoID:(NSString *)videoID presenter:(UIViewController *)presenter {
    [self startAudioDownloadWithAudioFormat:audioFormat fileName:fileName videoID:videoID outputFormat:nil presenter:presenter];
}

- (void)startAudioDownloadWithAudioFormat:(YouModMediaFormat *)audioFormat fileName:(NSString *)fileName videoID:(NSString *)videoID outputFormat:(YouModAudioOutputFormat *)outputFormat presenter:(UIViewController *)presenter {
    if (self.active) {
        YouModSendToast(@"Already downloading", presenter);
        return;
    }
    [self startDirectAudioDownloadWithAudioFormat:audioFormat fileName:fileName videoID:videoID outputFormat:outputFormat presenter:presenter];
}

- (void)startDirectAudioDownloadWithAudioFormat:(YouModMediaFormat *)audioFormat fileName:(NSString *)fileName videoID:(NSString *)videoID presenter:(UIViewController *)presenter {
    [self startDirectAudioDownloadWithAudioFormat:audioFormat fileName:fileName videoID:videoID outputFormat:nil presenter:presenter];
}

- (void)startDirectAudioDownloadWithAudioFormat:(YouModMediaFormat *)audioFormat fileName:(NSString *)fileName videoID:(NSString *)videoID outputFormat:(YouModAudioOutputFormat *)outputFormat presenter:(UIViewController *)presenter {
    NSURL *audioURL = [NSURL URLWithString:audioFormat.urlString];
    if (!audioURL) {
        YouModSendToast(@"No audio URL found", presenter);
        return;
    }
    outputFormat = outputFormat ?: YouModDefaultAudioOutputFormat();
    if (!outputFormat.supported) {
        YouModSendToast([NSString stringWithFormat:@"%@ not supported", outputFormat.title ?: @"Format"], presenter);
        return;
    }

    self.active = YES;
    self.cancelled = NO;
    self.completedBytes = 0;
    self.totalBytes = audioFormat.contentLength;
    BOOL passthrough = YouModAudioOutputFormatCanPassthrough(outputFormat, audioFormat);
    if (!passthrough && !YouModFFmpegKitAvailable()) {
        self.active = NO;
        NSString *details = YouModFFmpegKitDiagnosticText(outputFormat, audioFormat, videoID);
        YouModRecordDownloadDiagnostic(@"FFmpegKit unavailable for audio conversion", details);
        NSString *diagnostic = YouModDownloadDiagnosticText();
        if (diagnostic.length) {
            UIPasteboard.generalPasteboard.string = diagnostic;
            YouModSendToast(@"FFmpegKit not loaded, diagnostics copied", presenter);
        } else {
            YouModSendToast([NSString stringWithFormat:@"FFmpegKit required for %@", outputFormat.title ?: @"this format"], presenter);
        }
        return;
    }

    NSURL *finalURL = YouModUniqueFileURL(fileName, YouModAudioOutputFileExtension(outputFormat, audioFormat, passthrough));
    NSURL *downloadURL = passthrough ? finalURL : YouModTemporaryFileURL(YouModFileExtensionForFormat(audioFormat, @"m4a"));
    self.audioTempURL = passthrough ? nil : downloadURL;
    [self showProgressWithTitle:@"Downloading audio" presenter:presenter];

    __weak typeof(self) weakSelf = self;
    [self downloadURL:audioURL toURL:downloadURL expectedBytes:audioFormat.contentLength headers:audioFormat.httpHeaders completion:^(NSURL *fileURL, NSError *error) {
        __strong typeof(weakSelf) self = weakSelf;
        if (!self || error) {
            [self failWithError:error ?: [NSError errorWithDomain:@"YouMod" code:4 userInfo:@{NSLocalizedDescriptionKey: @"Audio download failed"}]];
            return;
        }
        if (!passthrough) {
            unsigned long long durationMs = audioFormat.durationMs ?: YouModDurationMsForURL(fileURL);
            [self convertAudioURL:fileURL outputURL:finalURL outputFormat:outputFormat durationMs:durationMs presenter:presenter];
            return;
        }
        [self completeWithFileURL:fileURL isVideo:NO presenter:presenter];
    }];
}

- (void)convertAudioURL:(NSURL *)inputURL outputURL:(NSURL *)outputURL outputFormat:(YouModAudioOutputFormat *)outputFormat durationMs:(unsigned long long)durationMs presenter:(UIViewController *)presenter {
    [self updateProgressTitle:[NSString stringWithFormat:@"Converting to %@", outputFormat.title ?: @"audio"] progress:0.985f];
    [NSFileManager.defaultManager removeItemAtURL:outputURL error:nil];

    __weak typeof(self) weakSelf = self;
    BOOL started = YouModStartFFmpegKitAudioConvert(inputURL, outputURL, outputFormat, durationMs, ^(float progress) {
        __strong typeof(weakSelf) self = weakSelf;
        if (!self || self.cancelled) return;
        [self updateProgressTitle:[NSString stringWithFormat:@"Converting to %@", outputFormat.title ?: @"audio"] progress:progress];
    }, ^(BOOL success, NSError *error) {
        __strong typeof(weakSelf) self = weakSelf;
        if (!self || self.cancelled) return;
        if (success) {
            [self completeWithFileURL:outputURL isVideo:NO presenter:presenter];
            return;
        }
        [self failWithError:error ?: [NSError errorWithDomain:@"YouMod" code:14 userInfo:@{NSLocalizedDescriptionKey: @"Conversion failed"}]];
    });

    if (!started) {
        [self failWithError:[NSError errorWithDomain:@"YouMod" code:15 userInfo:@{NSLocalizedDescriptionKey: @"Format unavailable"}]];
    }
}

- (void)mergeVideoURL:(NSURL *)videoURL audioURL:(NSURL *)audioURL fileName:(NSString *)fileName outputExtension:(NSString *)outputExtension durationMs:(unsigned long long)durationMs presenter:(UIViewController *)presenter {
    [self updateProgressTitle:@"Merging video" progress:0.985f];
    NSURL *outputURL = YouModUniqueFileURL(fileName, outputExtension.length ? outputExtension : @"mp4");
    if (durationMs == 0) durationMs = YouModDurationMsForURL(videoURL);

    if (YouModFFmpegKitAvailable()) {
        __weak typeof(self) weakSelf = self;
        BOOL started = YouModStartFFmpegKitMerge(videoURL, audioURL, outputURL, durationMs, ^(float progress) {
            __strong typeof(weakSelf) self = weakSelf;
            if (!self || self.cancelled) return;
            [self updateProgressTitle:@"Merging video" progress:progress];
        }, ^(BOOL success, NSError *error) {
            __strong typeof(weakSelf) self = weakSelf;
            if (!self || self.cancelled) return;
            if (success) {
                [self completeWithFileURL:outputURL isVideo:YES presenter:presenter];
                return;
            }

            [NSFileManager.defaultManager removeItemAtURL:outputURL error:nil];
            if (YouModVideoFileCanUseAVFoundation(outputURL)) {
                [self mergeVideoWithAVFoundationVideoURL:videoURL audioURL:audioURL outputURL:outputURL durationMs:durationMs presenter:presenter fallbackError:error];
            } else {
                [self failWithError:error ?: [NSError errorWithDomain:@"YouMod" code:16 userInfo:@{NSLocalizedDescriptionKey: @"FFmpegKit required for this stream"}]];
            }
        });
        if (started) return;
    }

    if (YouModVideoFileCanUseAVFoundation(outputURL)) {
        [self mergeVideoWithAVFoundationVideoURL:videoURL audioURL:audioURL outputURL:outputURL durationMs:durationMs presenter:presenter fallbackError:nil];
    } else {
        [self failWithError:[NSError errorWithDomain:@"YouMod" code:16 userInfo:@{NSLocalizedDescriptionKey: @"FFmpegKit required for this stream"}]];
    }
}

- (void)mergeVideoWithAVFoundationVideoURL:(NSURL *)videoURL audioURL:(NSURL *)audioURL outputURL:(NSURL *)outputURL durationMs:(unsigned long long)durationMs presenter:(UIViewController *)presenter fallbackError:(NSError *)fallbackError {
    [self updateProgressTitle:fallbackError ? @"Merging video with fallback" : @"Merging video" progress:0.985f];
    AVURLAsset *videoAsset = [AVURLAsset URLAssetWithURL:videoURL options:nil];
    AVURLAsset *audioAsset = [AVURLAsset URLAssetWithURL:audioURL options:nil];
    AVMutableComposition *composition = [AVMutableComposition composition];

    AVAssetTrack *videoTrack = [[videoAsset tracksWithMediaType:AVMediaTypeVideo] firstObject];
    AVAssetTrack *audioTrack = [[audioAsset tracksWithMediaType:AVMediaTypeAudio] firstObject];
    if (!videoTrack || !audioTrack) {
        [self failWithError:fallbackError ?: [NSError errorWithDomain:@"YouMod" code:5 userInfo:@{NSLocalizedDescriptionKey: @"Merge failed"}]];
        return;
    }

    CMTime duration = YouModExportDuration(videoAsset, audioAsset, durationMs);
    if (!YouModCMTimeIsUsable(duration)) {
        [self failWithError:fallbackError ?: [NSError errorWithDomain:@"YouMod" code:9 userInfo:@{NSLocalizedDescriptionKey: @"Cannot determine duration"}]];
        return;
    }
    NSError *insertError = nil;
    AVMutableCompositionTrack *compositionVideo = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
    [compositionVideo insertTimeRange:CMTimeRangeMake(kCMTimeZero, duration) ofTrack:videoTrack atTime:kCMTimeZero error:&insertError];
    compositionVideo.preferredTransform = videoTrack.preferredTransform;
    if (insertError) {
        [self failWithError:insertError];
        return;
    }

    AVMutableCompositionTrack *compositionAudio = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
    [compositionAudio insertTimeRange:CMTimeRangeMake(kCMTimeZero, duration) ofTrack:audioTrack atTime:kCMTimeZero error:&insertError];
    if (insertError) {
        [self failWithError:insertError];
        return;
    }

    AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetPassthrough];
    exporter.outputURL = outputURL;
    exporter.outputFileType = AVFileTypeMPEG4;
    exporter.shouldOptimizeForNetworkUse = YES;

    __weak typeof(self) weakSelf = self;
    [exporter exportAsynchronouslyWithCompletionHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            __strong typeof(weakSelf) self = weakSelf;
            if (!self) return;
            if (exporter.status == AVAssetExportSessionStatusCompleted) {
                [self completeWithFileURL:outputURL isVideo:YES presenter:presenter];
            } else {
                [self failWithError:exporter.error ?: [NSError errorWithDomain:@"YouMod" code:6 userInfo:@{NSLocalizedDescriptionKey: @"Merge failed"}]];
            }
        });
    }];
}

- (void)trimSingleVideoURL:(NSURL *)inputURL outputURL:(NSURL *)outputURL durationMs:(unsigned long long)durationMs presenter:(UIViewController *)presenter {
    [self updateProgressTitle:@"Finalizing video" progress:0.99f];
    [NSFileManager.defaultManager removeItemAtURL:outputURL error:nil];

    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
    AVAssetTrack *videoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] firstObject];
    if (!videoTrack) {
        [self failWithError:[NSError errorWithDomain:@"YouMod" code:10 userInfo:@{NSLocalizedDescriptionKey: @"Cannot finalize video"}]];
        return;
    }

    CMTime duration = YouModExportDuration(asset, nil, durationMs);
    if (!YouModCMTimeIsUsable(duration)) {
        [self failWithError:[NSError errorWithDomain:@"YouMod" code:11 userInfo:@{NSLocalizedDescriptionKey: @"Cannot determine duration"}]];
        return;
    }

    AVMutableComposition *composition = [AVMutableComposition composition];
    NSError *insertError = nil;
    AVMutableCompositionTrack *compositionVideo = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
    [compositionVideo insertTimeRange:CMTimeRangeMake(kCMTimeZero, duration) ofTrack:videoTrack atTime:kCMTimeZero error:&insertError];
    compositionVideo.preferredTransform = videoTrack.preferredTransform;
    if (insertError) {
        [self failWithError:insertError];
        return;
    }

    AVAssetTrack *audioTrack = [[asset tracksWithMediaType:AVMediaTypeAudio] firstObject];
    if (audioTrack) {
        CMTime audioDuration = YouModMinUsableDuration(duration, audioTrack.timeRange.duration);
        AVMutableCompositionTrack *compositionAudio = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
        [compositionAudio insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioDuration) ofTrack:audioTrack atTime:kCMTimeZero error:&insertError];
        if (insertError) {
            [self failWithError:insertError];
            return;
        }
    }

    AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetPassthrough];
    exporter.outputURL = outputURL;
    exporter.outputFileType = AVFileTypeMPEG4;
    exporter.shouldOptimizeForNetworkUse = YES;

    __weak typeof(self) weakSelf = self;
    [exporter exportAsynchronouslyWithCompletionHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            __strong typeof(weakSelf) self = weakSelf;
            if (!self) return;
            if (exporter.status == AVAssetExportSessionStatusCompleted) {
                [self completeWithFileURL:outputURL isVideo:YES presenter:presenter];
            } else {
                [self failWithError:exporter.error ?: [NSError errorWithDomain:@"YouMod" code:12 userInfo:@{NSLocalizedDescriptionKey: @"Finalize failed"}]];
            }
        });
    }];
}

- (void)completeWithFileURL:(NSURL *)fileURL isVideo:(BOOL)isVideo presenter:(UIViewController *)presenter {
    self.active = NO;
    [self updateProgressTitle:@"Download completed" progress:1.0f];
    [self.progressAlert dismissViewControllerAnimated:YES completion:nil];
    self.progressAlert = nil;
    self.progressView = nil;

    BOOL canSaveToPhotos = isVideo && YouModVideoFileCanSaveToPhotos(fileURL);
    if (isVideo && IS_ENABLED(DownloadSaveToPhotos) && canSaveToPhotos) {
        [self cleanupTemporaryFiles];
        YouModSaveVideoToPhotos(fileURL, presenter, ^(BOOL success, NSError *error) {
            if (success) {
                YouModSendToast(@"Saved to Photos", presenter);
            } else {
                YouModSendToast(error.localizedDescription ?: @"Cannot save to Photos", presenter);
                YouModShareFile(fileURL, presenter);
            }
        });
    } else {
        [self cleanupTemporaryFiles];
        YouModSendToast(isVideo ? @"Download completed" : @"Audio saved", presenter);
        if (!isVideo || (isVideo && !canSaveToPhotos)) YouModShareFile(fileURL, presenter);
    }
}

- (void)failWithError:(NSError *)error {
    self.active = NO;
    [self.progressAlert dismissViewControllerAnimated:YES completion:nil];
    self.progressAlert = nil;
    self.progressView = nil;
    [self cleanupTemporaryFiles];
    YouModSendToast(error.localizedDescription ?: @"Download failed", self.presenter);
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    self.currentBytes = (unsigned long long)MAX(totalBytesWritten, 0);
    if (totalBytesExpectedToWrite > 0)
        [self adjustCurrentExpectedBytesIfNeeded:(unsigned long long)totalBytesExpectedToWrite];
    if (self.currentBytes > self.currentExpectedBytes)
        [self adjustCurrentExpectedBytesIfNeeded:self.currentBytes];
    [self updateDownloadProgressWithCurrentBytes:self.currentBytes expectedBytes:self.currentExpectedBytes];
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    self.finishedCurrentFile = YES;
    NSError *error = nil;
    [NSFileManager.defaultManager removeItemAtURL:self.destinationURL error:nil];
    [NSFileManager.defaultManager moveItemAtURL:location toURL:self.destinationURL error:&error];
    if (self.fileCompletion) self.fileCompletion(error ? nil : self.destinationURL, error);
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    if (error && !self.finishedCurrentFile && self.fileCompletion) {
        self.fileCompletion(nil, error);
    }
}

@end

static void YouModDownloadThumbnail(NSString *videoID, UIViewController *presenter) {
    NSURL *thumbnailURL = YouModThumbnailURLForVideoID(videoID);
    if (!thumbnailURL) {
        YouModSendToast(@"No thumbnail found", presenter);
        return;
    }

    YouModSendToast(@"Downloading thumbnail", presenter);
    [[NSURLSession.sharedSession dataTaskWithURL:thumbnailURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        UIImage *image = data ? [UIImage imageWithData:data] : nil;
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!image || error) {
                YouModSendToast(error.localizedDescription ?: @"Thumbnail failed", presenter);
                return;
            }
            YouModRequestPhotoAccess(^(BOOL granted) {
                if (!granted) {
                    YouModSendToast(@"Photos access denied", presenter);
                    return;
                }
                [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                    [PHAssetChangeRequest creationRequestForAssetFromImage:image];
                } completionHandler:^(BOOL success, NSError *saveError) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        YouModSendToast(success ? @"Saved to Photos" : (saveError.localizedDescription ?: @"Save failed"), presenter);
                    });
                }];
            });
        });
    }] resume];
}

static void YouModCopyVideoInfo(YTPlayerViewController *player, UIViewController *presenter) {
    NSString *videoID = YouModVideoIDForPlayer(player);
    NSString *title = YouModTitleForPlayer(player);
    NSString *url = videoID.length ? [NSString stringWithFormat:@"https://youtu.be/%@", videoID] : @"";
    UIPasteboard.generalPasteboard.string = url.length ? [NSString stringWithFormat:@"%@\n%@", title, url] : title;
    YouModSendToast(@"Copied video information", presenter);
}

static void YouModShowVideoQualitySheet(YTPlayerViewController *player, UIViewController *presenter, UIView *sender) {
    NSArray <YouModMediaFormat *> *videoFormats = YouModFormatsForPlayer(player, YES);
    YouModMediaFormat *audioFormat = YouModBestAudioFormatForPlayer(player);
    NSString *title = YouModTitleForPlayer(player);
    NSString *videoID = YouModVideoIDForPlayer(player);

    if (videoFormats.count == 0 || !audioFormat) {
        YouModSendToast(@"No video/audio streams found", presenter);
        return;
    }

    NSMutableArray *items = [NSMutableArray array];
    for (YouModMediaFormat *format in videoFormats) {
        NSString *rowTitle = format.qualityLabel.length ? format.qualityLabel : @"Video";
        NSString *subtitle = YouModFormatSubtitle(format);
        [items addObject:[YouModMenuItem itemWithTitle:rowTitle subtitle:subtitle icon:YouModIconImage(658) handler:^{
            [[YouModDownloadCoordinator sharedCoordinator] startVideoDownloadWithVideoFormat:format audioFormat:audioFormat fileName:title videoID:videoID presenter:presenter];
        }]];
    }
    YouModPresentMenu(@"Download video", items, presenter, sender);
}

static void YouModShowAudioSourceSheet(YTPlayerViewController *player, YouModAudioOutputFormat *outputFormat, UIViewController *presenter, UIView *sender) {
    NSArray <YouModMediaFormat *> *audioFormats = YouModFormatsForPlayer(player, NO);
    NSString *title = YouModTitleForPlayer(player);
    NSString *videoID = YouModVideoIDForPlayer(player);
    NSMutableArray *items = [NSMutableArray array];

    if (audioFormats.count == 0) {
        if (items.count) {
            YouModPresentMenu(@"Download audio", items, presenter, sender);
            return;
        }
        YouModSendToast(@"No audio streams found", presenter);
        return;
    }

    NSUInteger index = 1;
    for (YouModMediaFormat *format in audioFormats) {
        NSString *rowTitle = audioFormats.count == 1 ? @"Audio" : [NSString stringWithFormat:@"Audio %lu", (unsigned long)index++];
        NSString *subtitle = YouModFormatSubtitle(format);
        [items addObject:[YouModMenuItem itemWithTitle:rowTitle subtitle:subtitle icon:YouModIconImage(21) handler:^{
            [[YouModDownloadCoordinator sharedCoordinator] startAudioDownloadWithAudioFormat:format fileName:title videoID:videoID outputFormat:outputFormat presenter:presenter];
        }]];
    }
    NSString *menuTitle = outputFormat.title.length ? [NSString stringWithFormat:@"Download %@", outputFormat.title] : @"Download audio";
    YouModPresentMenu(menuTitle, items, presenter, sender);
}

static void YouModShowAudioSheet(YTPlayerViewController *player, UIViewController *presenter, UIView *sender) {
    NSMutableArray *items = [NSMutableArray array];
    for (YouModAudioOutputFormat *format in YouModAudioOutputFormats()) {
        [items addObject:[YouModMenuItem itemWithTitle:format.title subtitle:YouModAudioOutputSubtitle(format) icon:YouModIconImage(21) handler:^{
            if (!format.supported) {
                YouModSendToast(@"DSD export is not supported by bundled FFmpeg.", presenter);
                return;
            }
            YouModShowAudioSourceSheet(player, format, presenter, sender);
        }]];
    }
    YouModPresentMenu(@"Audio format", items, presenter, sender);
}

static void YouModShowCaptionsSheet(YTPlayerViewController *player, UIViewController *presenter, UIView *sender) {
    NSArray *tracks = YouModCaptionTracksForPlayer(player);
    if (tracks.count == 0) {
        YouModSendToast(@"No captions available for this video.", presenter);
        return;
    }
    
    NSMutableArray *items = [NSMutableArray array];
    for (id track in tracks) {
        NSString *baseURL = YouModStringFromSelector(track, @selector(baseURL));
        if (baseURL.length == 0) continue;
        
        NSString *languageCode = YouModStringFromSelector(track, @selector(languageCode));
        NSString *vssId = YouModStringFromSelector(track, @selector(vssId));
        NSString *nameStr = nil;
        id nameObj = YouModObjectFromSelector(track, @selector(name));
        nameStr = YouModStringFromSelector(nameObj, @selector(simpleText));
        if (!nameStr.length) {
            NSArray *runs = YouModObjectFromSelector(nameObj, @selector(runsArray));
            if (runs.count > 0) nameStr = YouModStringFromSelector(runs.firstObject, @selector(text));
        }
        if (!nameStr.length) nameStr = languageCode;
        if (!nameStr.length) nameStr = vssId;
        
        [items addObject:[YouModMenuItem itemWithTitle:nameStr subtitle:languageCode icon:YouModIconImage(637) handler:^{
            NSString *vttURL = [baseURL stringByAppendingString:@"&fmt=vtt"];
            NSURL *url = [NSURL URLWithString:vttURL];
            if (!url) {
                YouModSendToast(@"Invalid caption URL.", presenter);
                return;
            }
            YouModSendToast(@"Downloading captions...", presenter);
            [[NSURLSession.sharedSession dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (error || data.length == 0) {
                        YouModSendToast(@"Failed to download captions.", presenter);
                        return;
                    }
                    NSString *videoID = YouModVideoIDForPlayer(player) ?: @"video";
                    NSString *filename = [NSString stringWithFormat:@"%@_%@.vtt", videoID, languageCode ?: @"captions"];
                    NSURL *tempURL = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:filename]];
                    [data writeToURL:tempURL atomically:YES];
                    YouModShareFile(tempURL, presenter);
                });
            }] resume];
        }]];
    }
    
    if (items.count == 0) {
        YouModSendToast(@"No valid caption URLs found.", presenter);
        return;
    }
    
    YouModPresentMenu(@"Download captions", items, presenter, sender);
}

static void YouModShowDownloadManager(YTPlayerViewController *player, UIViewController *presenter, UIView *sender) {
    if (!player) {
        YouModSendToast(@"Open a video before using the download manager.", presenter);
        return;
    }

    NSString *videoID = YouModVideoIDForPlayer(player);
    NSMutableArray *items = [NSMutableArray array];
    [items addObject:[YouModMenuItem itemWithTitle:@"Download video" subtitle:@"Choose quality" icon:YouModIconImage(658) handler:^{
        YouModShowVideoQualitySheet(player, presenter, sender);
    }]];
    [items addObject:[YouModMenuItem itemWithTitle:@"Download audio" subtitle:@"Choose format" icon:YouModIconImage(21) handler:^{
        YouModShowAudioSheet(player, presenter, sender);
    }]];
    [items addObject:[YouModMenuItem itemWithTitle:@"Download captions" subtitle:@"Save subtitles as VTT" icon:YouModIconImage(637) handler:^{
        YouModShowCaptionsSheet(player, presenter, sender);
    }]];
    [items addObject:[YouModMenuItem itemWithTitle:@"Copy diagnostics" subtitle:@"Copy last error log" icon:YouModIconImage(870) handler:^{
        YouModCopyDownloadDiagnostics(presenter);
    }]];
    [items addObject:[YouModMenuItem itemWithTitle:@"Save thumbnail" subtitle:@"Save to Photos" icon:YouModIconImage(367) handler:^{
        YouModDownloadThumbnail(videoID, presenter);
    }]];
    [items addObject:[YouModMenuItem itemWithTitle:@"Copy video information" subtitle:@"Copy title and URL" icon:YouModIconImage(250) handler:^{
        YouModCopyVideoInfo(player, presenter);
    }]];
    YouModPresentMenu(@"Download manager", items, presenter, sender);
}

void YouModConfigureDownloadButton(_ASDisplayView *view) {
    if (![view.accessibilityIdentifier isEqualToString:@"id.ui.add_to.offline.button"]) return;
    if (!IS_ENABLED(DownloadManager) || IS_ENABLED(HideDownloadButton)) return;
    if (objc_getAssociatedObject(view, @selector(YouModDownloadButtonTapped:))) return;

    view.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:view action:@selector(YouModDownloadButtonTapped:)];
    tap.cancelsTouchesInView = YES;
    tap.delaysTouchesBegan = YES;
    tap.delaysTouchesEnded = YES;
    [view addGestureRecognizer:tap];
    objc_setAssociatedObject(view, @selector(YouModDownloadButtonTapped:), @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

%hook _ASDisplayView

%new
- (void)YouModDownloadButtonTapped:(UITapGestureRecognizer *)sender {
    if (sender.state != UIGestureRecognizerStateEnded) return;
    UIViewController *presenter = YouModPresenterForSender(self, YouModCurrentPlayerViewController);
    YTPlayerViewController *player = YouModPlayerFromViewController(presenter);
    YouModShowDownloadManager(player, presenter, self);
}

%end

%hook YTPlayerViewController

- (void)viewDidAppear:(BOOL)animated {
    %orig;
    YouModCurrentPlayerViewController = self;
}

- (void)viewWillDisappear:(BOOL)animated {
    %orig;
    if (YouModCurrentPlayerViewController == self)
        YouModCurrentPlayerViewController = nil;
}

%end

NSString *YouModGlobalAuthHeader = nil;

%hook SSOAuthorization
- (id)accessToken {
    id token = %orig;
    if ([token isKindOfClass:[NSString class]] && [(NSString *)token length] > 0) {
        YouModGlobalAuthHeader = [NSString stringWithFormat:@"Bearer %@", token];
    }
    return token;
}
%end

%hook SSOAuthorizationImpl
- (id)accessToken {
    id token = %orig;
    if ([token isKindOfClass:[NSString class]] && [(NSString *)token length] > 0) {
        YouModGlobalAuthHeader = [NSString stringWithFormat:@"Bearer %@", token];
    }
    return token;
}
%end

%hook GNPSSOAuthorizationService
- (id)authToken {
    id token = %orig;
    if ([token isKindOfClass:[NSString class]] && [(NSString *)token length] > 0) {
        YouModGlobalAuthHeader = [NSString stringWithFormat:@"Bearer %@", token];
    }
    return token;
}
%end