### Google Cast Context Setup Example Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/INDEX.txt Example of setting up the Google Cast context. This is a crucial step for enabling Google Cast functionality in your iOS application. ```swift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // ... let options = GCKCastOptions(receiverApplicationID: kBCOVCAFReceiverApplicationID) GCKCastContext.setSharedInstanceWith(options) // ... return true } ``` -------------------------------- ### Basic Brightcove Google Cast Manager Implementation Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/protocol-delegate.md This example demonstrates the basic setup and implementation of the `BCOVGoogleCastManagerDelegate` protocol. It includes initializing the cast manager and playback controller, and handling delegate callbacks for playback state changes and errors. ```swift import BrightcoveGoogleCast import BrightcovePlayerSDK class VideoViewController: UIViewController, BCOVGoogleCastManagerDelegate { var googleCastManager: BCOVGoogleCastManager! var playbackController: BCOVPlaybackController? override func viewDidLoad() { super.viewDidLoad() // Initialize cast manager googleCastManager = BCOVGoogleCastManager() googleCastManager.delegate = self // Initialize playback controller playbackController = BCOVPlayerSDKManager.sharedManager().createPlaybackController() playbackController?.add(googleCastManager) } // MARK: - BCOVGoogleCastManagerDelegate func switchedToRemotePlayback() { updateUIForRemotePlayback() } func switchedToLocalPlayback(_ lastKnownStreamPosition: TimeInterval, withError error: Error?) { updateUIForLocalPlayback() if let error = error { handleCastError(error) } } func currentCastedVideoDidComplete() { playNextVideo() } func suitableSourceNotFound() { showUnsupportedFormatAlert() } // MARK: - Helper Methods private func updateUIForRemotePlayback() { // Implementation } private func updateUIForLocalPlayback() { // Implementation } private func handleCastError(_ error: Error) { // Implementation } private func playNextVideo() { // Implementation } private func showUnsupportedFormatAlert() { // Implementation } } ``` -------------------------------- ### Minimal Example for Google Cast Integration Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/README.md This example demonstrates the basic setup for integrating Google Cast with the Brightcove Player SDK. It includes creating the cast manager, playback controller, and handling cast state changes. ```swift import BrightcoveGoogleCast import BrightcovePlayerSDK class ViewController: UIViewController, BCOVGoogleCastManagerDelegate { var googleCastManager: BCOVGoogleCastManager! var playbackController: BCOVPlaybackController? override func viewDidLoad() { super.viewDidLoad() // [1] Create manager let config = BCOVReceiverAppConfig() config.accountId = "4337717568001" config.policyKey = "BCpk..." googleCastManager = BCOVGoogleCastManager(forBrightcoveReceiverApp: config) googleCastManager.delegate = self // [2] Create playback controller playbackController = BCOVPlayerSDKManager.sharedManager() .createPlaybackController() // [3] Add manager as consumer playbackController?.add(googleCastManager) } // [4] Handle Cast events func switchedToRemotePlayback() { print("Now casting") } func switchedToLocalPlayback(_ pos: TimeInterval, withError error: Error?) { print("Returned to local playback") } func suitableSourceNotFound() { print("Cannot cast this video") } } ``` -------------------------------- ### CocoaPods Podfile Example Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/README.md Example of how to add the Brightcove-Player-GoogleCast pod to your project's Podfile. ```bash source 'https://github.com/CocoaPods/Specs' source 'https://github.com/brightcove/BrightcoveSpecs.git' platform :ios, '14.0' use_frameworks! target 'ExampleApp' do pod 'Brightcove-Player-GoogleCast' end ``` -------------------------------- ### Complete iOS Google Cast Integration Example Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/integration-guide.md A full example demonstrating the integration of Google Cast with the Brightcove Player SDK for iOS. Includes setup for navigation, player, cast manager, and video loading. ```swift import UIKit import BrightcovePlayerSDK import BrightcoveGoogleCast import GoogleCast import GoogleCastUI class VideoViewController: UIViewController { var playbackController: BCOVPlaybackController? var googleCastManager: BCOVGoogleCastManager! var castStatusLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() setupNavigation() setupPlayer() setupCast() loadVideo() } private func setupNavigation() { title = "Video Player" // Add Cast button let castButton = GCKUICastButton(frame: CGRect(x: 0, y: 0, width: 24, height: 24)) castButton.tintColor = .white navigationItem.rightBarButtonItem = UIBarButtonItem(customView: castButton) } private func setupPlayer() { // Create playback controller playbackController = BCOVPlayerSDKManager.sharedManager().createPlaybackController() playbackController?.delegate = self // Add to view if let view = playbackController?.view { addChild(playbackController!) view.frame = CGRect(x: 0, y: 0, width: 400, height: 300) self.view.addSubview(view) } } private func setupCast() { // Create receiver configuration let receiverConfig = BCOVReceiverAppConfig() receiverConfig.accountId = "4337717568001" receiverConfig.policyKey = "BCpk7DFtVLzWrWVT..." // Create Cast manager googleCastManager = BCOVGoogleCastManager(forBrightcoveReceiverApp: receiverConfig) googleCastManager.delegate = self googleCastManager.posterImageSize = CGSize(width: 1280, height: 720) // Add to playback controller playbackController?.add(googleCastManager) // Setup Cast status label castStatusLabel = UILabel() castStatusLabel.text = "Not casting" castStatusLabel.textColor = .gray view.addSubview(castStatusLabel) } private func loadVideo() { let catalog = BCOVCatalogService(token: "BCpk7DFtVLzWrWVT...") catalog.findVideoWithVideoID("6331507056001") { video, error in self.playbackController?.setVideo(video) } } } extension VideoViewController: BCOVGoogleCastManagerDelegate { func switchedToRemotePlayback() { castStatusLabel.text = "Casting..." castStatusLabel.textColor = .systemBlue } func switchedToLocalPlayback(_ pos: TimeInterval, withError error: Error?) { castStatusLabel.text = "Not casting" castStatusLabel.textColor = .gray if let error = error { print("Cast error: \(error)") } } func suitableSourceNotFound() { print("Cannot cast: no suitable source found") } } extension VideoViewController: BCOVPlaybackControllerDelegate { // Implement as needed } ``` -------------------------------- ### Basic Cast Integration Pattern Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/INDEX.txt A fundamental example demonstrating the basic integration of the Google Cast functionality. This pattern covers the essential setup for casting video content. ```swift // Pattern 1: Basic Cast Integration // Setup Google Cast context let options = GCKCastOptions(receiverApplicationID: kBCOVCAFReceiverApplicationID) GCKCastContext.setSharedInstanceWith(options) // Initialize BCOVGoogleCastManager let castManager = BCOVGoogleCastManager.init(delegate: self) // Prepare for reuse when loading a new video castManager.prepareForReuse() // Add cast button to your UI // let castButton = GCKCastButton.init(frame: CGRect.init(x: 0, y: 0, width: 44, height: 44)) // self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: castButton) ``` -------------------------------- ### Complete Brightcove Google Cast Configuration Example Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/api-reference-receiver-config.md This example demonstrates how to initialize and configure BCOVReceiverAppConfig with various optional parameters, including account ID, policy key, authentication, watermarking, ads, analytics, custom player URL, and splash screen. ```swift import BrightcoveGoogleCast let receiverAppConfig = BCOVReceiverAppConfig() // Required receiverAppConfig.accountId = "4337717568001" receiverAppConfig.policyKey = "BCpk7DFtVLzWrWVTW2tVrVFGk6..." // Optional - Authentication & Playback Restrictions receiverAppConfig.authToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." // Optional - Watermarking receiverAppConfig.watermarkingToken = "fwm_token_xyz123..." // Optional - Server-Side Ads receiverAppConfig.adConfigId = "ssai_config_456" // Optional - Analytics receiverAppConfig.userId = "user_8765432" receiverAppConfig.applicationId = "myapp_ios_v1" // Optional - Custom Player receiverAppConfig.playerUrl = "https://players.brightcove.net/4337717568001/default_default/index.min.js" // Optional - UI Customization receiverAppConfig.splashScreen = "https://example.com/images/splash.jpg" // Create manager with configuration let googleCastManager = BCOVGoogleCastManager(forBrightcoveReceiverApp: receiverAppConfig) ``` -------------------------------- ### Async Video Loading and Casting Setup Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/implementation-patterns.md This snippet shows how to set up the BCOVPlaybackController and BCOVGoogleCastManager, load a video asynchronously, and handle potential casting errors. It's useful for applications that need to support video casting. ```swift class AsyncCastViewController: UIViewController { var playbackController: BCOVPlaybackController? var googleCastManager: BCOVGoogleCastManager! var currentVideo: BCOVVideo? override func viewDidLoad() { super.viewDidLoad() googleCastManager = BCOVGoogleCastManager() googleCastManager.delegate = self playbackController = BCOVPlayerSDKManager.sharedManager() .createPlaybackController() playbackController?.add(googleCastManager) loadVideo(videoId: "6331507056001") } private func loadVideo(videoId: String) { let catalogService = BCOVCatalogService(token: "BCpk7DFtVLzWrWVT...") showLoadingSpinner() catalogService.findVideoWithVideoID(videoId) { [weak self] video, error in DispatchQueue.main.async { self?.hideLoadingSpinner() guard let video = video else { self?.showError("Video not found: \(error?.localizedDescription ?? \"unknown\")") return } self?.currentVideo = video self?.playbackController?.setVideo(video) } } } private func showLoadingSpinner() { // Implementation } private func hideLoadingSpinner() { // Implementation } private func showError(_ message: String) { let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default)) present(alert, animated: true) } } extension AsyncCastViewController: BCOVGoogleCastManagerDelegate { func suitableSourceNotFound() { showError("This video cannot be cast") } } ``` -------------------------------- ### Handle No Suitable Source Found Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/source-selection.md Implement the `suitableSourceNotFound` delegate method to handle scenarios where no compatible source is available for casting. This example logs a message and presents a user-friendly alert. ```swift extension VideoViewController: BCOVGoogleCastManagerDelegate { func suitableSourceNotFound() { // No castable source found print("This video cannot be cast") // Show user-friendly error let alert = UIAlertController( title: "Cannot Cast Video", message: "This video is not available for casting.", preferredStyle: .alert ) alert.addAction(UIAlertAction(title: "OK", style: .default)) present(alert, animated: true) } } ``` -------------------------------- ### Basic Brightcove Google Cast Setup Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/configuration.md Configure the BCOVGoogleCastManager with basic Brightcove receiver app details. This setup is suitable for standard video playback casting. ```swift import BrightcoveGoogleCast import BrightcovePlayerSDK class VideoViewController: UIViewController { var googleCastManager: BCOVGoogleCastManager! var playbackController: BCOVPlaybackController? override func viewDidLoad() { super.viewDidLoad() // Create receiver configuration let receiverConfig = BCOVReceiverAppConfig() receiverConfig.accountId = "4337717568001" receiverConfig.policyKey = "BCpk7DFtVLzWrWVT..." // Create and configure manager googleCastManager = BCOVGoogleCastManager(forBrightcoveReceiverApp: receiverConfig) googleCastManager.delegate = self googleCastManager.posterImageSize = CGSize(width: 1280, height: 720) googleCastManager.createMediaTracks = true // Create playback controller playbackController = BCOVPlayerSDKManager.sharedManager().createPlaybackController() playbackController?.add(googleCastManager) } } extension VideoViewController: BCOVGoogleCastManagerDelegate { func switchedToRemotePlayback() { print("Casting started") } func switchedToLocalPlayback(_ pos: TimeInterval, withError error: Error?) { print("Casting ended at \(pos)s") } } ``` -------------------------------- ### Configure Player for Generic Stream Concurrency Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/README.md Example JSON configuration for a Brightcove player to enable Generic Stream Concurrency. This involves setting 'stream_concurrency' to true and providing a policy key. ```json { "video_cloud": { "stream_concurrency": true, "policy_key": "BCpk..." }, "player": { "template": { "name": "single-video-template", "version": "6.63.1" } }, } ``` -------------------------------- ### Handle Remote Playback Start Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/protocol-delegate.md Called when a Cast session starts and playback moves to a remote Cast device. Use this to show/hide UI elements or trigger other events when a user initiates casting. ```swift extension ViewController: BCOVGoogleCastManagerDelegate { func switchedToRemotePlayback() { print("Now casting to device") // Update UI to reflect remote playback castStatusLabel.text = "Casting to Living Room" castStatusLabel.isHidden = false // Hide local playback controls localControlsView.isHidden = true } } ``` -------------------------------- ### Advanced Brightcove Google Cast Setup with SSAI Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/configuration.md Enable Server-Side Ad Insertion (SSAI) by providing an ad configuration ID. This setup is for advanced ad experiences. ```swift let receiverConfig = BCOVReceiverAppConfig() receiverConfig.accountId = "4337717568001" receiverConfig.policyKey = "BCpk7DFtVLzWrWVT..." receiverConfig.adConfigId = "ssai_config_456" // Enable SSAI receiverConfig.userId = "user_8765432" receiverConfig.applicationId = "myapp_ios_v1" let googleCastManager = BCOVGoogleCastManager(forBrightcoveReceiverApp: receiverConfig) ``` -------------------------------- ### Override Default Source Selection Logic Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/source-selection.md Implement the `useSourceFromSources:` delegate method to provide custom logic for selecting the best video source. This example demonstrates preferring high-bitrate DASH sources, then any DASH source, and finally falling back to the first available source. ```swift extension VideoViewController: BCOVGoogleCastManagerDelegate { func useSourceFromSources(_ sources: [BCOVSource]) -> BCOVSource { // Custom selection logic // Example 1: Prefer high-bitrate DASH for source in sources { if source.deliveryMethod == "dash" && source.bitrate > 5000 { return source } } // Example 2: Prefer specific codec for source in sources { if source.deliveryMethod == "dash" { return source } } // Fallback to first available return sources.first ?? BCOVSource() } } ``` -------------------------------- ### Adopting BCOVGoogleCastManagerDelegate Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/types.md Example of adopting the BCOVGoogleCastManagerDelegate protocol in a UIViewController. Ensure the delegate is set on the BCOVGoogleCastManager instance. ```Swift class MyViewController: UIViewController, BCOVGoogleCastManagerDelegate { var googleCastManager: BCOVGoogleCastManager! override func viewDidLoad() { super.viewDidLoad() googleCastManager.delegate = self } // Implement optional delegate methods... } ``` -------------------------------- ### Basic Brightcove Google Cast Integration Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/implementation-patterns.md Minimal setup to enable casting functionality. Requires importing necessary Brightcove and Google Cast SDKs. ```swift import UIKit import BrightcovePlayerSDK import BrightcoveGoogleCast import GoogleCast class BasicCastViewController: UIViewController { var playbackController: BCOVPlaybackController? var googleCastManager: BCOVGoogleCastManager! override func viewDidLoad() { super.viewDidLoad() // Create manager googleCastManager = BCOVGoogleCastManager() // Create playback controller playbackController = BCOVPlayerSDKManager.sharedManager() .createPlaybackController() // Register manager playbackController?.add(googleCastManager) // Add to view if let view = playbackController?.view { addChild(playbackController!) self.view.addSubview(view) } } } ``` -------------------------------- ### Advanced Brightcove Google Cast Setup with Stream Concurrency Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/configuration.md Configure stream concurrency by specifying a player URL and providing a JWT token with the necessary GSC claims. This is for managing multiple concurrent streams. ```swift let receiverConfig = BCOVReceiverAppConfig() receiverConfig.accountId = "4337717568001" receiverConfig.policyKey = "BCpk7DFtVLzWrWVT..." // Must use a player with stream concurrency enabled receiverConfig.playerUrl = "https://players.brightcove.net/4337717568001/v2_default/index.min.js" // JWT token with required GSC claims let jwtToken = generateGSCJWT( userId: "user_123", streamLimit: 2, sessionId: UUID().uuidString ) receiverConfig.authToken = jwtToken let googleCastManager = BCOVGoogleCastManager(forBrightcoveReceiverApp: receiverConfig) ``` -------------------------------- ### Install Brightcove Google Cast via CocoaPods Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/integration-guide.md Use this Ruby code in your Podfile to install the Brightcove Google Cast plugin. Ensure your pod repo is updated before installing. ```ruby source 'https://github.com/CocoaPods/Specs' source 'https://github.com/brightcove/BrightcoveSpecs.git' platform :ios, '14.0' use_frameworks! target 'ExampleApp' do pod 'Brightcove-Player-GoogleCast' end ``` -------------------------------- ### switchedToRemotePlayback Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/protocol-delegate.md Called when a Cast session starts and playback moves to a remote Cast device. Use this to show/hide UI elements or trigger other events when a user initiates casting. ```APIDOC ## Method: switchedToRemotePlayback ### Description Called when a Cast session starts and playback moves to a remote Cast device. Use this to show/hide UI elements or trigger other events when a user initiates casting. ### Signature ```swift func switchedToRemotePlayback() ``` ### Return Type `Void` ### Example ```swift extension ViewController: BCOVGoogleCastManagerDelegate { func switchedToRemotePlayback() { print("Now casting to device") // Update UI to reflect remote playback castStatusLabel.text = "Casting to Living Room" castStatusLabel.isHidden = false // Hide local playback controls localControlsView.isHidden = true } } ``` ``` -------------------------------- ### Select Custom Source by Bitrate/Format (Swift) Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/implementation-patterns.md Implement BCOVGoogleCastManagerDelegate to select specific video sources based on delivery method and bitrate. Prefers DASH sources with a bitrate above 2000 kbps, falling back to any DASH source, and finally to the first available source. ```swift extension CastViewController: BCOVGoogleCastManagerDelegate { func useSourceFromSources(_ sources: [BCOVSource]) -> BCOVSource { print("Available sources:") for source in sources { print(" - \(source.deliveryMethod ?? \"unknown\"): \(source.bitrate) kbps") } // Prefer DASH with medium-to-high bitrate let dashSources = sources.filter { source in source.deliveryMethod == "dash" && source.bitrate > 2000 } if let preferredSource = dashSources.sorted(by: { $0.bitrate > $1.bitrate }).first { print("Selected DASH: \(preferredSource.bitrate) kbps") return preferredSource } // Fall back to any DASH if let dashSource = sources.first(where: { $0.deliveryMethod == "dash" }) { return dashSource } // Final fallback return sources.first ?? BCOVSource() } } ``` -------------------------------- ### BCOVGoogleCastManager Instance Method Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/module-overview.md The `prepareForReuse` instance method for BCOVGoogleCastManager. ```APIDOC ## Public API Inventory ### Instance Methods | Class | Method | Signature | |-------|--------|-----------| | `BCOVGoogleCastManager` | `prepareForReuse` | `- (void)prepareForReuse;` | ``` -------------------------------- ### BCOVGoogleCastManager Initialization Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/README.md Demonstrates how to initialize the BCOVGoogleCastManager for both demo and production Brightcove receiver applications. ```APIDOC ## BCOVGoogleCastManager Initialization ### Description Initializes the `BCOVGoogleCastManager` for either a demo receiver or a production Brightcove receiver application. ### Usage **Default manager (demo receiver):** ```swift let manager = BCOVGoogleCastManager() ``` **Brightcove receiver (production):** ```swift let config = BCOVReceiverAppConfig() let manager = BCOVGoogleCastManager(forBrightcoveReceiverApp: config) ``` **Reset state for reuse:** ```swift manager.prepareForReuse() ``` ``` -------------------------------- ### Objective-C Property Declaration Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/types.md Example of a weak delegate property declaration in Objective-C, commonly found in manager classes. ```objc @property (nonatomic, weak) id delegate; ``` -------------------------------- ### Override Source Selection for Google Cast Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/configuration.md Implement `useSourceFromSources:` to manually select the video source, for example, to prioritize high-bitrate DASH sources over others. ```swift func useSourceFromSources(_ sources: [BCOVSource]) -> BCOVSource { // Prefer high-bitrate DASH sources for source in sources { if source.deliveryMethod == "dash" && source.bitrate > 5000 { return source } } return sources.first ?? BCOVSource() } ``` -------------------------------- ### Initialize Google Cast Manager Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/README.md Instantiate the BCOVGoogleCastManager. Use the default manager for the demo receiver or provide a BCOVReceiverAppConfig for production Brightcove receivers. Remember to call prepareForReuse() to reset state. ```swift // Default manager (demo receiver) let manager = BCOVGoogleCastManager() // Brightcove receiver (production) let config = BCOVReceiverAppConfig() let manager = BCOVGoogleCastManager(forBrightcoveReceiverApp: config) // Reset state for reuse manager.prepareForReuse() ``` -------------------------------- ### Logging Source Selection for Debugging Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/source-selection.md Implement logging to record the selected source's details, including URL, delivery method, and bitrate. This aids in debugging source selection issues. ```swift func useSourceFromSources(_ sources: [BCOVSource]) -> BCOVSource { guard let selected = selectPreferredSource(sources) else { print("ERROR: No preferred source found") return sources.first ?? BCOVSource() } print("Selected source for casting:") print(" URL: \(selected.url?.absoluteString ?? \"N/A\")") print(" Type: \(selected.deliveryMethod ?? \"unknown\")") print(" Bitrate: \(selected.bitrate) kbps") return selected } ``` -------------------------------- ### Handle Cast Session Changes Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/implementation-patterns.md Implement GCKSessionManagerListener to detect when a Cast session starts or ends. This is useful for updating the UI to reflect casting status. ```swift class CastSessionViewController: UIViewController, GCKSessionManagerListener { var googleCastManager: BCOVGoogleCastManager! override func viewDidLoad() { super.viewDidLoad() // Create manager googleCastManager = BCOVGoogleCastManager() googleCastManager.delegate = self // Listen for Cast session changes GCKCastContext.sharedInstance().sessionManager.add(self) } deinit { GCKCastContext.sharedInstance().sessionManager.remove(self) } // MARK: - GCKSessionManagerListener func sessionManager(_ sessionManager: GCKSessionManager, didStartSession session: GCKSession) { print("Cast device connected: \(session.displayName)") updateUIForCasting() } func sessionManager(_ sessionManager: GCKSessionManager, didEndSession session: GCKSession, withError error: Error?) { print("Cast device disconnected") updateUIForLocalPlayback() } private func updateUIForCasting() { // Show casting UI } private func updateUIForLocalPlayback() { // Show local playback UI } } extension CastSessionViewController: BCOVGoogleCastManagerDelegate { func switchedToRemotePlayback() { print("Video switched to remote playback") } func switchedToLocalPlayback(_ pos: TimeInterval, withError error: Error?) { print("Video switched back to local playback") } } ``` -------------------------------- ### Create Playback Controller Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/module-overview.md Create a playback controller using the shared Brightcove Player SDK manager. ```swift BCOVPlayerSDKManager.sharedManager().createPlaybackController() ``` -------------------------------- ### Automatic Source Selection Logic Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/source-selection.md This pseudocode illustrates the priority-based logic for selecting the best video source for casting. It iterates through a predefined list of source types and selects the first available match. ```pseudocode For each source type in priority order: If source exists for video: Select source and proceed to casting Else: Continue to next source type If no source found: Call delegate method: suitableSourceNotFound() Casting cannot proceed ``` -------------------------------- ### Swift Import Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/module-overview.md This is the recommended import path for Swift projects, which automatically exposes all public types. ```APIDOC ## Import Paths ### Swift ```swift import BrightcoveGoogleCast ``` This is the recommended import for Swift projects. It automatically exposes all public types. ``` -------------------------------- ### Advanced Brightcove Google Cast Setup with Custom Branding Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/configuration.md Customize the cast receiver's appearance with a splash screen and fallback poster image. This allows for branded casting experiences. ```swift let receiverConfig = BCOVReceiverAppConfig() receiverConfig.accountId = "4337717568001" receiverConfig.policyKey = "BCpk7DFtVLzWrWVT..." receiverConfig.splashScreen = "https://example.com/branding/splash.jpg" receiverConfig.playerUrl = "https://players.brightcove.net/4337717568001/custom_player/index.min.js" let googleCastManager = BCOVGoogleCastManager(forBrightcoveReceiverApp: receiverConfig) googleCastManager.fallbackPosterImage = loadFallbackImage() googleCastManager.posterImageSize = CGSize(width: 1920, height: 1080) ``` -------------------------------- ### Select Source by Network Bandwidth (Swift) Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/known-limitations.md Selects the most appropriate video source based on estimated network bandwidth to optimize playback quality and minimize buffering. Ensure adaptive bitrate selection is implemented. ```swift func useSourceFromSources(_ sources: [BCOVSource]) -> BCOVSource { let bandwidth = estimateNetworkBandwidth() let filtered = sources.filter { source in source.bitrate <= bandwidth } return filtered.sorted { $0.bitrate > $1.bitrate }.first ?? sources.first ?? BCOVSource() } ``` -------------------------------- ### Control Video Casting with shouldCastVideo Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/protocol-delegate.md Implement this method to override the default logic for casting videos. Return `false` to prevent casting, for example, if the video ID is the same as the last casted video or if the video is marked as local-only. ```swift extension ViewController: BCOVGoogleCastManagerDelegate { func shouldCastVideo(_ video: BCOVVideo) -> Bool { // Don't re-cast if it's the same video ID if video.properties["id"] as? String == lastCastedVideoId { return false } // Don't cast videos marked as local-only if video.properties["localOnly"] as? Bool == true { return false } return true } } ``` -------------------------------- ### Objective-C Import Path (Full) Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/module-overview.md Import the entire Brightcove Google Cast SDK for Objective-C projects. ```objc #import ``` -------------------------------- ### Debug: Log All Available Video Sources Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/source-selection.md Use this function to log all available sources for a video, which helps in diagnosing why a video might not be casting. ```swift func useSourceFromSources(_ sources: [BCOVSource]) -> BCOVSource { if sources.isEmpty { print("ERROR: No sources available for video") } else { sources.forEach { source in print("Available source: \(source.deliveryMethod ?? "unknown") - \(source.url?.absoluteString ?? "N/A")") } } return sources.first ?? BCOVSource() } ``` -------------------------------- ### Select Custom Source for Google Cast Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/protocol-delegate.md Implement this method to override the default source selection logic for casting. This allows you to specify which BCOVSource should be used with the Cast receiver, for example, by preferring specific delivery methods or bitrates. ```swift extension ViewController: BCOVGoogleCastManagerDelegate { func useSourceFromSources(_ sources: [BCOVSource]) -> BCOVSource { // Prefer DASH sources with a specific codec for source in sources { if source.deliveryMethod == "dash" && source.bitrate > 2000 { return source } } // Fallback to first available source return sources.first ?? BCOVSource() } } ``` -------------------------------- ### Initialize Brightcove Google Cast Manager and Playback Controller Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/README.md This snippet demonstrates the basic usage for integrating the Brightcove Google Cast plugin. It involves creating instances of BCOVGoogleCastManager and BCOVPlaybackController, and then adding the manager as a session consumer to the playback controller. ```swift googleCastManager = BCOVGoogleCastManager() playbackController = BCOVPlayerSDKManager.sharedManager().createPlaybackController() playbackController?.add(googleCastManager) ``` -------------------------------- ### Custom Analytics for Cast Events Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/implementation-patterns.md Implement custom analytics tracking for Google Cast events by conforming to the BCOVGoogleCastManagerDelegate protocol. This snippet shows how to log events like cast start, end, completion, failure, and source not found. ```swift class AnalyticsCastViewController: UIViewController, BCOVGoogleCastManagerDelegate { var analyticsService: AnalyticsService! var googleCastManager: BCOVGoogleCastManager! var castStartTime: Date? override func viewDidLoad() { super.viewDidLoad() analyticsService = AnalyticsService() let config = BCOVReceiverAppConfig() config.accountId = "4337717568001" config.policyKey = "BCpk7DFtVLzWrWVT..." config.userId = analyticsService.currentUserId config.applicationId = "myapp_v2" googleCastManager = BCOVGoogleCastManager(forBrightcoveReceiverApp: config) googleCastManager.delegate = self } // MARK: - BCOVGoogleCastManagerDelegate func switchedToRemotePlayback() { castStartTime = Date() analyticsService.logEvent("cast_started", parameters: [:]) } func switchedToLocalPlayback(_ pos: TimeInterval, withError error: Error?) { let castDuration = Date().timeIntervalSince(castStartTime ?? Date()) analyticsService.logEvent("cast_ended", parameters: [ "duration": castDuration, "position": pos, "error": error?.localizedDescription ?? "none" ]) castStartTime = nil } func currentCastedVideoDidComplete() { analyticsService.logEvent("cast_video_completed", parameters: [:]) } func castedVideoFailedToPlay() { analyticsService.logEvent("cast_video_failed", parameters: [:]) } func suitableSourceNotFound() { analyticsService.logEvent("cast_no_source", parameters: [:]) } } // Mock analytics service class AnalyticsService { let currentUserId = "user_" + UUID().uuidString func logEvent(_ name: String, parameters: [String: Any]) { print("Analytics: \(name) - \(parameters)") } } ``` -------------------------------- ### Implement BCOVGoogleCastManagerDelegate Methods Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/integration-guide.md Handle Cast-related events by implementing the BCOVGoogleCastManagerDelegate protocol. This includes updating the UI for remote and local playback, handling video completion on the Cast device, and managing errors when a suitable source is not found. ```swift extension VideoViewController: BCOVGoogleCastManagerDelegate { func switchedToRemotePlayback() { print("Now casting to device") // Update UI: hide local controls, show "Casting to..." label updateUIForCasting() } func switchedToLocalPlayback(_ lastKnownStreamPosition: TimeInterval, withError error: Error?) { print("Returned to local playback") // Update UI: show local controls updateUIForLocalPlayback() // Optionally resume at the remote position if error == nil { playbackController?.seek(to: CMTime(seconds: lastKnownStreamPosition, preferredTimescale: 600)) } } func currentCastedVideoDidComplete() { // Video finished on Cast device // Load next video or dismiss } func suitableSourceNotFound() { // No compatible source found (likely DRM or unsupported format) showError("This video cannot be cast") } } ``` -------------------------------- ### Unit Tests for Cast Integration Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/implementation-patterns.md Provides unit tests for verifying the initialization and configuration of Google Cast functionality within a Brightcove iOS application. Includes tests for manager setup, receiver app configuration, and delegate callback handling. ```swift import XCTest @testable import MyCastApp class CastIntegrationTests: XCTestCase { var viewController: CastViewController! var mockPlaybackController: MockBCOVPlaybackController! override func setUp() { super.setUp() viewController = CastViewController() mockPlaybackController = MockBCOVPlaybackController() viewController.playbackController = mockPlaybackController } func testManagerInitialization() { // Given let viewController = CastViewController() // When viewController.viewDidLoad() // Then XCTAssertNotNil(viewController.googleCastManager) } func testReceiverConfiguration() { // Given let config = BCOVReceiverAppConfig() config.accountId = "test_account" config.policyKey = "test_key" // When let manager = BCOVGoogleCastManager(forBrightcoveReceiverApp: config) // Then XCTAssertEqual(manager.appConfig.accountId, "test_account") XCTAssertEqual(manager.appConfig.policyKey, "test_key") } func testDelegateCallbacks() { // Given var delegateCalled = false let delegate = MockCastDelegate { delegateCalled = true } viewController.googleCastManager.delegate = delegate // When // Simulate Cast session start delegate.simulateSwitchToRemotePlayback() // Then XCTAssertTrue(delegateCalled) } } class MockBCOVPlaybackController: BCOVPlaybackController { // Mock implementation } class MockCastDelegate: NSObject, BCOVGoogleCastManagerDelegate { let onCallback: () -> Void init(_ callback: @escaping () -> Void) { self.onCallback = callback } func switchedToRemotePlayback() { onCallback() } func simulateSwitchToRemotePlayback() { switchedToRemotePlayback() } } ``` -------------------------------- ### Brightcove Google Cast Integration with Custom Receiver and Error Handling Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/implementation-patterns.md A more robust setup enabling casting to a Brightcove receiver app, including delegate callbacks for managing playback state and handling errors. Requires configuring receiver app details and implementing the BCOVGoogleCastManagerDelegate protocol. ```swift import UIKit import BrightcovePlayerSDK import BrightcoveGoogleCast class RobustCastViewController: UIViewController, BCOVGoogleCastManagerDelegate { var playbackController: BCOVPlaybackController? var googleCastManager: BCOVGoogleCastManager! var castStatusView: UIView! override func viewDidLoad() { super.viewDidLoad() setupReceiver() setupUI() } private func setupReceiver() { // Configure receiver let config = BCOVReceiverAppConfig() config.accountId = "4337717568001" config.policyKey = "BCpk7DFtVLzWrWVT..." config.userId = "user_\(UIDevice.current.identifierForVendor?.uuidString ?? "unknown")" // Create manager googleCastManager = BCOVGoogleCastManager(forBrightcoveReceiverApp: config) googleCastManager.delegate = self googleCastManager.posterImageSize = CGSize(width: 1280, height: 720) // Create playback controller playbackController = BCOVPlayerSDKManager.sharedManager() .createPlaybackController() playbackController?.add(googleCastManager) } private func setupUI() { // Add Cast button let castButton = GCKUICastButton(frame: CGRect(x: 0, y: 0, width: 24, height: 24)) castButton.tintColor = .white navigationItem.rightBarButtonItem = UIBarButtonItem(customView: castButton) // Status view castStatusView = UIView() castStatusView.backgroundColor = .systemBlue castStatusView.isHidden = true view.addSubview(castStatusView) } // MARK: - BCOVGoogleCastManagerDelegate func switchedToRemotePlayback() { castStatusView.isHidden = false } func switchedToLocalPlayback(_ pos: TimeInterval, withError error: Error?) { castStatusView.isHidden = true if let error = error { handleError(error) } } func suitableSourceNotFound() { showAlert("Cannot Cast", "This video format is not supported for casting") } private func handleError(_ error: Error) { print("Cast error: \(error.localizedDescription)") } private func showAlert(_ title: String, _ message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default)) present(alert, animated: true) } } ``` -------------------------------- ### Initialize Google Cast Manager Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/integration-guide.md Instantiate `BCOVGoogleCastManager` using the configured `BCOVReceiverAppConfig`. Set the manager as a delegate and optionally configure the poster image size. ```swift import BrightcoveGoogleCast class VideoViewController: UIViewController { var googleCastManager: BCOVGoogleCastManager! var playbackController: BCOVPlaybackController? override func viewDidLoad() { super.viewDidLoad() // Create manager with Brightcove receiver let receiverConfig = BCOVReceiverAppConfig() receiverConfig.accountId = "4337717568001" receiverConfig.policyKey = "BCpk7DFtVLzWrWVT..." googleCastManager = BCOVGoogleCastManager(forBrightcoveReceiverApp: receiverConfig) googleCastManager.delegate = self googleCastManager.posterImageSize = CGSize(width: 1280, height: 720) } } ``` -------------------------------- ### Handle No Suitable Source Found for Casting Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/protocol-delegate.md Implement `suitableSourceNotFound` when the `BCOVGoogleCastManager` cannot find a compatible video source for casting. This is useful for handling unsupported video formats, such as DRM-protected content. ```swift extension ViewController: BCOVGoogleCastManagerDelegate { func suitableSourceNotFound() { print("No suitable source found for casting") let alert = UIAlertController(title: "Cannot Cast", message: "This video format is not supported for casting.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default)) present(alert, animated: true) } } ``` -------------------------------- ### Configure SSAI (Server-Side Ad Insertion) Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/receiver-features.md Set the Server-Side Ad Insertion configuration ID to enable ads on the receiver. The ad config must be set up in Video Cloud Studio. ```swift config.adConfigId = "ssai_config_456" ``` -------------------------------- ### Async Video Loading Pattern Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/INDEX.txt Shows how to load video content asynchronously for casting. This pattern is useful when fetching video data from a remote source before initiating playback on the cast receiver. ```swift // Pattern 9: Async Video Loading // Fetch your BCOVVideo object asynchronously, then load it for casting. // Example: // fetchVideoFromAPI { [weak self] (video: BCOVVideo?) in // guard let video = video else { // // Handle error // return // } // // Load the video using BCOVGoogleCastManager // self?.castManager.loadVideo(video) // } ``` -------------------------------- ### Custom Source Selection Pattern Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/INDEX.txt Demonstrates how to implement custom logic for selecting video sources when using Google Cast. This is useful for prioritizing specific video renditions or formats. ```swift // Pattern 3: Custom Source Selection // Implement BCOVGoogleCastManagerDelegate // Example method for custom source selection func googleCastManager(_ manager: BCOVGoogleCastManager, sourceFor video: BCOVVideo) -> BCOVVideoSource? { // Your custom logic to select the best source for casting // For example, prioritize HLS over DASH, or a specific rendition return video.sources.first { $0.url != nil && $0.url!.absoluteString.contains(".m3u8") } } ``` -------------------------------- ### Initialize Default Google Cast Manager Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/configuration.md Use this to create a BCOVGoogleCastManager with the default Google Cast receiver. This is suitable for testing or demos, but has limitations with DRM, multiple audio tracks, advertising, and live streams. ```swift let googleCastManager = BCOVGoogleCastManager() ``` -------------------------------- ### Configure Brightcove Receiver App Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/integration-guide.md Set up the `BCOVReceiverAppConfig` with your Video Cloud account ID and policy key. Optional fields like userId and applicationId can also be configured. ```swift import BrightcoveGoogleCast let receiverConfig = BCOVReceiverAppConfig() receiverConfig.accountId = "YOUR_ACCOUNT_ID" receiverConfig.policyKey = "YOUR_POLICY_KEY" // Optional: Configure additional features receiverConfig.userId = "user_identifier" receiverConfig.applicationId = "app_identifier" ``` -------------------------------- ### Create Brightcove Playback Controller Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/integration-guide.md Initialize the Brightcove Player SDK playback controller and set its delegate. This controller is essential for managing video playback. ```swift import BrightcovePlayerSDK let playbackController = BCOVPlayerSDKManager.sharedManager().createPlaybackController() playbackController?.delegate = self ``` -------------------------------- ### Validate Configuration Before Initialization Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/receiver-features.md Before creating the BCOVGoogleCastManager, validate that essential configuration fields like 'accountId' and 'policyKey' are not empty. ```swift guard !config.accountId?.isEmpty ?? false else { print("ERROR: Account ID is required") return } guard !config.policyKey?.isEmpty ?? false else { print("ERROR: Policy key is required") return } let googleCastManager = BCOVGoogleCastManager(forBrightcoveReceiverApp: config) ``` -------------------------------- ### Implement Google Cast Delegate Methods Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/README.md Implement optional delegate methods to handle callbacks for playback state changes, errors, and media information building. Use `useSourceFromSources` to select the appropriate video source and `shouldCastVideo` to control casting behavior. ```swift func switchedToLocalPlayback(_ pos: TimeInterval, withError error: Error?) func switchedToRemotePlayback() func currentCastedVideoDidComplete() func castedVideoFailedToPlay() func suitableSourceNotFound() func willBuildMediaInformationBuilder(_ builder: GCKMediaInformationBuilder) func willSendMediaLoadOptions(_ mediaLoadOptions: GCKMediaLoadOptions) func useSourceFromSources(_ sources: [BCOVSource]) -> BCOVSource func shouldCastVideo(_ video: BCOVVideo) -> Bool ``` -------------------------------- ### Create Google Cast Manager Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/module-overview.md Instantiate the BCOVGoogleCastManager. Use the default initializer or provide a specific Brightcove receiver app ID. ```swift BCOVGoogleCastManager() ``` ```swift BCOVGoogleCastManager(forBrightcoveReceiverApp:) ``` -------------------------------- ### Initialize BCOVGoogleCastManager with Configuration Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/integration-guide.md Pass the BCOVReceiverAppConfig to the BCOVGoogleCastManager for correct receiver app functionality. The wrong initialization will result in receiver app features not being available. ```swift // Correct: configuration is passed let googleCastManager = BCOVGoogleCastManager(forBrightcoveReceiverApp: config) // Wrong: receiver app features not available let googleCastManager = BCOVGoogleCastManager() ``` -------------------------------- ### BCOVReceiverAppConfig Initializer Source: https://github.com/brightcove/brightcove-player-sdk-ios-googlecast/blob/master/_autodocs/api-reference-receiver-config.md Initializes a new BCOVReceiverAppConfig object with default nil values. Properties must be set individually. ```APIDOC ## Initializer: Default ### Signature ```swift init() ``` ### Description Creates a new, empty instance of `BCOVReceiverAppConfig` with all properties initialized to `nil`. All properties must be set individually as needed. ### Return Type `BCOVReceiverAppConfig` — An uninitialized configuration object ### Example ```swift let config = BCOVReceiverAppConfig() config.accountId = "4337717568001" config.policyKey = "BCpk7DFtVLzWrWVT..." ``` ```