//
//  SampleHandler.m
//  ERTCDemoBroadcast
//
//  Created by Harper Kan on 2022/3/3.
//


#import "SampleHandler.h"

@implementation SampleHandler

- (void)broadcastStartedWithSetupInfo:(NSDictionary<NSString *,NSObject *> *)setupInfo {
    // User has requested to start the broadcast. Setup info from the UI extension can be supplied but optional.
    [[ERTCReplayKit sharedManager] setup];
}

- (void)broadcastPaused {
    // User has requested to pause the broadcast. Samples will stop being delivered.
}

- (void)broadcastResumed {
    // User has requested to resume the broadcast. Samples delivery will resume.
}

- (void)broadcastFinished {
    // User has requested to finish the broadcast.
    [[ERTCReplayKit sharedManager] finish];
}

- (void)processSampleBuffer:(CMSampleBufferRef)sampleBuffer withType:(RPSampleBufferType)sampleBufferType {
    switch ([ERTCReplayKit sharedManager].state) {
        case ERTCReplayKitStateStopped:
            [self finishBroadcastWithError:nil];
            return;
        case ERTCReplayKitStateUnconnected:
        case ERTCReplayKitStateConnecting:
        {
            NSString *endTipStr = @"未能与主应用建立链接";
            NSLog(@"FinishBroadcastWithError :%@ ",endTipStr);
            NSError *error = [NSError errorWithDomain:NSStringFromClass(self.class)
                                                     code:0
                                                 userInfo:@{
                                                     NSLocalizedFailureReasonErrorKey:endTipStr
                                                 }];
            [self finishBroadcastWithError:error];
            return;
        }
        default:
            break;
    }
    
    switch (sampleBufferType) {
        case RPSampleBufferTypeVideo:
            // Handle video sample buffer
            [[ERTCReplayKit sharedManager] sendVideoBuffer:sampleBuffer];
            break;
        case RPSampleBufferTypeAudioApp:
            // Handle audio sample buffer for app audio
            break;
        case RPSampleBufferTypeAudioMic:
            // Handle audio sample buffer for mic audio
            break;
            
        default:
            break;
    }
}

@end
