|
| 1 | +import AVFoundation |
| 2 | +import Foundation |
| 3 | +import Network |
| 4 | +import PocketCastsDataModel |
| 5 | +import PocketCastsUtils |
| 6 | + |
| 7 | +/// Tracks network data usage for AVPlayer streaming by monitoring network path changes |
| 8 | +/// and querying AVPlayerItem access logs for bytes transferred. |
| 9 | +/// |
| 10 | +/// This is used for direct AVPlayer streaming (when not using MediaExporterResourceLoaderDelegate). |
| 11 | +/// For cached streaming, network tracking is handled by MediaExporterResourceLoaderDelegate's |
| 12 | +/// URLSessionTaskMetrics. |
| 13 | +#if !os(watchOS) |
| 14 | +class StreamingCellularTracker { |
| 15 | + private let monitor = NWPathMonitor() |
| 16 | + private let monitorQueue = DispatchQueue(label: "com.pocketcasts.StreamingCellularTracker") |
| 17 | + |
| 18 | + private weak var playerItem: AVPlayerItem? |
| 19 | + private var episodeUuid: String? |
| 20 | + private var podcastUuid: String? |
| 21 | + |
| 22 | + private var currentConnectionType: CellularDataUsageManager.ConnectionType? |
| 23 | + private var bytesWhenConnectionStarted: Int64 = 0 |
| 24 | + private var lastReportedBytes: Int64 = 0 |
| 25 | + |
| 26 | + private var accessLogObserver: NSObjectProtocol? |
| 27 | + |
| 28 | + init() {} |
| 29 | + |
| 30 | + deinit { |
| 31 | + stopTracking() |
| 32 | + } |
| 33 | + |
| 34 | + /// Start tracking network usage for a player item |
| 35 | + func startTracking(playerItem: AVPlayerItem, episodeUuid: String?, podcastUuid: String?) { |
| 36 | + stopTracking() |
| 37 | + |
| 38 | + self.playerItem = playerItem |
| 39 | + self.episodeUuid = episodeUuid |
| 40 | + self.podcastUuid = podcastUuid |
| 41 | + self.lastReportedBytes = 0 |
| 42 | + self.bytesWhenConnectionStarted = 0 |
| 43 | + self.currentConnectionType = nil |
| 44 | + |
| 45 | + monitor.pathUpdateHandler = { [weak self] path in |
| 46 | + self?.handlePathUpdate(path) |
| 47 | + } |
| 48 | + monitor.start(queue: monitorQueue) |
| 49 | + |
| 50 | + // Observe access log changes to track bytes as they're downloaded |
| 51 | + accessLogObserver = NotificationCenter.default.addObserver( |
| 52 | + forName: .AVPlayerItemNewAccessLogEntry, |
| 53 | + object: playerItem, |
| 54 | + queue: nil |
| 55 | + ) { [weak self] _ in |
| 56 | + self?.checkAndReportConnectionUsage() |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + /// Stop tracking and report final network usage |
| 61 | + func stopTracking() { |
| 62 | + reportCurrentConnectionUsageIfNeeded() |
| 63 | + |
| 64 | + monitor.cancel() |
| 65 | + |
| 66 | + if let observer = accessLogObserver { |
| 67 | + NotificationCenter.default.removeObserver(observer) |
| 68 | + accessLogObserver = nil |
| 69 | + } |
| 70 | + |
| 71 | + playerItem = nil |
| 72 | + episodeUuid = nil |
| 73 | + podcastUuid = nil |
| 74 | + currentConnectionType = nil |
| 75 | + bytesWhenConnectionStarted = 0 |
| 76 | + lastReportedBytes = 0 |
| 77 | + } |
| 78 | + |
| 79 | + // MARK: - Private |
| 80 | + |
| 81 | + private func handlePathUpdate(_ path: NWPath) { |
| 82 | + let previousConnectionType = currentConnectionType |
| 83 | + let nextConnectionType: CellularDataUsageManager.ConnectionType? = { |
| 84 | + if path.usesInterfaceType(.cellular) { |
| 85 | + return .cellular |
| 86 | + } |
| 87 | + |
| 88 | + if path.usesInterfaceType(.wifi) { |
| 89 | + return .wifi |
| 90 | + } |
| 91 | + |
| 92 | + return nil |
| 93 | + }() |
| 94 | + |
| 95 | + guard previousConnectionType != nextConnectionType else { |
| 96 | + return |
| 97 | + } |
| 98 | + |
| 99 | + reportCurrentConnectionUsageIfNeeded() |
| 100 | + |
| 101 | + currentConnectionType = nextConnectionType |
| 102 | + bytesWhenConnectionStarted = currentBytesTransferred() |
| 103 | + lastReportedBytes = 0 |
| 104 | + |
| 105 | + let connectionLabel = nextConnectionType?.displayName ?? "none" |
| 106 | + FileLog.shared.addMessage("StreamingCellularTracker: Switched connection type to \(connectionLabel), starting bytes: \(bytesWhenConnectionStarted)") |
| 107 | + } |
| 108 | + |
| 109 | + private func checkAndReportConnectionUsage() { |
| 110 | + guard currentConnectionType != nil else { return } |
| 111 | + |
| 112 | + let currentBytes = currentBytesTransferred() |
| 113 | + let bytesOnConnection = currentBytes - bytesWhenConnectionStarted |
| 114 | + |
| 115 | + let bytesThreshold: Int64 = 100 * 1024 |
| 116 | + if bytesOnConnection - lastReportedBytes >= bytesThreshold { |
| 117 | + let bytesToReport = bytesOnConnection - lastReportedBytes |
| 118 | + reportConnectionBytes(bytesToReport) |
| 119 | + lastReportedBytes = bytesOnConnection |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + private func reportCurrentConnectionUsageIfNeeded() { |
| 124 | + guard currentConnectionType != nil else { return } |
| 125 | + |
| 126 | + let currentBytes = currentBytesTransferred() |
| 127 | + let bytesOnConnection = currentBytes - bytesWhenConnectionStarted |
| 128 | + let unreportedBytes = bytesOnConnection - lastReportedBytes |
| 129 | + |
| 130 | + if unreportedBytes > 0 { |
| 131 | + reportConnectionBytes(unreportedBytes) |
| 132 | + lastReportedBytes = bytesOnConnection |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + private func reportConnectionBytes(_ bytes: Int64) { |
| 137 | + guard bytes > 0, let connectionType = currentConnectionType else { return } |
| 138 | + |
| 139 | + FileLog.shared.addMessage("StreamingCellularTracker: Reporting \(bytes) bytes of \(connectionType.displayName) streaming for episode: \(episodeUuid ?? "unknown")") |
| 140 | + |
| 141 | + DataManager.sharedManager.cellularDataUsageManager.add( |
| 142 | + episodeUuid: episodeUuid, |
| 143 | + podcastUuid: podcastUuid, |
| 144 | + bytesStreamed: bytes, |
| 145 | + operationType: .stream, |
| 146 | + connectionType: connectionType, |
| 147 | + sessionType: .foreground |
| 148 | + ) |
| 149 | + } |
| 150 | + |
| 151 | + private func currentBytesTransferred() -> Int64 { |
| 152 | + guard let accessLog = playerItem?.accessLog(), |
| 153 | + let lastEvent = accessLog.events.last else { |
| 154 | + return 0 |
| 155 | + } |
| 156 | + return lastEvent.numberOfBytesTransferred |
| 157 | + } |
| 158 | +} |
| 159 | + |
| 160 | +private extension CellularDataUsageManager.ConnectionType { |
| 161 | + var displayName: String { |
| 162 | + switch self { |
| 163 | + case .unknown: |
| 164 | + return "unknown" |
| 165 | + case .wifi: |
| 166 | + return "wifi" |
| 167 | + case .cellular: |
| 168 | + return "cellular" |
| 169 | + } |
| 170 | + } |
| 171 | +} |
| 172 | +#endif |
0 commit comments