diff --git a/apple/Common/AV.swift b/apple/Common/AV.swift new file mode 100644 index 0000000..936e82d --- /dev/null +++ b/apple/Common/AV.swift @@ -0,0 +1,372 @@ + +import AVFoundation + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Queue +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +func assert_audio_capture_queue() { + assert(DispatchQueue.OnQueue(AV.shared.audioCaptureQueue)) +} + +func assert_video_capture_queue() { + assert(DispatchQueue.OnQueue(AV.shared.videoCaptureQueue)) +} + +func assert_av_output_queue() { + assert(DispatchQueue.OnQueue(AV.shared.avOutputQueue)) +} + +func dispatch_sync_av_output(_ block: FuncVV) { + if DispatchQueue.OnQueue(AV.shared.avOutputQueue) { + block() + } + else { + AV.shared.avOutputQueue.sync { block() } + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// AV +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class AV { + + static let shared = AV() + static let defaultAudioFormatID = kAudioFormatMPEG4AAC + static let defaultAudioInterval = 0.1 + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // IO + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + let audioCaptureQueue = DispatchQueue.CreateCheckable("chat.AudioCaptureQueue") + let videoCaptureQueue = DispatchQueue.CreateCheckable("chat.VideoCaptureQueue") + let avOutputQueue = DispatchQueue.CreateCheckable("chat.AVOutputQueue") + + init() { + defaultVideoDimension = defaultVideoInputDevice?.activeFormat.dimensions + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Input + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + var defaultVideoInputDevice: AVCaptureDevice? { + return AVCaptureDevice.chatVideoDevice() + } + + var defaultVideoDimension: CMVideoDimensions? + + var defaultVideoInputFormat: AVCaptureDeviceFormat? { + get { + guard let dimensions = defaultVideoDimension else { return nil } + return defaultVideoInputDevice?.inputFormat(width: dimensions.width) + } + } + + var defaultAudioInputFormat: AudioStreamBasicDescription? { + guard let inputFormat = AVAudioEngine().inputNode?.inputFormat(forBus: AudioBus.input) else { return nil } + + return AudioStreamBasicDescription.CreateVBR(AV.defaultAudioFormatID, + inputFormat.sampleRate/*8000*/, + 1/*inputFormat.channelCount*/) + } + + private func _defaultNetworkVideoInput(_ id: IOID, + _ context: IOInputContext, + _ rotated: Bool, + _ info: inout NetworkVideoSessionInfo?, + _ session: inout AVCaptureSession.Accessor?, + _ x: inout [VideoSessionProtocol]) { + guard let device = AVCaptureDevice.chatVideoDevice() else { return } + guard var outFormat = defaultVideoOutputFormat else { return } + guard let inpFormat = defaultVideoInputFormat else { return } + + if rotated { + outFormat.rotate() + } + + let serializer = + NetworkH264Serializer( + NetworkOutputVideo(id, context.qos, context.balancer)) + + let sessionEncoder = + VideoEncoderSessionH264( + inpFormat.dimensions, + outFormat, + serializer) + + let videoInput = + VideoInput( + device, + AV.shared.videoCaptureQueue, + inpFormat, + sessionEncoder) + + let videoInputQoS + = VideoInputQoS(inpFormat, + VideoSessionBroadcast([videoInput, sessionEncoder])) + + let qos = + IOQoSDispatcher( + videoCaptureQueue, + IOQoSBroadcast([videoInputQoS, serializer])) + + context.qos.add(qos) + info = NetworkVideoSessionInfo(id, factory(outFormat)) + session = videoInput.sessionAccessor + x.append(VideoSessionBroadcast([sessionEncoder, videoInput])) + } + + func defaultNetworkVideoInput(_ id: IOID, + _ context: IOInputContext, + _ rotated: Bool, + _ info: inout NetworkVideoSessionInfo?, + _ session: inout AVCaptureSession.Accessor?) -> VideoSessionProtocol? { + var x = [VideoSessionProtocol]() + + _defaultNetworkVideoInput(id, context, rotated, &info, &session, &x) + return broadcast(x) + } + + func defaultNetworkVideoInput(_ id: IOID, + _ context: IOInputContext, + _ preview: AVCaptureVideoPreviewLayer, + _ info: inout NetworkVideoSessionInfo?) -> VideoSessionProtocol? { + var x = [VideoSessionProtocol]() + var y: AVCaptureSession.Accessor? + + _defaultNetworkVideoInput(id, context, false, &info, &y, &x) + + if y != nil { + x.append(VideoPreview(preview, y!)) + } + + return broadcast(x) + } + + private func _defaultNetworkAudioInput(_ id: IOID, + _ context: IOInputContext, + _ x: inout [IOSessionProtocol], + _ formatOut: inout AudioFormat.Factory?) { + + guard let format = defaultAudioInputFormat else { return } + + let serializer = + NetworkAudioSerializer( + NetworkOutputAudio(id, context.qos, context.balancer)) + + let input = + AudioInput( + format, + AV.defaultAudioInterval, + serializer) + + x.append( + IOSessionSyncDispatcher( + audioCaptureQueue, + input)) + + let qos = + IOQoSDispatcher( + audioCaptureQueue, + serializer) + + context.qos.add(qos) + formatOut = input.format + } + + func defaultNetworkAudioInput(_ id: IOID, + _ context: IOInputContext, + _ info: inout NetworkAudioSessionInfo?) -> IOSessionProtocol? { + var x = [IOSessionProtocol]() + var format: AudioFormat.Factory? + + _defaultNetworkAudioInput(id, context, &x, &format) + + if format != nil { + info = NetworkAudioSessionInfo(id, format!) + } + return broadcast(x) + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Output + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + var defaultVideoOutputFormat: VideoFormat? { + get { + guard let format = defaultVideoInputFormat else { return nil } + return VideoFormat(format) + } + } + + func defaultNetworkVideoOutput(_ id: IOID, + _ context: IOOutputContext, + _ output: VideoOutputProtocol, + _ session: IOSessionProtocol? = nil) -> IOOutputContext { + + let time = + VideoTimeSerializer(NetworkDeserializer.timeIndex) + + let balancedOutput = + IOBalancedDataSession( + NetworkH264Deserializer( +// VideoDecoderH264( + output)) + + let sheduler = + IOSheduler( + IOKind.Video, + balancedOutput) + + let balancer = + IODataAdapter4Balancer( + time, + context.balancer!, + sheduler) + + let resultSession = + IODataSession( + IOTimebaseReset( + context.timebase!, + time, + balancer)) + + let result = + IODataAsyncDispatcher( + avOutputQueue, + resultSession) + + return IOOutputContext(id, + broadcast([sheduler, resultSession, balancedOutput, session])!, + result, + context) + } + + func defaultNetworkVideoOutput(_ id: IOID, + _ context: IOOutputContext, + _ layer: AVSampleBufferDisplayLayer, + _ session: IOSessionProtocol? = nil) -> IOOutputContext { + let output = VideoOutput(layer) + + return AV.shared.defaultNetworkVideoOutput(id, + context, + output, + output) + } + + func defaultNetworkAudioOutput(_ id: IOID, + _ format: AudioFormat, + _ context: IOOutputContext, + _ session: IOSessionProtocol? = nil) -> IOOutputContext { + let time = + AudioTimeUpdater(NetworkDeserializer.timeIndex) + + let output = + AudioOutput( + factory(format), + avOutputQueue) + + let decoder = + AudioDecoder( + factory(format), + output.format, + output) + + let balancedOutput = + IOBalancedDataSession( + IOBalanceSubdataSkip( + NetworkAudioDeserializer( + decoder))) + + let sheduler = + IOSheduler( + IOKind.Audio, + balancedOutput) + + let balancer = + IODataAdapter4Balancer( + time, + context.balancer!, + sheduler) + + let resultSession = + IODataSession( + IOTimebaseReset( + context.timebase!, + time, + balancer)) + + let result = + IODataAsyncDispatcher( + avOutputQueue, + resultSession) + + return IOOutputContext(id, + broadcast([sheduler, resultSession, output, balancedOutput, decoder, session])!, + result, + context) + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Playback + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + var defaultAudioInputUncompressedFormat: AudioStreamBasicDescription? { + guard let inputFormat = AVAudioEngine().inputNode?.inputFormat(forBus: AudioBus.input) else { return nil } + var format = inputFormat.streamDescription.pointee + + format.mChannelsPerFrame = 1 + return format + } + + func audioUncompressedPlayback() throws -> IOSessionProtocol? { + guard let format = defaultAudioInputUncompressedFormat else { return nil } + + let input = + AudioInput( + format, + AV.defaultAudioInterval) + + let output = + AudioOutput( + input.format, + AV.shared.audioCaptureQueue) + + input.output = + NetworkAudioSerializer( + NetworkAudioDeserializer( + output)) + + return broadcast([output, input]) + } + + func audioCompressedPlayback() throws -> IOSessionProtocol? { + guard let format = defaultAudioInputFormat else { return nil } + + let input = + AudioInput( + format, + AV.defaultAudioInterval) + + let output = + AudioOutput( + input.format, + AV.shared.audioCaptureQueue) + + let decoder = + AudioDecoder( + input.format, + output.format, + output) + + input.output = + NetworkAudioSerializer( + NetworkAudioDeserializer( + decoder)) + + return broadcast([input, output, decoder]) + } +} diff --git a/apple/Common/Application.swift b/apple/Common/Application.swift new file mode 100644 index 0000000..5e047f8 --- /dev/null +++ b/apple/Common/Application.swift @@ -0,0 +1,69 @@ + +import Foundation +import CoreMedia +import Fabric +import Crashlytics + +class Application : AppleApplicationDelegate { + + static let kCompressedPlayback = false + static let kUncompressedPlayback = false + + static let kServerIP = "kServerIP" + static let kVideoWidth = "kVideoWidth" + static let kVideoHeight = "kVideoHeight" + + var playback: IOSessionProtocol? + + override init() { + + // start time + + _ = HostTimeInfo.shared + + // crash on unhandled exceptions + + UserDefaults.standard.register(defaults: ["NSApplicationCrashOnExceptions": true]); + + // fabric + + Fabric.with([Crashlytics.self]) + + // server IP + + let serverIP = UserDefaults.standard.string(forKey: Application.kServerIP) + + if (serverIP != nil) { + Backend.address = serverIP! + } + + // video dimension + + let videoWidth = UserDefaults.standard.string(forKey: Application.kVideoWidth) + let videoHeight = UserDefaults.standard.string(forKey: Application.kVideoHeight) + + if videoWidth != nil && videoHeight != nil { + AV.shared.defaultVideoDimension = CMVideoDimensions(width: Int32(videoWidth!)!, + height: Int32(videoHeight!)!) + } + + // playback testing + + var playback: IOSessionProtocol? + + checkIO { + + if Application.kCompressedPlayback { + playback = try AV.shared.audioCompressedPlayback() + } + + if Application.kUncompressedPlayback { + playback = try AV.shared.audioUncompressedPlayback() + } + + try playback?.start() + } + + self.playback = playback + } +} diff --git a/apple/Common/Backend.swift b/apple/Common/Backend.swift new file mode 100644 index 0000000..17a7743 --- /dev/null +++ b/apple/Common/Backend.swift @@ -0,0 +1,482 @@ +import Foundation +import Starscream + +class Backend: WebSocketDelegate { + + static var address = "107.170.4.248" + static let shared = Backend() + + private var audio = NetworkInput() + private var video = NetworkInput() + + private var websocket: WebSocket? + private var sessionId: String? + + func connect(withUsername: String) { + guard let url = URL(string: "ws://\(Backend.address):8000/ws") else { + logNetworkError("could not create url from " + Backend.address) + return + } + self.websocket = WebSocket(url: url) + Model.shared.username = withUsername + websocket?.delegate = self + websocket?.callbackQueue = DispatchQueue(label: "chat.Websocket") + websocket?.connect() + } + + var videoSessionStart: ((NetworkVideoSessionInfo) throws ->IODataProtocol?)? + var videoSessionStop: ((IOID)->Void)? + + var audioSessionStart: ((NetworkAudioSessionInfo) throws ->IODataProtocol?)? + var audioSessionStop: ((IOID)->Void)? + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Send + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + func send(_ haberBuilder:Haber.Builder, _ details: String? = nil, _ completion: FuncVV? = nil) { + guard let haber = try? haberBuilder.setSessionId(self.sessionId ?? "").build() else { + logNetworkError("could not create haber") + return + } + + switch haber.which { + case .av: + logNetwork("write \(haber.data().count) bytes for \(haber.which) \(details != nil ? details! : "")") + default: + logNetworkPrior("write \(haber.data().count) bytes for \(haber.which) \(details != nil ? details! : "")") + } + + self.websocket?.write(data: haber.data()) { + completion?() + } + } + + func sendText(_ body: String, to: String) { + guard let update = try? Text.Builder().setBody(body).build() else { + logNetworkError("could not create Text") + return + } + let haberBuilder = Haber.Builder().setText(update).setWhich(.text).setTo(to) + self.send(haberBuilder) + } + + func sendContacts(_ contacts: [String:Contact]) { + let haberBuilder = Haber.Builder().setContacts(Array(contacts.values)).setWhich(.contacts) + Backend.shared.send(haberBuilder) + } + + func sendCallProposal(_ to: String, _ info: NetworkCallProposalInfo) { + send(try! Haber.Create(.callProposal, to, info)) + } + + func sendCallCancel(_ to: String, _ info: NetworkCallProposalInfo) { + send(try! Haber.Create(.callCancel, to, info)) + } + + func sendCallAccept(_ to: String, _ info: NetworkCallProposalInfo) { + send(try! Haber.Create(.callAccept, to, info)) + } + + func sendCallDecline(_ to: String, _ info: NetworkCallProposalInfo) { + send(try! Haber.Create(.callDecline, to, info)) + } + + func sendOutgoingCallStart(_ to: String, _ info: NetworkCallInfo) { + send(try! Haber.Create(.callStartOutgoing, to, info)) + } + + func sendIncomingCallStart(_ to: String, _ info: NetworkCallInfo) { + send(try! Haber.Create(.callStartIncoming, to, info)) + } + + func sendCallChangeQuality(_ to: String, _ info: NetworkCallInfo, _ diff: Int32) { + send(try! Haber.CreateQuality(to, info, diff)) + } + + func sendCallStop(_ to: String, _ info: NetworkCallInfo) { + send(try! Haber.Create(.callStop, to, info)) + } + + func sendVideoSession(_ session: NetworkVideoSessionInfo, _ active: Bool) { + send(try! Haber.Create(.videoSession, session, active).setWhich(.videoSession)) + } + + func sendAudioSession(_ session: NetworkAudioSessionInfo, _ active: Bool) { + send(try! Haber.Create(.audioSession, session, active).setWhich(.audioSession)) + } + + func sendVideo(_ id: IOID, _ data: NSData, _ callback: @escaping FuncVV) { + + assert_video_capture_queue() + + do { + let image = try Image.Builder().setData(data as Data).build() + let media = try VideoSample.Builder().setImage(image).build() + let av = try Av.Builder().setVideo(media).build() + + let haberBuilder = Haber.Builder() + .setTo(id.to) + .setWhich(.av) + .setAv(av) + .setVideoSession(try Avsession.Builder().setSid(id.sid).build()) + + Backend.shared.send(haberBuilder, "video", callback) + } + catch { + logNetworkError(error) + } + } + + func sendAudio(_ id: IOID, _ data: NSData, _ callback: @escaping FuncVV) { + + assert_audio_capture_queue() + + do { + let image = try Image.Builder().setData(data as Data).build() + let media = try AudioSample.Builder().setImage(image).build() + let av = try Av.Builder().setAudio(media).build() + + let haberBuilder = Haber.Builder() + .setTo(id.to) + .setWhich(.av) + .setAv(av) + .setAudioSession(try Avsession.Builder().setSid(id.sid).build()) + + Backend.shared.send(haberBuilder, "audio", callback) + } + catch { + logNetworkError(error) + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Receive + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + func getsCallProposal(_ haber: Haber) { + NetworkCallProposalController.incoming?.start(haber.callProposalInfo) + } + + func getsCallCancel(_ haber: Haber) { + NetworkCallProposalController.incoming?.stop(haber.callProposalInfo) + NetworkCallProposalController.outgoing?.stop(haber.callProposalInfo) + } + + func getsCallAccept(_ haber: Haber) { + NetworkCallProposalController.outgoing?.accept(haber.callProposalInfo) + } + + func getsCallDecline(_ haber: Haber) { + NetworkCallProposalController.outgoing?.decline(haber.callProposalInfo) + } + + func getsOutgoingCallStart(_ haber: Haber) { + NetworkCallController.incoming?.start(try! haber.callInfo()) + startCallOutput(haber, NetworkCallController.incoming, audio, video) + } + + func getsIncomingCallStart(_ haber: Haber) { + startCallOutput(haber, NetworkCallController.outgoing, audio, video) + } + + func getsCallQuality(_ haber: Haber) { + changeCallQuality(try! haber.callInfo(), Int(haber.avQuality.diff)) + } + + func getsCallStop(_ haber: Haber) { + NetworkCallController.incoming?.stop(try! haber.callInfo()) + NetworkCallController.outgoing?.stop(try! haber.callInfo()) + + if haber.hasAudioSession { + audio.remove(haber.audioSession.sid) + } + + if haber.hasVideoSession { + video.remove(haber.videoSession.sid) + } + } + + func getsAV(_ haber: Haber) { + if (haber.av.hasAudio) { + audio.process(haber.audioSession.sid, haber.av.audio.image.data as NSData) + } + + if (haber.av.hasVideo) { + video.process(haber.videoSession.sid, haber.av.video.image.data as NSData) + } + } + + func getsVideoSession(_ haber: Haber) { + do { + if haber.videoSession.hasActive && haber.videoSession.active { + video.removeAll() + + try dispatch_sync_on_main { + guard let output = try videoSessionStart?(try haber.videoSessionInfo()!) else { return } + video.add(haber.videoSession.sid, output) + } + } + else { + videoSessionStop?(haber.videoSessionID!) + video.remove(haber.videoSession.sid) + } + } + catch { + logNetworkError(error) + } + } + + func getsAudioSession(_ haber: Haber) { + do { + if haber.audioSession.hasActive && haber.audioSession.active { + audio.removeAll() + + try dispatch_sync_on_main { + guard let output = try audioSessionStart?(try haber.audioSessionInfo()!) else { return } + audio.add(haber.audioSession.sid, output) + } + } + else { + audioSessionStop?(haber.audioSessionID!) + audio.remove(haber.audioSession.sid) + } + } + catch { + logNetworkError(error) + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // websocket delegate + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + public func websocketDidConnect(_ websocket: Starscream.WebSocket) { + if let username = Model.shared.username { + do { + let login = try Login.Builder().setUsername(username).build() + let haberBuilder = Haber.Builder().setLogin(login).setWhich(.login) + self.send(haberBuilder) + } catch { + print(error.localizedDescription) + } + } + } + + public func websocketDidDisconnect(_ websocket: Starscream.WebSocket, error: NSError?) { + logNetwork("disconnected") + } + + public func websocketDidReceiveMessage(_ websocket: Starscream.WebSocket, text: String) { + logNetwork("websocketDidReceiveMessage") + } + + public func websocketDidReceiveData(_ websocket: Starscream.WebSocket, data: Data) { + guard let haber = try? Haber.parseFrom(data:data) else { + logNetworkError("Could not deserialize") + return + } + + if haber.hasSessionId { + self.sessionId = haber.sessionId + } + + switch haber.which { + case .av: + logNetwork("read \(data.count) bytes for \(haber.which)") + default: + logNetworkPrior("read \(data.count) bytes for \(haber.which)") + } + + switch haber.which { + case .contacts: + dispatch_sync_on_main { Model.shared.didReceiveRoster(haber.contacts) } + case .text: + dispatch_sync_on_main { Model.shared.didReceiveText(haber) } + case .presence: + dispatch_sync_on_main { Model.shared.didReceivePresence(haber) } + case .av: + getsAV(haber) + case .audioSession: + getsAudioSession(haber) + case .videoSession: + getsVideoSession(haber) + case .callProposal: + dispatch_async_network_call { self.getsCallProposal(haber) } + case .callCancel: + dispatch_async_network_call { self.getsCallCancel(haber) } + case .callAccept: + dispatch_async_network_call { self.getsCallAccept(haber) } + case .callDecline: + dispatch_async_network_call { self.getsCallDecline(haber) } + case .callStartOutgoing: + dispatch_async_network_call { self.getsOutgoingCallStart(haber) } + case .callStartIncoming: + dispatch_async_network_call { self.getsIncomingCallStart(haber) } + case .callQuality: + dispatch_async_network_call { self.getsCallQuality(haber) } + case .callStop: + dispatch_async_network_call { self.getsCallStop(haber) } + default: + logNetworkError("did not handle \(haber.which)") + } + } +} + +extension Haber.Builder { + + func Fill(_ call: NetworkCallProposalInfo) throws -> Haber.Builder { + return setCall(try Call.Builder() + .setKey(call.id) + .setFrom(call.from) + .setTo(call.to) + .setAudio(call.audio) + .setVideo(call.video).build()) + } + + func Fill(_ session: NetworkAudioSessionInfo?, _ active: Bool) throws -> Haber.Builder { + guard session != nil else { return self } + return setAudioSession(try Avsession.Create(session, active)) + } + + func Fill(_ session: NetworkVideoSessionInfo?, _ active: Bool) throws -> Haber.Builder { + guard session != nil else { return self } + return setVideoSession(try Avsession.Create(session, active)) + } + + func FillQuality(_ diff: Int32) throws -> Haber.Builder { + setAvQuality(try Avquality.Builder() + .setDiff(diff).build()) + + return self + } +} + +extension Avsession { + static func Create(_ session_: NetworkIOSessionInfo?, _ active: Bool) throws -> Avsession? { + guard let session = session_ else { return nil } + + let sessionBuilder = Avsession.Builder() + .setSid(session.id.sid) + .setGid(session.id.gid) + .setActive(active) + + if session.formatData != nil { + sessionBuilder.setData(try session.formatData!() as Data) + } + + return try sessionBuilder.build() + } +} + +extension Haber { + + static func Create(_ which: Haber.Which, + _ data: NetworkAudioSessionInfo, + _ active: Bool) throws -> Haber.Builder { + return try Haber.Builder() + .setWhich(which) + .setTo(data.id.to) + .setFrom(data.id.from) + .Fill(data, active) + } + + static func Create(_ which: Haber.Which, + _ data: NetworkVideoSessionInfo, + _ active: Bool) throws -> Haber.Builder { + return try Haber.Builder() + .setWhich(which) + .setTo(data.id.to) + .setFrom(data.id.from) + .Fill(data, active) + } + + static func Create(_ which: Haber.Which, + _ to: String, + _ data: NetworkCallProposalInfo) throws -> Haber.Builder { + + return try Haber.Builder() + .setWhich(which) + .setTo(to) + .setFrom(Model.shared.username!) + .Fill(data) + } + + static func Create(_ which: Haber.Which, + _ to: String, + _ data: NetworkCallInfo) throws -> Haber.Builder { + return try Haber.Builder() + .setWhich(which) + .setTo(to) + .setFrom(Model.shared.username!) + .Fill(data.proposal) + .Fill(data.audioSession, true) + .Fill(data.videoSession, true) + } + + static func CreateQuality(_ to: String, + _ call: NetworkCallInfo, + _ diff: Int32) throws -> Haber.Builder { + return try Create(.callQuality, to, call).FillQuality(diff) + } + + var audioSessionID: IOID? { + get { + guard hasAudioSession else { return nil } + return IOID(from, to, audioSession.sid, audioSession.gid) + } + } + + var videoSessionID: IOID? { + get { + guard hasVideoSession else { return nil } + return IOID(from, to, videoSession.sid, videoSession.gid) + } + } + + func audioSessionInfo() throws -> NetworkAudioSessionInfo? { + guard hasAudioSession else { return nil } + return NetworkAudioSessionInfo(audioSessionID!, + audioSession.hasData ? factory(audioSession.data as NSData) : nil) + } + + func videoSessionInfo() throws -> NetworkVideoSessionInfo? { + guard hasVideoSession else { return nil } + return NetworkVideoSessionInfo(videoSessionID!, + videoSession.hasData ? factory(videoSession.data as NSData) : nil) + } + + func callInfo() throws -> NetworkCallInfo { + return NetworkCallInfo(callProposalInfo, try audioSessionInfo(), try videoSessionInfo()) + } + + var callProposalInfo: NetworkCallProposalInfo { + get { + return NetworkCallProposalInfo(self.call.key, + self.call.from, + self.call.to, + self.call.hasAudio ? self.call.audio : false, + self.call.hasVideo ? self.call.video : false) + } + } +} + +func startCallOutput(_ haber: Haber, _ call: NetworkCallController?, _ audio: NetworkInput, _ video: NetworkInput) { + var audio_: IODataProtocol? + var video_: IODataProtocol? + + do { + try call?.startOutput(try! haber.callInfo(), &audio_, &video_) + } + catch { + logNetworkError(error) + } + + if audio_ != nil { + audio.add(haber.audioSession.sid, audio_!) + } + + if video_ != nil { + video.add(haber.videoSession.sid, video_!) + } +} diff --git a/apple/Common/IO/Audio.swift b/apple/Common/IO/Audio.swift new file mode 100644 index 0000000..a860abc --- /dev/null +++ b/apple/Common/IO/Audio.swift @@ -0,0 +1,235 @@ + +import AVFoundation +import AudioToolbox + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Simple types +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +protocol AudioOutputProtocol { + + func process(_ data: AudioData) +} + +struct AudioBus { + static let input = 0 + static let output = 1 +} + +struct AudioData { + let time: AudioTimeStamp! + let data: NSData! + let desc: [AudioStreamPacketDescription]? + + init(_ time: AudioTimeStamp, + _ data: NSData, + _ desc: [AudioStreamPacketDescription]?) { + self.time = time + self.data = data + self.desc = desc + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// AudioFormat +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +struct AudioFormat { + + typealias Factory = () throws -> AudioFormat + + private static let kFormatID = "kFormatID" + private static let kFlags = "kFlags" + private static let kSampleRate = "kSampleRate" + private static let kChannelCount = "kChannelCount" + private static let kFramesPerPacket = "kFramesPerPacket" + + private(set) var format: IOFormat + + init(_ x: AudioStreamBasicDescription) { + format = IOFormat() + + self.formatID = x.mFormatID + self.flags = x.mFormatFlags + self.sampleRate = x.mSampleRate + self.channelCount = x.mChannelsPerFrame + self.framesPerPacket = x.mFramesPerPacket + } + + init(_ format: IOFormat) { + self.format = format + } + + var formatID: UInt32 { + get { + return format.data.keys.contains(AudioFormat.kFormatID) ? format.data[AudioFormat.kFormatID] as! UInt32 : 0 + } + set { + format.data[AudioFormat.kFormatID] = newValue + } + } + + var flags: UInt32 { + get { + return format.data.keys.contains(AudioFormat.kFlags) ? format.data[AudioFormat.kFlags] as! UInt32 : 0 + } + set { + format.data[AudioFormat.kFlags] = newValue + } + } + + var sampleRate: Double { + get { + return format.data.keys.contains(AudioFormat.kSampleRate) + ? format.data[AudioFormat.kSampleRate] as! Double + : 0 + } + set { + format.data[AudioFormat.kSampleRate] = newValue + } + } + + var channelCount: UInt32 { + get { + return format.data.keys.contains(AudioFormat.kChannelCount) ? format.data[AudioFormat.kChannelCount] as! UInt32 : 0 + } + set { + format.data[AudioFormat.kChannelCount] = newValue + } + } + + var framesPerPacket: UInt32 { + get { + return format.data.keys.contains(AudioFormat.kFramesPerPacket) ? + format.data[AudioFormat.kFramesPerPacket] as! UInt32 + : 0 + } + set { + format.data[AudioFormat.kFramesPerPacket] = newValue + } + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Time +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +struct AudioTime : IOTimeProtocol { + let time: IOTime + let sampleTime: Float64 + + init() { + time = IOTime() + sampleTime = 0 + } + + init(_ hostSeconds: Float64, _ sampleTime: Float64) { + self.time = IOTime(hostSeconds) + self.sampleTime = sampleTime + } + + func copy(time: IOTime) -> AudioTime { + return AudioTime(time.hostSeconds, sampleTime) + } +} + +extension AudioTime { + + init(_ x: AudioTimeStamp) { + self.init(x.seconds(), x.mSampleTime) + } + + func ToAudioTimeStamp() -> AudioTimeStamp { + var result = AudioTimeStamp() + + result.mHostTime = mach_absolute_time(seconds: time.hostSeconds) + result.mSampleTime = sampleTime + result.mFlags = AudioTimeStampFlags.sampleTimeValid.intersection(.hostTimeValid) + + return result + } +} + +extension AudioTime : InitProtocol {} +typealias AudioTimeUpdater = IOTimeUpdater + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Protocols adapters +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class AudioPipe : AudioOutputProtocol { + + var next: AudioOutputProtocol? + + func process(_ data: AudioData) { + next?.process(data) + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// AudioDataBuffer +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class AudioDataReader { + + var data = [AudioData]() + var capacity: Int + var current: AudioData? + var currentIndex: Int = 0 + + init(capacity: Int) { + self.capacity = capacity + } + + func push(_ data: AudioData) { + self.data.append(data) + + if self.data.count > capacity { + self.data.removeLast() + } + } + + private func popFirst() -> AudioData? { + let result = data.first + + if data.count != 0 { + data.removeFirst() + } + + return result + } + + func pop(_ count: Int, _ outData: UnsafeMutableRawPointer) { + + if current == nil { + current = popFirst() + currentIndex = 0 + } + + if current == nil { + memset(outData, 0, count) + return + } + + var countRead = min(count, Int(current!.data.length) - currentIndex) + var outIndex = 0 + + while current != nil && countRead > 0 { + memcpy(outData.advanced(by: outIndex), current?.data.bytes.advanced(by: currentIndex), countRead) + currentIndex += countRead + outIndex += countRead + + if currentIndex == Int(current!.data.length) { + current = popFirst() + currentIndex = 0 + } + + if current != nil { + countRead = min(count - outIndex, Int(current!.data.length) - currentIndex) + } + else { + memset(outData.advanced(by: outIndex), 0, count - outIndex) + } + } + } +} diff --git a/apple/Common/IO/AudioDecoder.swift b/apple/Common/IO/AudioDecoder.swift new file mode 100644 index 0000000..990fd44 --- /dev/null +++ b/apple/Common/IO/AudioDecoder.swift @@ -0,0 +1,159 @@ + +import AudioToolbox + +class AudioDecoder : AudioOutputProtocol, IOSessionProtocol { + + var input: AudioFormat.Factory + var output: AudioStreamBasicDescription.Factory + let next: AudioOutput? + + var converter: AudioConverterRef? + var inputDescription: AudioStreamBasicDescription? + var outputDescription: AudioStreamBasicDescription? + var asc: UInt8 = 0 + + var pcmDataSize: UInt32 = 0 + var pcmBufferList: AudioBufferList? + + init(_ input: @escaping AudioFormat.Factory, + _ output: @escaping AudioStreamBasicDescription.Factory, + _ next: AudioOutput?) { + self.input = input + self.output = output + self.next = next + } + + func start() throws { + guard var outputDescription = try self.output() else { return } + outputDescription.mChannelsPerFrame = 1 + + self.inputDescription = AudioStreamBasicDescription.CreateVBR(try self.input()) + self.outputDescription = outputDescription + + try checkStatus(AudioConverterNew(&inputDescription!, &outputDescription, &converter), + "decoder: AudioConverterNew") + } + + func stop() { + guard let converter = self.converter else { return } + + do { + try checkStatus(AudioConverterDispose(converter), + "AudioConverterDispose") + self.converter = nil + + if pcmBufferList != nil { + free(pcmBufferList!.mBuffers.mData) + pcmBufferList = nil + pcmDataSize = 0 + } + } + catch { + logIOError(error) + } + } + + func restart() { + do { + stop() + try start() + } + catch { + logIOError(error) + } + } + + func process(_ packet: AudioData) { + + guard let converter = self.converter else { return } + + // asc + + if (asc == 0 && packet.data.length == 2) { + logIO("asc size \(packet.data.length)") + memcpy(&asc, packet.data.bytes, 2); + return; + } + // adts + + else if (packet.data.length == 7 || packet.data.length == 9) { + logIO("adts size \(packet.data.length)") + return; + } + + var pcmPacketNum = inputDescription!.mFramesPerPacket * UInt32(packet.desc!.count) + let pcmDataSize = pcmPacketNum * outputDescription!.mBytesPerPacket + + _prepareBufferList(pcmDataSize) + + do { + var copy = packet + try checkStatus(AudioConverterFillComplexBuffer(converter, + decodeProc, + ©, + &pcmPacketNum, + &pcmBufferList!, + nil), + "AudioConverterFillComplexBuffer") + + next?.process(AudioData(packet.time, + NSData(bytes: pcmBufferList!.mBuffers.mData, length: Int(pcmDataSize)), + nil)) + } + catch { + logIOError(error) + restart() + } + } + + private let decodeProc: AudioConverterComplexInputDataProc = {( + converter: AudioConverterRef, + ioNumberDataPackets: UnsafeMutablePointer, + ioData: UnsafeMutablePointer, + outDataPacketDescription: UnsafeMutablePointer?>?, + userData: UnsafeMutableRawPointer?) -> OSStatus in + + let packet = UnsafePointer(OpaquePointer(userData!)) + + // data + + var bufferList = AudioBufferList() + + bufferList.mNumberBuffers = 1 + bufferList.mBuffers.mData = UnsafeMutableRawPointer(OpaquePointer(packet.pointee.data.bytes)) + bufferList.mBuffers.mDataByteSize = UInt32(packet.pointee.data.length) + bufferList.mBuffers.mNumberChannels = 1 + ioData.initialize(to: bufferList) + + // descriptions + + var desc = packet.pointee.desc + + desc?.withUnsafeMutableBufferPointer({ + (ptr: inout UnsafeMutableBufferPointer) -> Void in + outDataPacketDescription?.initialize(to: ptr.baseAddress!) + }) + + ioNumberDataPackets.pointee = UInt32(packet.pointee.desc!.count) + + return 0 + } + + private func _prepareBufferList(_ size: UInt32) { + if size <= pcmDataSize { + pcmBufferList!.mBuffers.mDataByteSize = size + return + } + + if pcmBufferList != nil { + free(pcmBufferList!.mBuffers.mData) + } + + let pcmBuffer = AudioBuffer(mNumberChannels: 1, + mDataByteSize: size, + mData: malloc(Int(size))) + pcmBufferList = AudioBufferList(mNumberBuffers: 1, + mBuffers: pcmBuffer) + pcmDataSize = size + } +} diff --git a/apple/Common/IO/AudioInput.swift b/apple/Common/IO/AudioInput.swift new file mode 100644 index 0000000..e518057 --- /dev/null +++ b/apple/Common/IO/AudioInput.swift @@ -0,0 +1,247 @@ + +import AudioToolbox +import AVFoundation + +class AudioInput : NSObject, IOSessionProtocol +{ + private static let kBuffersCount = 3 + + public var output: AudioOutputProtocol? + + private var queue: AudioQueueRef? + private var buffers = [AudioQueueBufferRef]() + private var stopping: Bool = false + + private var formatDescription: AudioStreamBasicDescription + private var formatChat: AudioFormat? + private let interval: Double + + private var thread: ChatThread? + private let dqueue: DispatchQueue + + public var format: AudioFormat.Factory { + get { + return { () in self.formatChat! } + } + } + + init(_ format: AudioStreamBasicDescription, + _ interval: Double, + _ queue: DispatchQueue, + _ output: AudioOutputProtocol?) { + self.formatDescription = format + self.interval = interval + self.dqueue = queue + self.output = output + } + + convenience init(_ format: AudioStreamBasicDescription, + _ interval: Double, + _ output: AudioOutputProtocol?) { + self.init(format, interval, AV.shared.audioCaptureQueue, output) + } + + convenience init(_ format: AudioStreamBasicDescription, + _ interval: Double) { + self.init(format, interval, nil) + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // IOSessionProtocol + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + func start() throws { + assert(dqueue) + logIOPrior("audio input start") + + // thread + + thread = ChatThread(AudioInput.self) + thread!.start() + + // start queue + + var packetMaxSize: UInt32 = 0 + var bufferByteSize: UInt32 + var size: UInt32 + + // create the queue + + try checkStatus(AudioQueueNewInput( + &formatDescription, + callback, + Unmanaged.passUnretained(self).toOpaque() /* userData */, + thread!.runLoop.getCFRunLoop(), CFRunLoopMode.defaultMode.rawValue, + 0 /* flags */, + &queue), "AudioQueueNewInput failed") + + // get the record format back from the queue's audio converter -- + // the file may require a more specific stream description than was necessary to create the encoder. + + size = UInt32(MemoryLayout.size) + try checkStatus(AudioQueueGetProperty(queue!, + kAudioQueueProperty_StreamDescription, + &formatDescription, + &size), "couldn't get queue's format"); + + // allocate and enqueue buffers + + bufferByteSize = computeBufferSize(formatDescription, + interval, + &packetMaxSize); // enough bytes for kBufferDurationSeconds + + for _ in 0 ..< AudioInput.kBuffersCount { + var buffer: AudioQueueBufferRef? + + try checkStatus(AudioQueueAllocateBuffer(queue!, + bufferByteSize, + &buffer), "AudioQueueAllocateBuffer failed"); + + try checkStatus(AudioQueueEnqueueBuffer(queue!, + buffer!, + 0, + nil), "AudioQueueEnqueueBuffer failed"); + } + + // start the queue + + try checkStatus(AudioQueueStart(queue!, + nil), "AudioQueueStart failed"); + + // audio format + + formatChat = AudioFormat(formatDescription) + } + + func stop() { + assert(dqueue) + logIOPrior("audio input stop") + + guard let queue = self.queue else { assert(false); return } + + stopping = true + + thread?.sync { + do { + // end recording + try checkStatus(AudioQueueStop(queue, + true), "AudioQueueStop failed") + + // free buffers + _ = self.buffers.map({ AudioQueueFreeBuffer(queue, $0) }) + + // a codec may update its cookie at the end of an encoding session, so reapply it to the file now + try checkStatus(AudioQueueDispose(queue, + true), "AudioQueueDispose failed") + + self.queue = nil + self.thread!.cancel() + self.thread = nil + } + catch { + logIOError(error) + } + } + + stopping = false + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Utils + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + private let callback: AudioQueueInputCallback = { + (inUserData: UnsafeMutableRawPointer?, + inAQ: AudioQueueRef, + inBuffer: AudioQueueBufferRef, + inStartTime: UnsafePointer, + inNumPackets: UInt32, + inPacketDesc: UnsafePointer?) in + + let input = Unmanaged.fromOpaque(inUserData!).takeUnretainedValue() + + guard input.stopping == false else { return } + + logIO("audio input \(inStartTime.pointee.seconds())") + + do { + guard let queue = input.queue else { return } + + if (inNumPackets > 0) { + let time = inStartTime.pointee + let data = NSData(bytes: inBuffer.pointee.mAudioData, length: Int(inBuffer.pointee.mAudioDataByteSize)) + let desc = inPacketDesc != nil ? AudioStreamPacketDescription.ToArray(inPacketDesc!, inNumPackets) : nil + + // process input + + AV.shared.audioCaptureQueue.async { input.output!.process(AudioData(time, data, desc)) } + + // simulate gaps + +// AV.shared.audioCaptureQueue.asyncAfter0_5 { input.output!.process(AudioData(time, data, desc)) } + } + + try checkStatus(AudioQueueEnqueueBuffer(input.queue!, + inBuffer, + 0, + nil), "AudioQueueEnqueueBuffer failed"); + } + catch { + logIOError(error) + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Utils + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + private func computeBufferSize(_ format: AudioStreamBasicDescription, + _ interval: Double, + _ packetMaxSize: inout UInt32) -> UInt32 + { + var packets: UInt32 + var frames: UInt32 + var bytes: UInt32 = 0 + + do { + frames = UInt32(ceil(interval * format.mSampleRate)) + + if (format.mBytesPerFrame > 0) { + bytes = frames * format.mBytesPerFrame + packetMaxSize = format.mBytesPerPacket + } + else { + if (format.mBytesPerPacket > 0) { + packetMaxSize = format.mBytesPerPacket // constant packet size + } + else { + var propertySize: UInt32 = UInt32(MemoryLayout.size) + try checkStatus(AudioQueueGetProperty(queue!, + kAudioQueueProperty_MaximumOutputPacketSize, + &packetMaxSize, + &propertySize), + "couldn't get queue's maximum output packet size") + } + + if (format.mFramesPerPacket > 0) { + packets = frames / format.mFramesPerPacket + } + else { + packets = frames // worst-case scenario: 1 frame in a packet + } + + if (packets == 0) { // sanity check + packets = 1 + } + + bytes = packets * packetMaxSize; + } + } + catch { + logIOError(error) + } + + return bytes; + } + +} diff --git a/apple/Common/IO/AudioOutput.swift b/apple/Common/IO/AudioOutput.swift new file mode 100644 index 0000000..96ea5d0 --- /dev/null +++ b/apple/Common/IO/AudioOutput.swift @@ -0,0 +1,121 @@ + +import AudioToolbox + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// AudioOutput +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class AudioOutput : AudioOutputProtocol, IOSessionProtocol { + + private let dqueue: DispatchQueue + private var squeue: DispatchQueue? + private var unit: AppleAudioUnit? + + private var buffer = AudioDataReader(capacity: 2) + private var bufferFrames = 0 + + private let formatInput: AudioFormat.Factory + private var formatDescription: AudioStreamBasicDescription? + + var packets: Int = 0 + + init(_ format: @escaping AudioFormat.Factory, _ queue: DispatchQueue) { + self.dqueue = queue + self.formatInput = format + } + + var format: AudioStreamBasicDescription.Factory { + get { + return { () in + return self.formatDescription + } + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // IOSessionProtocol + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + func start() { + assert(dqueue) + logIOPrior("audio output start") + + do { + packets = 0 + squeue = DispatchQueue.CreateCheckable("chat.AudioOutput") + + var callback = AURenderCallbackStruct(inputProc: self.callback, + inputProcRefCon: Unmanaged.passUnretained(self).toOpaque()) + + #if os(iOS) + unit = try AppleAudioUnit(kAudioUnitType_Output, kAudioUnitSubType_RemoteIO) + #else + unit = try AppleAudioUnit(kAudioUnitType_Output, kAudioUnitSubType_VoiceProcessingIO) + #endif + + try unit!.getFormat(kAudioUnitScope_Input, AudioBus.input, &formatDescription) + try unit!.setIOEnabled(kAudioUnitScope_Input, AudioBus.output, true) + try unit!.setRenderer(kAudioUnitScope_Input, AudioBus.input, &callback) + try unit!.initialize() + try unit!.start() + } + catch { + logIOError(error) + } + } + + func stop() { + assert(dqueue) + logIOPrior("audio output stop") + + do { + try unit!.reset(kAudioUnitScope_Input, AudioBus.input) + try unit!.uninitialize() + try unit!.stop() + squeue = nil + } + catch { + logIOError(error) + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // AudioOutputProtocol + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + func process(_ data: AudioData) { + assert(dqueue) + + squeue!.sync { + buffer.push(data) + } + } + + var lastTime: Double = 0 + + private let callback: AURenderCallback = {( + inRefCon: UnsafeMutableRawPointer, + ioActionFlags: UnsafeMutablePointer, + inTimeStamp: UnsafePointer, + inBusNumber: UInt32, + inNumberFrames: UInt32, + ioData: UnsafeMutablePointer?) in + + let SELF = Unmanaged.fromOpaque(inRefCon).takeUnretainedValue() + let buffers = UnsafeBufferPointer(start: &ioData!.pointee.mBuffers, + count: Int(ioData!.pointee.mNumberBuffers)) + + SELF.squeue!.sync { + autoreleasepool(invoking: { + SELF.buffer.pop(Int(inNumberFrames * SELF.formatDescription!.mBytesPerFrame), + buffers[0].mData!) + + for i in 1 ..< Int(ioData!.pointee.mNumberBuffers) { + memcpy(buffers[i].mData!, buffers[0].mData!, Int(buffers[0].mDataByteSize)) + } + }) + } + + return 0 + } +} diff --git a/apple/Common/IO/IO.swift b/apple/Common/IO/IO.swift new file mode 100644 index 0000000..c0ea594 --- /dev/null +++ b/apple/Common/IO/IO.swift @@ -0,0 +1,431 @@ + +import AVFoundation +import AudioToolbox +import VideoToolbox + +struct IOID { + let from: String + let to: String + let sid: String // session unique ID + let gid: String // io group (audio + video) ID + + init(_ from: String, _ to: String, _ sid: String, _ gid: String) { + self.from = from + self.to = to + self.sid = sid + self.gid = gid + } + + init(_ from: String, _ to: String) { + self.from = from + self.to = to + self.sid = IOID.newID(from, to, "sid") + self.gid = IOID.newID(from, to, "gid") + } + + func groupNew() ->IOID { + return IOID(from, to, IOID.newID(from, to, "sid"), gid) + } + + static private func newID(_ from: String, _ to: String, _ kind: String) -> String { + return "\(kind) \(from) - \(to) (\(UUID()))" + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Simple types +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +enum IOKind : Int { + case Audio + case Video +} + +protocol IODataProtocol { + + func process(_ data: NSData) +} + +typealias IOSessionProtocol = SessionProtocol + +struct IOFormat { + + private static let kID = "kID" + + var data: [String: Any] + + init () { + data = [String: Any]() + data[IOFormat.kID] = UUID().uuidString + } + + init(_ data: [String: Any]) { + self.data = data + } + + var id: String { + get { + return data[IOFormat.kID]! as! String + } + } +} + +class IOData : IODataProtocol { + private let next: IODataProtocol? + init() { next = nil } + init(_ next: IODataProtocol?) { self.next = next } + func process(_ data: NSData) { next?.process(data) } +} + +class IOSession : IOSessionProtocol { + private let next: IOSessionProtocol? + init() { next = nil } + init(_ next: IOSessionProtocol?) { self.next = next } + func start() throws { try next?.start() } + func stop() { next?.stop() } +} + +class IOSessionBroadcast : IOSessionProtocol { + + private var x: [IOSessionProtocol?] + + init(_ x: [IOSessionProtocol?]) { + self.x = x + } + + func start () throws { + _ = try x.map({ try $0?.start() }) + } + + func stop() { + _ = x.reversed().map({ $0?.stop() }) + } +} + +func broadcast(_ x: [IOSessionProtocol?]) -> IOSessionProtocol? { + if (x.count == 0) { + return nil + } + if (x.count == 1) { + return x.first! + } + + return IOSessionBroadcast(x) +} + +class IODataSession : IODataProtocol, IOSessionProtocol { + + private(set) var active = false + private let next: IODataProtocol + + init(_ next: IODataProtocol) { + self.next = next + } + + func start() throws { + assert(active == false) + active = true + } + + func stop() { + assert(active == true) + active = false + } + + func process(_ data: NSData) { + guard active else { logIO("received data after session stopped"); return } + next.process(data) + } +} + +struct IOInputContext { + let qos: IOQoS + let balancer: IOQoSBalancerProtocol + + init(_ balancer: IOQoSBalancerProtocol) { + self.qos = IOQoS() + self.balancer = balancer + } +} + +struct IOOutputContext { + let id: IOID? + let session: IOSessionProtocol? + let data: IODataProtocol? + let timebase: IOTimebase? + let balancer: IOBalancer? + + // concrete context + init(_ id: IOID?, + _ session: IOSessionProtocol?, + _ data: IODataProtocol?, + _ timebase: IOTimebase?, + _ balancer: IOBalancer?) { + self.id = id + self.session = session + self.data = data + self.timebase = timebase + self.balancer = balancer + } + + // create context with shared info + init(_ id: IOID, + _ session: IOSessionProtocol, + _ data: IODataProtocol, + _ context: IOOutputContext) { + self.init(id, session, data, context.timebase, context.balancer) + } + + // context for sharing sync and balancer + init() { + self.init(nil, nil, nil, IOTimebase(), IOBalancer()) + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Time +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +struct IOTime { + + let hostSeconds: Float64 + + init() { + hostSeconds = 0 + } + + init(_ hostSeconds: Float64) { + self.hostSeconds = hostSeconds + } +} + +protocol IOTimeProtocol { + var time: IOTime { get } + func copy(time: IOTime) -> Self +} + +protocol IOTimeUpdaterProtocol { + func time(_ data: NSData) -> Double + func time(_ data: inout NSData, _ time: Double) +} + +class IOTimeUpdater : IOTimeUpdaterProtocol { + + private let updater: PacketsUpdater + + init(_ index: Int) { + updater = PacketsUpdater(index) + } + + func concreteTime(_ data: NSData) -> T { + var result = T() + updater.getValue(data, &result) + return result + } + + func concreteTime(_ data: inout NSData, _ time: T) { + updater.setValue(&data, time) + } + + func time(_ data: NSData) -> Double { + return concreteTime(data).time.hostSeconds + } + + func time(_ data: inout NSData, _ time: Double) { + concreteTime(&data, concreteTime(data).copy(time: IOTime(time))) + } +} + +class IOTimebase { + var zero: Double? +} + +class IOTimebaseReset : IODataProtocol { + + private let time: IOTimeUpdaterProtocol + private var timebase: IOTimebase + private let next: IODataProtocol? + + init(_ timebase: IOTimebase, + _ time: IOTimeUpdaterProtocol, + _ next: IODataProtocol?) { + self.time = time + self.timebase = timebase + self.next = next + } + + func process(_ data: NSData) { + let dataTime = time.time(data) + var copy = data + + if timebase.zero == nil { + timebase.zero = dataTime + } + + else if timebase.zero! > dataTime { + return + } + + time.time(©, dataTime - timebase.zero!) + next?.process(copy) + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// QOS +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +protocol IOQoSProtocol { + func change(_ toQID: String, _ diff: Int) +} + +protocol IOQoSBalancerProtocol { + func process(_ qosID: String, _ gap: Double) +} + +class IOQoSDispatcher : IOQoSProtocol { + + let queue: DispatchQueue + let next: IOQoSProtocol + + init(_ queue: DispatchQueue, _ next: IOQoSProtocol) { + self.queue = queue + self.next = next + } + + func change(_ toQID: String, _ diff: Int) { + queue.sync { next.change(toQID, diff) } + } + +} + +class IOQoSBroadcast : IOQoSProtocol { + + private var x: [IOQoSProtocol?] + + init(_ x: [IOQoSProtocol?]) { + self.x = x + } + + func change(_ toQID: String, _ diff: Int) { + _ = x.map({ $0?.change(toQID, diff) }) + } +} + +class IOQoS { + + static let kInit = 0 + static let kIncrease = 1 + static let kDecrease = -1 + + var clients = [IOQoSProtocol]() + var qid: String = UUID().uuidString + + func add(_ x: IOQoSProtocol) { + clients.append(x) + x.change(qid, IOQoS.kInit) + } + + func change(_ diff: Int) { + qid = UUID().uuidString + _ = clients.map({ $0.change(qid, diff) }) + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Logging +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +enum ErrorIO : Error { + case Error(String) +} + +func logIO(_ message: String) { + logMessage("IO", message) +} + +func logIOPrior(_ message: String) { + logPrior("IO", message) +} + +func logIOError(_ error: Error) { + logError("IO", error) +} + +func logIOError(_ error: String) { + logError("IO", error) +} + +func checkStatus(_ status: OSStatus, _ message: String) throws { + guard status == 0 else { + throw ErrorIO.Error(message + ", status code \(status)") + } +} + +func checkIO(_ x: FuncVVT) { + do { + try x() + } + catch { + logIOError(error) + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// IOData dispatcher +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class IODataAsyncDispatcher : IODataProtocol { + + let queue: DispatchQueue + private let next: IODataProtocol + + init(_ queue: DispatchQueue, _ next: IODataProtocol) { + self.queue = queue + self.next = next + } + + func process(_ data: NSData) { + queue.async { self.next.process(data) } + } +} + +class IOSessionDispatcher : IOSessionProtocol { + typealias Call = (@escaping FuncVV) -> Void + + private let call: Call + private let next: IOSessionProtocol? + + init(_ call: @escaping Call, _ next: IOSessionProtocol?) { + self.call = call + self.next = next + } + + func start() throws { + call { do { try self.next?.start() } catch { logIOError(error) } } + } + + func stop() { + call { self.next?.stop() } + } +} + +class IOSessionSyncDispatcher : IOSessionDispatcher { + + let queue: DispatchQueue + + init(_ queue: DispatchQueue, _ next: IOSessionProtocol?) { + self.queue = queue + super.init({ (block: @escaping FuncVV) in queue.sync(execute: block) }, next) + } +} + +class IOSessionAsyncDispatcher : IOSessionDispatcher { + + let queue: DispatchQueue + + init(_ queue: DispatchQueue, _ next: IOSessionProtocol?) { + self.queue = queue + super.init({ (block: @escaping FuncVV) in queue.async(execute: block) }, next) + } +} diff --git a/apple/Common/IO/IOBalancer.swift b/apple/Common/IO/IOBalancer.swift new file mode 100644 index 0000000..24cbcef --- /dev/null +++ b/apple/Common/IO/IOBalancer.swift @@ -0,0 +1,396 @@ + +import Foundation + +func logIOSync(_ message: String) { + logIO("Sync: \(message)") +} + +func logIOSyncPrior(_ message: String) { + logIOPrior("Sync: \(message)") +} + +protocol IODataBalancerProtocol { + + func tuning(_ data: NSData, _ gap: Double) + func shedule(_ data: NSData, _ gap: Double, _ at: Date) + func zombie(_ data: NSData, _ gap: Double) + func reshedule(_ shift: Double) +} + +protocol IOBalancedDataProtocol : IODataProtocol { + + func tuning(_ data: NSData) + func belated(_ data: NSData) +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// IOBalancer +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class IOBalancer { + + static let kMaxGap = 3.0 // in seconds + static let kInterval = 0.1 // number packets for tuning + private static let kTuneCount = 10 // number packets for tuning + private static var kGapCount: Int = 30 + + private var localZero: Double? + private var remoteZero: Double? + private var remoteLast = 0.0 + private var shedule = [Int64: Double]() // local nanoseconds : remote seconds + + private var gap = 0.0 + private var gapReal = 0.0 + private var gapLog = [Double]() + + private var packets: Int = 0 + + private var localTime: Double { + get { + return Date().timeIntervalSince1970 + } + } + + func process(_ remoteTime: Double, + shedule: @escaping FuncDDV, + reshedule: @escaping FuncDV, + zombie: @escaping FuncDV, + tuning: @escaping FuncDV) { + let localTime = self.localTime + var callback: FuncVV? + + packets += 1 + + // init + + if localZero == nil { + localZero = localTime + remoteZero = remoteTime + } + + // calc gap + + let gap = (localTime - localZero!) - (remoteTime - remoteZero!) + let gapPrev = self.gap + let sheduleTime = localTime + self.gap - gap + + _updateGap(gap) + + // sheduling + + let shedule_: FuncDV = { (time: Double) in + shedule(self.gapReal, time) + self.shedule[seconds2nano(sheduleTime)] = remoteTime + } + + // belated + + if _belated(remoteTime, localTime) { + callback = { logIOSyncPrior("global gap: \(self.gapReal)"); zombie(self.gapReal) } + } + + // reshedule + shedule + + else if micro(gap) > micro(self.gap) { + callback = { reshedule(self.gap - gapPrev); shedule_(sheduleTime) } + } + + // shedule + + else { + callback = { shedule_(sheduleTime) } + } + + if packets > IOBalancer.kTuneCount { + callback!() + } + else { + tuning(self.gapReal) + } + } + + private func _belated(_ remoteTime: Double, _ localTime: Double) -> Bool { + + let localNano = seconds2nano(localTime) + + for i in shedule.keys { + if i > localNano { + continue + } + + if remoteLast < shedule[i]! { + remoteLast = shedule[i]! + } + + shedule.removeValue(forKey: i) + } + + return nano(remoteTime) <= nano(remoteLast) + } + + private func _calc() -> Double { + let gapSorted = gapLog.sorted() + let diffAverage = max((gapSorted.last! - gapSorted.first!) / Double(gapSorted.count), IOBalancer.kInterval) + var index: Int = gapSorted.count - 1 + + while index >= gapSorted.count * 10 / 100 && index > 1 { + if gapSorted[index] - gapSorted[index - 1] < diffAverage { + break + } + + index -= 1 + } + + return gapSorted[index] + } + + private func _updateGap(_ gap: Double) { + gapLog.append(gap) + + if gapLog.count > IOBalancer.kGapCount { + gapLog.removeFirst() + } + + self.gapReal = _calc() + self.gap = min(gapReal, IOBalancer.kMaxGap) + IOBalancer.kInterval + + logIOSync("gap \(self.gap)") + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// IOSheduler +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class IOSheduler : IODataBalancerProtocol, IOSessionProtocol { + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Internal Structs + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + private struct _QueueItem { + var timer: Timer + let data: NSData + + init(_ timer: Timer, _ data: NSData) { + self.timer = timer + self.data = data + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Fields + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + private(set) var active: Bool = false + + private var id: Int = 0 + private var nextID: Int { get { id += 1; return id } } + + private var thread: ChatThread? + private var queue = [Int: _QueueItem]() + + private let kind: IOKind + private let output: IOBalancedDataProtocol + + init(_ kind: IOKind, _ output: IOBalancedDataProtocol) { + self.kind = kind + self.output = output + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // IOSessionProtocol + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + func start() throws { + guard active == false else { return } + + thread = ChatThread(IOSheduler.self) + thread!.start() + active = true + } + + func stop() { + guard active == true else { return } + + thread!.cancel() + thread = nil + active = false + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // IOBalancedDataProtocol + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + func tuning(_ data: NSData, _ gap: Double) { + output.tuning(data) + } + + func shedule(_ data: NSData, _ gap: Double, _ at: Date) { + thread!.sync { + let id = self.nextID + let timer = self._timer(at, id) + + logIOSync("Sheduling \(self.kind) data with id \(id)") + self.queue[id] = _QueueItem(timer, data) + self.sheduleTimer(timer) + } + } + + func zombie(_ data: NSData, _ gap: Double) { + logIOSyncPrior("Belated \(self.kind) data with gap \(gap) lost") + output.belated(data) + } + + func reshedule(_ shift: Double) { + thread!.sync { + logIOSync("Resheduling with shift \(shift)") + + for var i in self.queue { + i.value.timer.invalidate() + i.value.timer = self._timer(i.value.timer.fireDate.addingTimeInterval(shift), + i.key) + self.sheduleTimer(i.value.timer) + } + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Sheduling + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + private func _timer(_ at: Date, _ id: Int) -> Timer { + return Timer(fireAt: at, + interval: 0, + target: self, + selector: #selector(_output(timer:)), + userInfo: id, + repeats: false) + } + + @objc private func _output(timer: Timer) { + let id = timer.userInfo as! Int + +// assert(queue[id] != nil) + guard let data = queue[id]?.data else { return } + + _output(data) + queue.removeValue(forKey: id) + } + + private func _output(_ data: NSData) { + AV.shared.avOutputQueue.async { + self.output.process(data) + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Test support + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + fileprivate func sheduleTimer(_ timer: Timer) { + thread!.runLoop.add(timer, forMode: .defaultRunLoopMode) + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Utils +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class IOBalanceSubdataSkip : IOBalancedDataProtocol { + + let next: IODataProtocol? + + init(_ next: IODataProtocol?) { + self.next = next + } + + func tuning(_ data: NSData) { + } + + func belated(_ data: NSData) { + } + + func process(_ data: NSData) { + next?.process(data) + } +} + +class IOBalancedDataSession : IODataSession, IOBalancedDataProtocol { + + let next: IOBalancedDataProtocol + + init(_ next: IOBalancedDataProtocol) { + self.next = next + super.init(next) + } + + func tuning(_ data: NSData) { + guard active else { logIO("received data after session stopped"); return } + next.tuning(data) + } + + func belated(_ data: NSData) { + guard active else { logIO("received data after session stopped"); return } + next.belated(data) + } +} + +class IODataAdapter4Balancer : IODataProtocol { + + private let balancer: IOBalancer + private let time: IOTimeUpdaterProtocol + private let output: IODataBalancerProtocol + + init(_ time: IOTimeUpdaterProtocol, _ balancer: IOBalancer, _ output: IODataBalancerProtocol) { + self.time = time + self.output = output + self.balancer = balancer + } + + func process(_ data: NSData) { + let remoteTime = time.time(data) + + balancer.process(remoteTime, + shedule: { (gap: Double, at: Double) in + self.output.shedule(data, gap, Date(timeIntervalSince1970: at)) }, + reshedule: { (shift: Double) in self.output.reshedule(shift) }, + zombie: { (gap: Double) in self.output.zombie(data, gap) }, + tuning: { (gap: Double) in self.output.tuning(data, gap) }) + } +} + +class IODataBalancer: IODataBalancerProtocol { + + func tuning(_ data: NSData, _ gap: Double) { } + func shedule(_ data: NSData, _ gap: Double, _ at: Date) {} + func zombie(_ data: NSData, _ gap: Double) {} + func reshedule(_ shift: Double) {} +} + +class IODataBalancerBroadcast : IODataBalancerProtocol { + + var x: [IODataBalancerProtocol?] + + init(_ x: [IODataBalancerProtocol?]) { + self.x = x + } + + func tuning(_ data: NSData, _ gap: Double) { + _ = x.map({ $0?.tuning(data, gap) }) + } + + func shedule(_ data: NSData, _ gap: Double, _ at: Date) { + _ = x.map({ $0?.shedule(data, gap, at) }) + } + + func zombie(_ data: NSData, _ gap: Double) { + _ = x.map({ $0?.zombie(data, gap) }) + } + + func reshedule(_ shift: Double) { + _ = x.map({ $0?.reshedule(shift) }) + + } +} + diff --git a/apple/Common/IO/Video.swift b/apple/Common/IO/Video.swift new file mode 100644 index 0000000..9877c6d --- /dev/null +++ b/apple/Common/IO/Video.swift @@ -0,0 +1,164 @@ + +import AVFoundation +import VideoToolbox + +struct VideoFormat : Equatable { + + typealias Factory = () throws -> VideoFormat + + private(set) var format: IOFormat + private static let kWidth = "width" + private static let kHeight = "height" + + init(_ dimension: CMVideoDimensions) { + format = IOFormat() + width = UInt32(dimension.width) + height = UInt32(dimension.height) + } + + init(_ format: IOFormat) { + self.format = format + } + + init(_ format: AVCaptureDeviceFormat) { + self.init(format.dimensions) + } + + public static func ==(lhs: VideoFormat, rhs: VideoFormat) -> Bool { + return lhs.width == rhs.width && lhs.height == rhs.width + + } + + public static func !=(lhs: VideoFormat, rhs: VideoFormat) -> Bool { + return false == (lhs == rhs) + } + + var width: UInt32 { + get { + return format.data.keys.contains(VideoFormat.kWidth) ? format.data[VideoFormat.kWidth] as! UInt32 : 0 + } + set { + format.data[VideoFormat.kWidth] = newValue + } + } + + var height: UInt32 { + get { + return format.data.keys.contains(VideoFormat.kHeight) ? format.data[VideoFormat.kHeight] as! UInt32 : 0 + } + set { + format.data[VideoFormat.kHeight] = newValue + } + } + + var dimensions: CMVideoDimensions { + get { + return CMVideoDimensions(width: Int32(width), height: Int32(height)) + } + } + + mutating func rotate() { + swap(&width, &height) + } +} + +protocol VideoOutputProtocol { + + func process(_ data: CMSampleBuffer) +} + +protocol VideoSessionProtocol : IOSessionProtocol { + + func update(_ outputFormat: VideoFormat) throws +} + +class VideoSession : IOSession, VideoSessionProtocol { + + private let next: VideoSessionProtocol? + override init() { next = nil; super.init() } + init(_ next: VideoSessionProtocol?) { self.next = next; super.init(next) } + func update(_ outputFormat: VideoFormat) throws { try next?.update(outputFormat) } +} + +class VideoSessionBroadcast : IOSessionBroadcast, VideoSessionProtocol { + + private var x: [VideoSessionProtocol?] + + init(_ x: [VideoSessionProtocol?]) { + self.x = x + super.init(x) + } + + func update(_ outputFormat: VideoFormat) throws { + _ = try x.map({ try $0?.update(outputFormat) }) + } +} + +class VideoSessionAsyncDispatcher : IOSessionAsyncDispatcher, VideoSessionProtocol { + + private let next: VideoSessionProtocol? + + init(_ queue: DispatchQueue, _ next: VideoSessionProtocol?) { + self.next = next + super.init(queue, next) + } + + func update(_ outputFormat: VideoFormat) throws { + queue.async{ do { try self.next?.update(outputFormat) } catch { logIOError(error) } } + } +} + +func broadcast(_ x: [VideoSessionProtocol]) -> VideoSessionProtocol? { + if (x.count == 0) { + return nil + } + if (x.count == 1) { + return x.first + } + + return VideoSessionBroadcast(x) +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Time +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +struct VideoTime : IOTimeProtocol { + let time: IOTime + let timeScale: Int32 + + init() { + time = IOTime() + timeScale = 0 + } + + init(_ hostSeconds: Float64, _ timeScale: Int32) { + self.time = IOTime(hostSeconds) + self.timeScale = timeScale + } + + func copy(time: IOTime) -> VideoTime { + return VideoTime(time.hostSeconds, timeScale) + } +} + +extension VideoTime { + + init(_ x: CMSampleTimingInfo) { + self.init(CMTimeGetSeconds(x.presentationTimeStamp), x.presentationTimeStamp.timescale) + } + + func ToCMSampleTimingInfo() -> CMSampleTimingInfo { + var result = CMSampleTimingInfo() + result.presentationTimeStamp.flags = .valid + result.presentationTimeStamp.timescale = timeScale + CMTimeSetSeconds(&result.presentationTimeStamp, time.hostSeconds) + + return result + } +} + +extension VideoTime : InitProtocol {} +extension VideoTime : SerializableProtocol {} +typealias VideoTimeSerializer = IOTimeUpdater + diff --git a/apple/Common/IO/VideoDecoderH264.swift b/apple/Common/IO/VideoDecoderH264.swift new file mode 100644 index 0000000..9247840 --- /dev/null +++ b/apple/Common/IO/VideoDecoderH264.swift @@ -0,0 +1,115 @@ + +import Foundation +import CoreMedia +import VideoToolbox + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// VideoDecoderH264 +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class VideoDecoderH264 : VideoOutputProtocol, VideoSessionProtocol { + + private let next: VideoOutputProtocol? + private var session: VTDecompressionSession? + + init(_ next: VideoOutputProtocol?) { + self.next = next + } + + func start() throws { + } + + func stop() { + + } + + func update(_ outputFormat: VideoFormat) throws { + + } + + func process(_ data: CMSampleBuffer) { + if session == nil { + do { + guard + let formatDescription = CMSampleBufferGetFormatDescription(data) + else { logError("CMSampleBufferGetFormatDescription"); return } + let destinationPixelBufferAttributes = NSMutableDictionary() + destinationPixelBufferAttributes.setValue(NSNumber(value: kCVPixelFormatType_32BGRA), forKey: kCVPixelBufferPixelFormatTypeKey as String) + + var outputCallback = VTDecompressionOutputCallbackRecord() + outputCallback.decompressionOutputCallback = callback + outputCallback.decompressionOutputRefCon = unsafeBitCast(self, to: UnsafeMutableRawPointer.self) + + try checkStatus(VTDecompressionSessionCreate(kCFAllocatorDefault, + formatDescription, + nil, + destinationPixelBufferAttributes, + &outputCallback, + &session), "VTDecompressionSessionCreate") + } + catch { + logIOError(error) + } + } + + var infoFlags = VTDecodeInfoFlags(rawValue: 0) + + VTDecompressionSessionDecodeFrame(session!, + data, + [._1xRealTimePlayback], + nil, + &infoFlags) + VTDecompressionSessionFinishDelayedFrames(session!) + VTDecompressionSessionWaitForAsynchronousFrames(session!) + } + + var i = 0 + + private var callback: VTDecompressionOutputCallback = {(decompressionOutputRefCon: UnsafeMutableRawPointer?, + sourceFrameRefCon: UnsafeMutableRawPointer?, + status: OSStatus, + infoFlags: VTDecodeInfoFlags, + imageBuffer: CVImageBuffer?, + presentationTimeStamp: CMTime, + presentationDuration: CMTime) in + + do { + try checkStatus(status, "VTDecompressionOutputCallbacks") + + let SELF: VideoDecoderH264 = unsafeBitCast(decompressionOutputRefCon, to: VideoDecoderH264.self) + var sampleBuffer: CMSampleBuffer? + + var sampleTiming = CMSampleTimingInfo( + duration: presentationDuration, + presentationTimeStamp: presentationTimeStamp, + decodeTimeStamp: kCMTimeInvalid + ) + + var formatDescription: CMFormatDescription? + + try checkStatus(CMVideoFormatDescriptionCreateForImageBuffer( + kCFAllocatorDefault, + imageBuffer!, + &formatDescription), "CMVideoFormatDescriptionCreateForImageBuffer") + + + try checkStatus(CMSampleBufferCreateForImageBuffer( + kCFAllocatorDefault, + imageBuffer!, + true, + nil, + nil, + formatDescription!, + &sampleTiming, + &sampleBuffer), "CMSampleBufferCreateForImageBuffer") + + AV.shared.avOutputQueue.async { + SELF.next?.process(sampleBuffer!) + } + } + catch { + logIOError(error) + } + + } as VTDecompressionOutputCallback +} diff --git a/apple/Common/IO/VideoEncoderH264.swift b/apple/Common/IO/VideoEncoderH264.swift new file mode 100644 index 0000000..ad6f496 --- /dev/null +++ b/apple/Common/IO/VideoEncoderH264.swift @@ -0,0 +1,160 @@ + +import AVFoundation +import VideoToolbox + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Session +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class VideoEncoderSessionH264 : VideoSessionProtocol, VideoOutputProtocol { + + public typealias Callback = (VideoEncoderSessionH264) -> Void + + private var session: VTCompressionSession? + private let inputDimension: CMVideoDimensions + private var outputFormat: VideoFormat + private let next: VideoOutputProtocol? + private let callback: Callback? + + init(_ inputDimension: CMVideoDimensions, + _ outputFormat: VideoFormat, + _ next: VideoOutputProtocol?) { + self.inputDimension = inputDimension + self.outputFormat = outputFormat + self.next = next + self.callback = nil + } + + init(_ inputDimension: CMVideoDimensions, + _ outputFormat: VideoFormat, + _ next: VideoOutputProtocol?, + _ callback: @escaping Callback) { + self.inputDimension = inputDimension + self.outputFormat = outputFormat + self.next = next + self.callback = callback + } + + private var sessionCallback: VTCompressionOutputCallback = {( + outputCallbackRefCon:UnsafeMutableRawPointer?, + sourceFrameRefCon:UnsafeMutableRawPointer?, + status:OSStatus, + infoFlags:VTEncodeInfoFlags, + sampleBuffer_:CMSampleBuffer? + ) in + + let SELF: VideoEncoderSessionH264 = unsafeBitCast(outputCallbackRefCon, to: VideoEncoderSessionH264.self) + guard let sampleBuffer = sampleBuffer_ else { logIOError("VideoEncoderSessionH264 nil buffer"); return } + + do { + try checkStatus(status, "VTCompressionSession to H264 failed") + + AV.shared.videoCaptureQueue.async { + SELF.callback?(SELF) + SELF.next?.process(sampleBuffer) + } + } + catch { + logIOError(error) + } + + } as VTCompressionOutputCallback + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // IOSessionProtocol + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + func start() throws { + assert_video_capture_queue() + + VTCompressionSessionCreate( + kCFAllocatorDefault, + Int32(outputFormat.width), + Int32(outputFormat.height), + kCMVideoCodecType_H264, + nil, + attributes as CFDictionary, + nil, + sessionCallback, + unsafeBitCast(self, to: UnsafeMutableRawPointer.self), + &session) + + VTSessionSetProperties(session!, properties as CFDictionary) + VTCompressionSessionPrepareToEncodeFrames(session!) + } + + func stop() { + assert_video_capture_queue() + + guard let session = self.session else { return } + + VTCompressionSessionCompleteFrames(session, kCMTimeInvalid) + VTCompressionSessionInvalidate(session) + + self.session = nil + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // VideoSessionProtocol + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + func update(_ outputFormat: VideoFormat) throws { + self.outputFormat = outputFormat + + stop() + try start() + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // VideoOutputProtocol + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + func process(_ data: CMSampleBuffer) { + guard let imageBuffer:CVImageBuffer = CMSampleBufferGetImageBuffer(data) else { return } + guard let session = self.session else { logIOError("VideoEncoderSessionH264 no session"); return } + var flags:VTEncodeInfoFlags = VTEncodeInfoFlags() + + VTCompressionSessionEncodeFrame(session, + imageBuffer, + CMSampleBufferGetPresentationTimeStamp(data), + CMSampleBufferGetDuration(data), + nil, + nil, + &flags) + VTCompressionSessionCompleteFrames(session, kCMTimeInvalid) + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // Settings + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + let defaultAttributes:[NSString: AnyObject] = [ + kCVPixelBufferPixelFormatTypeKey: Int(kCVPixelFormatType_32BGRA) as AnyObject, + ] + fileprivate var width:Int32! + fileprivate var height:Int32! + + fileprivate var attributes:[NSString: AnyObject] { + var attributes:[NSString: AnyObject] = defaultAttributes + attributes[kCVPixelBufferHeightKey] = inputDimension.height as AnyObject + attributes[kCVPixelBufferWidthKey] = inputDimension.width as AnyObject + return attributes + } + + var profileLevel:String = kVTProfileLevel_H264_Baseline_AutoLevel as String + fileprivate var properties:[NSString: AnyObject] { + let isBaseline:Bool = profileLevel.contains("Baseline") + var properties:[NSString: AnyObject] = [ + kVTCompressionPropertyKey_RealTime: kCFBooleanTrue, + kVTCompressionPropertyKey_ProfileLevel: profileLevel as NSObject, + kVTCompressionPropertyKey_AverageBitRate: Int(outputFormat.width * outputFormat.height) as NSObject, + kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration: NSNumber(value: 1.0 as Double), + kVTCompressionPropertyKey_AllowFrameReordering: !isBaseline as NSObject, + ] + if (!isBaseline) { + properties[kVTCompressionPropertyKey_H264EntropyMode] = kVTH264EntropyMode_CABAC + } + return properties + } +} + diff --git a/apple/Common/IO/VideoInput.swift b/apple/Common/IO/VideoInput.swift new file mode 100644 index 0000000..e62498b --- /dev/null +++ b/apple/Common/IO/VideoInput.swift @@ -0,0 +1,230 @@ + +import AVFoundation +import VideoToolbox + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// VideoInput +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class VideoInput : NSObject, AVCaptureVideoDataOutputSampleBufferDelegate, VideoSessionProtocol { + + var sessionAccessor: AVCaptureSession.Accessor { + get { + weak var SELFW = self + + return { (_ x: (AVCaptureSession) throws -> Void) in + guard let SELF = SELFW else { return } + guard let session = SELF.session else { return } + + try x(session) + } + } + } + + private var session: AVCaptureSession? + private var format: AVCaptureDeviceFormat + private let output: VideoOutputProtocol? + private let outputQueue: DispatchQueue? + private let device: AVCaptureDevice? + private var connection_: AVCaptureConnection? + + init(_ device: AVCaptureDevice?, + _ outputQueue: DispatchQueue?, + _ format: AVCaptureDeviceFormat, + _ output: VideoOutputProtocol?) { + self.output = output + self.outputQueue = outputQueue + self.device = device + self.format = format + + super.init() + initSession() + } + + func initSession() { + guard let device = self.device else { return } + + session = AVCaptureSession() + + // output + + do { + let videoDeviceInput = try AVCaptureDeviceInput(device: device) + + if (session!.canAddInput(videoDeviceInput) == true) { + session!.addInput(videoDeviceInput) + } + + try device.lockForConfiguration() + let fps = CMTime(value: 1, timescale: 10) + device.activeFormat = format + device.activeVideoMinFrameDuration = fps + device.activeVideoMaxFrameDuration = fps + device.unlockForConfiguration() + + let videoDataOutput = AVCaptureVideoDataOutput() + + videoDataOutput.setSampleBufferDelegate(self, queue: outputQueue) + videoDataOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as AnyHashable: Int(kCVPixelFormatType_32BGRA)] + videoDataOutput.alwaysDiscardsLateVideoFrames = true + + if (session!.canAddOutput(videoDataOutput) == true) { + session!.addOutput(videoDataOutput) + connection_ = videoDataOutput.connection(withMediaType: AVMediaTypeVideo) + } + } catch { + logIOError(error) + stop() + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // IOSessionProtocol + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + func start() throws { + assert_video_capture_queue() + logIOPrior("video input start") + + NotificationCenter.default.addObserver( + forName: .AVSampleBufferDisplayLayerFailedToDecode, + object: nil, + queue: nil, + using: failureNotification) + + try device?.lockForConfiguration() + + try dispatch_sync_on_main { + try sessionAccessor({ (_ session: AVCaptureSession) throws in + session.startRunning() + }) + } + } + + func stop() { + assert_video_capture_queue() + logIOPrior("video input stop") + + session?.stopRunning() + session = nil + device?.unlockForConfiguration() + } + + func update(_ outputFormat: VideoFormat) throws { + // don't change input dimensions because we also showing preview + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // AVCaptureVideoDataOutputSampleBufferDelegate and failure notification + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + func formatNotChanged(_ sampleBuffer: CMSampleBuffer) -> Bool { + let sampleDimentions = CMVideoFormatDescriptionGetDimensions(CMSampleBufferGetFormatDescription(sampleBuffer)!) + + return format.dimensions == sampleDimentions || format.dimensions == sampleDimentions.turn() + } + + func captureOutput(_ captureOutput: AVCaptureOutput!, + didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, + from connection: AVCaptureConnection!) { + + assert(formatNotChanged(sampleBuffer)) + logIO("video input \(sampleBuffer.seconds())") + +// #if os(iOS) + self.output?.process(sampleBuffer) +// #else +// AV.shared.videoCaptureQueue.asyncAfter0_5 { self.output?.process(sampleBuffer) } +// #endif + } + + func failureNotification(notification: Notification) { + logIOError("failureNotification " + notification.description) + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// VideoPreview +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class VideoPreview : VideoSession { + + let layer: AVCaptureVideoPreviewLayer + let session: AVCaptureSession.Accessor + + convenience init(_ layer: AVCaptureVideoPreviewLayer, + _ session: @escaping AVCaptureSession.Accessor) { + self.init(layer, session, nil) + } + + init(_ layer: AVCaptureVideoPreviewLayer, + _ session: @escaping AVCaptureSession.Accessor, + _ next: VideoSessionProtocol?) { + self.layer = layer + self.session = session + super.init(next) + } + + override func start() throws { + logIOPrior("video preview start") + + try dispatch_sync_on_main { + try session({ (session: AVCaptureSession) in + layer.session = session + layer.connection.automaticallyAdjustsVideoMirroring = false + layer.connection.isVideoMirrored = false + }) + } + + try super.start() + } + + override func stop() { + logIOPrior("video preview stop") + + super.stop() + + dispatch_sync_on_main { + layer.session = nil + } + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// VideoInputQoS +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class VideoInputQoS : IOQoSProtocol { + + let input: VideoSessionProtocol + let format: AVCaptureDeviceFormat + var dimensions: CMVideoDimensions + + init(_ format: AVCaptureDeviceFormat, _ input: VideoSessionProtocol) { + self.input = input + self.format = format + self.dimensions = format.dimensions + } + + func change(_ toQID: String, _ diff: Int) { + guard diff != IOQoS.kInit else { return } + + do { + let dimensions = CMVideoDimensions(width: self.dimensions.width / 2, + height: self.dimensions.height / 2) + + if dimensions.width > 100 { + try input.update(VideoFormat(dimensions)) + self.dimensions = dimensions + + logIOPrior("video quality changed to \(dimensions.width) * \(dimensions.height)") + } + else { + + } + } + catch { + logIOError(error) + } + } +} diff --git a/apple/Common/IO/VideoOutput.swift b/apple/Common/IO/VideoOutput.swift new file mode 100644 index 0000000..ce2af7e --- /dev/null +++ b/apple/Common/IO/VideoOutput.swift @@ -0,0 +1,64 @@ +// +// VideoOutput.swift +// Chat +// +// Created by Ivan Khvorostinin on 06/06/2017. +// Copyright © 2017 ys1382. All rights reserved. +// + +import AVFoundation + +class VideoOutput : VideoOutputProtocol, IOSessionProtocol { + + let layer: AVSampleBufferDisplayLayer + var format: CMFormatDescription? + + init(_ layer: AVSampleBufferDisplayLayer) { + self.layer = layer + } + + func printStatus() { + if layer.status == .failed { + logIOError("AVQueuedSampleBufferRenderingStatus failed") + } + if let error = layer.error { + logIOError(error.localizedDescription) + } + if !layer.isReadyForMoreMediaData { + logIOError("Video layer not ready for more media data") + } + } + + func start() throws { + logIOPrior("video output start") + layer.flushAndRemoveImage() + } + + func stop() { + logIOPrior("video output stop") + layer.flushAndRemoveImage() + } + + func process(_ data: CMSampleBuffer) { + assert_av_output_queue() + logIO("video output \(data.seconds())") + + let dataFormat = CMSampleBufferGetFormatDescription(data) + + if CMFormatDescriptionEqual(format, dataFormat) == false { + layer.flush() + } + + format = dataFormat + + dispatch_sync_on_main { + if self.layer.isReadyForMoreMediaData && self.layer.status != .failed { + self.layer.enqueue(data) + } + else { + self.printStatus() + self.layer.flush() + } + } + } +} diff --git a/apple/common/Model.swift b/apple/Common/Model.swift similarity index 97% rename from apple/common/Model.swift rename to apple/Common/Model.swift index d1219b8..0dc52c4 100644 --- a/apple/common/Model.swift +++ b/apple/Common/Model.swift @@ -27,7 +27,7 @@ class Model { func didReceiveText(_ haber: Haber) { let from = haber.from if haber.from != self.watching { - self.unreads[from] = (self.unreads[from] ?? 0) + 1 + self.unreads[from!] = (self.unreads[from!] ?? 0) + 1 } self.texts.append(haber) self.post(about:.text) diff --git a/apple/Common/Network/Network.swift b/apple/Common/Network/Network.swift new file mode 100644 index 0000000..2e0af4e --- /dev/null +++ b/apple/Common/Network/Network.swift @@ -0,0 +1,143 @@ + +import Foundation + +class NetworkIOSessionInfo { + let id: IOID + let formatData: NSData.Factory? + + init(_ id: IOID) { + self.id = id + formatData = nil + } + + init(_ id: IOID, _ format: NSData.Factory?) { + self.id = id + self.formatData = format + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Logs +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +func logNetwork(_ message: String) { + logMessage("Network", message) +} + +func logNetworkPrior(_ message: String) { + logPrior("Network", message) +} + +func logNetworkError(_ message: String) { + logError("Network", message) +} + +func logNetworkError(_ error: Error) { + logError("Network", error) +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Serialization +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class NetworkDeserializer { + + static let timeIndex = 0 + static let qosIDIndex = 1 + static let dataIndex = 2 + + private let _data: NSData + + init(_ data: NSData) { + self._data = data + } + + var time: PacketDeserializer { + get { + return PacketDeserializer(_data, NetworkDeserializer.timeIndex) + } + } + + var qosID: PacketDeserializer { + get { + return PacketDeserializer(_data, NetworkDeserializer.qosIDIndex) + } + } + + var data: PacketDeserializer { + get { + return PacketDeserializer(_data, NetworkDeserializer.dataIndex) + } + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// NetworkInput +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class NetworkInput { + + private var output = [String: IODataProtocol]() + + func add(_ sid: String, _ output: IODataProtocol) { + self.output[sid] = output + } + + func remove(_ sid: String) { + output.removeValue(forKey: sid) + } + + func removeAll() { + self.output.removeAll() + } + + func process(_ sid: String, _ data: NSData) { + guard output.keys.contains(sid) else { return } + output[sid]?.process(data) + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// NetworkOutput +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class NetworkOutput : IODataProtocol { + + struct _Item { + let time: Double + let qosID: String + } + + let id: IOID + + private let qos: IOQoS + private let balancer: IOQoSBalancerProtocol + private var queue = [UUID: _Item]() + + init(_ id: IOID, _ qos: IOQoS, _ balancer: IOQoSBalancerProtocol) { + self.id = id + self.qos = qos + self.balancer = balancer + } + + func process(_ dataID: UUID, _ data: NSData) { + + } + + func process(_ data: NSData) { + let dataID = UUID() + + queue[dataID] = _Item(time: mach_absolute_seconds(), + qosID: NetworkDeserializer(data).qosID.popString()) + + process(dataID, data) + } + + func processed(_ id: UUID) { + let item = queue[id]! + let gap = mach_absolute_seconds() - item.time + + balancer.process(item.qosID, gap) + queue.removeValue(forKey: id) + } +} diff --git a/apple/Common/Network/NetworkAudio.swift b/apple/Common/Network/NetworkAudio.swift new file mode 100644 index 0000000..6f3350e --- /dev/null +++ b/apple/Common/Network/NetworkAudio.swift @@ -0,0 +1,145 @@ + +import AudioToolbox + +class NetworkAudioSessionInfo : NetworkIOSessionInfo { + let format: AudioFormat.Factory? + + init(_ id: IOID, _ format: @escaping AudioFormat.Factory) { + self.format = format + super.init(id, data(format)) + } + + override init(_ id: IOID) { + format = nil + super.init(id) + } + + override init(_ id: IOID, _ format: NSData.Factory?) { + if format != nil { + self.format = audioFormat(format!) + } + else { + self.format = nil + } + super.init(id, format) + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// NetworkAudioSerializer +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class NetworkAudioSerializer : AudioOutputProtocol, IOQoSProtocol { + + private let output: IODataProtocol? + private var qid: String = "" + + init(_ output: IODataProtocol?) { + self.output = output + } + + func change(_ toQID: String, _ diff: Int) { + self.qid = toQID + } + + func process(_ packet: AudioData) { + + let s = PacketSerializer() + var t = AudioTime(packet.time) + + s.push(&t, MemoryLayout.size) + s.push(string: qid) + s.push(packet.data.bytes, packet.data.length) + s.push(array: packet.desc) + + output?.process(s.data) + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// NetworkAudioDeserializer +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class NetworkAudioDeserializer : IODataProtocol { + + private let output: AudioOutputProtocol? + + init(_ output: AudioOutputProtocol) { + self.output = output + } + + func process(_ data: NSData) { + + let deserializer = PacketDeserializer(data) + var time = AudioTime() + var data: NSData? + var desc: [AudioStreamPacketDescription]? + + deserializer.pop(&time) + _ = deserializer.popSkip() + deserializer.pop(data: &data) + deserializer.pop(array: &desc) + + output?.process(AudioData(time.ToAudioTimeStamp(), data!, desc)) + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Audio format +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +extension AudioFormat { + + func toNetwork() throws -> NSData { + return try JSONSerialization.data(withJSONObject: format.data, + options: JSONSerialization.defaultWritingOptions) as NSData + } + + static func fromNetwork(_ data: NSData) throws -> AudioFormat { + let json = try JSONSerialization.jsonObject(with: data as Data, + options: JSONSerialization.ReadingOptions()) as! [String: Any] + return AudioFormat(IOFormat(json)) + } +} + +func data(_ src: @escaping AudioFormat.Factory) -> NSData.Factory { + return { return try src().toNetwork() } +} + +func audioFormat(_ src: @escaping NSData.Factory) -> AudioFormat.Factory { + return { return try AudioFormat.fromNetwork(src()) } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// NetworkOutputAudio +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class NetworkOutputAudio : NetworkOutput { + + override func process(_ dataID: UUID, _ data: NSData) { + Backend.shared.sendAudio(id, data) { + self.processed(dataID) + } + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// NetworkOutputAudioSession +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class NetworkOutputAudioSession : IOSessionProtocol { + + let info: NetworkAudioSessionInfo + + init(_ info: NetworkAudioSessionInfo) { + self.info = info + } + + func start() throws { + Backend.shared.sendAudioSession(info, true) + } + + func stop() { + Backend.shared.sendAudioSession(info, false) + } +} diff --git a/apple/Common/Network/NetworkBalancer.swift b/apple/Common/Network/NetworkBalancer.swift new file mode 100644 index 0000000..20ec28d --- /dev/null +++ b/apple/Common/Network/NetworkBalancer.swift @@ -0,0 +1,68 @@ + +import Foundation + +class NetworkBalancer : IOQoSBalancerProtocol { + + private static let kGapCount = 3 // number packets for tuning + private static let kGapMax = 1.5 + + private var qid: String? + private var qidObsolete: Bool = true + + var gaps = [Double]() + + func process(_ qosID: String, _ gap: Double) { + _update(qosID, gap) + } + + fileprivate func change(_ diff: Int) { + + } + + private func _update(_ qosID: String, _ gap: Double) { + + if qidObsolete && self.qid != qosID { + self.qid = qosID + qidObsolete = false + } + + _update(gap) + } + + private func _update(_ gap: Double) { + gaps.append(gap) + + if gaps.count > NetworkBalancer.kGapCount { + gaps.removeFirst() + } + else { + return + } + + for i in gaps { + if i < NetworkBalancer.kGapMax { + return + } + } + + if qidObsolete == false { + qidObsolete = true + change(IOQoS.kDecrease) + } + } +} + +class NetworkCallQuality : NetworkBalancer { + + let to: String + let call: NetworkCallInfo + + init(_ to: String, _ call: NetworkCallInfo) { + self.to = to + self.call = call + } + + override func change(_ diff: Int) { + changeCallQuality(call, diff) + } +} diff --git a/apple/Common/Network/NetworkCall.swift b/apple/Common/Network/NetworkCall.swift new file mode 100644 index 0000000..328cbf5 --- /dev/null +++ b/apple/Common/Network/NetworkCall.swift @@ -0,0 +1,510 @@ + +import Foundation + +extension DispatchQueue { + static let networkCall = DispatchQueue.CreateCheckable("chat.NetworkCallQueue") +} + +func assert_network_call_queue() { + assert(DispatchQueue.OnQueue(DispatchQueue.networkCall)) +} + +func dispatch_async_network_call(_ block: @escaping FuncVV) { + DispatchQueue.networkCall.async { block() } +} + +class NetworkCallSessionController { + + fileprivate func create(_ info: I) -> T? { + assert(false) + return nil + } + + fileprivate func id(_ info: I) -> String { + assert(false) + return "" + } + + fileprivate func call(_ info: I) -> T? { + assert(false) + return nil + } + + func start(_ info: I) { + assert_network_call_queue() + } + + func stop(_ info: I) { + assert_network_call_queue() + } +} + +class NetworkSingleCallSessionController : NetworkCallSessionController { + + var call: T? + var callInfo: I? + + override func start(_ info: I) { + super.start(info) + + stop() + call = create(info) + callInfo = info + do { try call?.start() } catch { logNetworkError(error) } + } + + override func stop(_ info: I) { + assert_network_call_queue() + + guard let callInfo = self.callInfo else { return } + guard id(callInfo) == id(info) else { return } + + call?.stop() + + self.call = nil + self.callInfo = nil + } + + func stop() { + guard callInfo != nil else { return } + stop(callInfo!) + } + + fileprivate override func call(_ info: I) -> T? { + guard let callInfo = self.callInfo else { return nil } + guard id(callInfo) == id(info) else { return nil } + + return call + } +} + +class NetworkMultiCallSessionController : NetworkCallSessionController { + + private var calls = [String: T]() + + override func start(_ info: I) { + super.start(info) + + let call = create(info) + calls[id(info)] = call + do { try call!.start() } catch { logNetworkError(error) } + } + + override func stop(_ info: I) { + assert_network_call_queue() + + calls[id(info)]?.stop() + calls.removeValue(forKey: id(info)) + } + + fileprivate override func call(_ info: I) -> T? { + return calls[id(info)] + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Call +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +struct NetworkCallInfo { + + let proposal: NetworkCallProposalInfo + let audioSession: NetworkAudioSessionInfo? + let videoSession: NetworkVideoSessionInfo? + + init(_ proposal: NetworkCallProposalInfo, + _ audioSession: NetworkAudioSessionInfo?, + _ videoSession: NetworkVideoSessionInfo?) { + self.proposal = proposal + self.audioSession = audioSession + self.videoSession = videoSession + } + + init(_ proposal: NetworkCallProposalInfo, audioSession: NetworkAudioSessionInfo) { + self.init(proposal, audioSession, nil) + } + + init(_ proposal: NetworkCallProposalInfo, videoSession: NetworkVideoSessionInfo) { + self.init(proposal, nil, videoSession) + } + + init(_ proposal: NetworkCallProposalInfo) { + self.init(proposal, nil, nil) + } + + var id: String { get { return proposal.id } } + var from: String { get { return proposal.from } } + var to: String { get { return proposal.to } } +} + +protocol NetworkCallProtocol : SessionProtocol { + +} + +protocol NetworkCallReceiverProtocol { + var callInfo: NetworkCallInfo? { get set } +} + +typealias NetworkCallFactory = (NetworkCallInfo) -> NetworkCallProtocol + +class NetworkCall : NetworkCallProtocol { + + let info: NetworkCallInfo + private var ui: NetworkCallReceiverProtocol? + + private(set) var inputContext: IOInputContext? + private var audioInputSession: IOSessionProtocol? + private var videoInputSession: IOSessionProtocol? + + private(set) var outputContext: IOOutputContext? + private var audioOutputContext: IOOutputContext? + private var videoOutputContext: IOOutputContext? + + init(_ info: NetworkCallInfo) { + self.info = info + } + + convenience init(_ info: NetworkCallInfo, _ ui: NetworkCallReceiverProtocol) { + self.init(info) + self.ui = ui + } + + func counterpart() -> String { + return info.from + } + + func start() throws { + assert_network_call_queue() + + outputContext = IOOutputContext() + inputContext = IOInputContext(NetworkCallQuality(counterpart(), info)) + + dispatch_sync_on_main { ui?.callInfo = info } + _ = try startCapture(info.from, info.to) + } + + func stop() { + assert_network_call_queue() + dispatch_sync_on_main { ui?.callInfo = nil } + + audioInputSession?.stop() + AV.shared.videoCaptureQueue.sync { videoInputSession?.stop() } + AV.shared.avOutputQueue.sync { audioOutputContext?.session?.stop() } + AV.shared.avOutputQueue.sync { videoOutputContext?.session?.stop() } + } + + func audioOutput(_ info: NetworkAudioSessionInfo, _ context: IOOutputContext) throws -> IOOutputContext? { + return AV.shared.defaultNetworkAudioOutput(info.id, try info.format!(), context) + } + + func videoOutput(_ info: NetworkVideoSessionInfo, _ context: IOOutputContext) throws -> IOOutputContext? { + return nil + } + + fileprivate func startOutput(_ info: NetworkAudioSessionInfo) throws -> IODataProtocol? { + audioOutputContext = try audioOutput(info, outputContext!) + try AV.shared.avOutputQueue.sync { try audioOutputContext?.session?.start() } + return audioOutputContext?.data + } + + fileprivate func startOutput(_ info: NetworkVideoSessionInfo) throws -> IODataProtocol? { + videoOutputContext = try videoOutput(info, outputContext!) + try AV.shared.avOutputQueue.sync { try videoOutputContext?.session?.start() } + return videoOutputContext?.data + } + + func audioCapture(_ id: IOID, _ info: inout NetworkAudioSessionInfo?) -> IOSessionProtocol? { + return AV.shared.defaultNetworkAudioInput(id, inputContext!, &info) + } + + func videoCapture(_ id: IOID, _ info: inout NetworkVideoSessionInfo?) -> IOSessionProtocol? { + return nil + } + + fileprivate func startCapture(_ from: String, _ to: String) throws -> NetworkCallInfo { + let audioID = IOID(from, to) + let videoID = audioID.groupNew() + + let audio = info.proposal.audio ? try startAudioCapture(audioID) : nil + let video = info.proposal.video ? try startVideoCapture(videoID) : nil + + return NetworkCallInfo(info.proposal, audio, video) + } + + fileprivate func startAudioCapture(_ id: IOID) throws -> NetworkAudioSessionInfo? { + var info: NetworkAudioSessionInfo? + + audioInputSession = audioCapture(id, &info) + try audioInputSession?.start() + + return info + } + + fileprivate func startVideoCapture(_ id: IOID) throws -> NetworkVideoSessionInfo? { + var info: NetworkVideoSessionInfo? + + videoInputSession = videoCapture(id, &info) + try videoInputSession?.start() + + return info + } +} + +class NetworkOutgoingCall : NetworkCall { + + override fileprivate func startCapture(_ from: String, _ to: String) throws -> NetworkCallInfo { + let info = try super.startCapture(from, to) + Backend.shared.sendOutgoingCallStart(info.to, info) + return info + } + + override func stop() { + super.stop() + Backend.shared.sendCallStop(info.to, info) + } +} + +class NetworkIncomingCall : NetworkCall { + + override func counterpart() -> String { + return info.to + } + + override fileprivate func startCapture(_ from: String, _ to: String) throws -> NetworkCallInfo { + var info = self.info + + if info.from != info.to { + info = try super.startCapture(to, from) + Backend.shared.sendIncomingCallStart(info.from, info) + } + return info + } + + override func stop() { + super.stop() + Backend.shared.sendCallStop(info.from, info) + } +} + +class NetworkCallController : NetworkSingleCallSessionController { + + static var incoming: NetworkCallController? + static var outgoing: NetworkCallController? + + private let factory: NetworkCallFactory + + init(_ factory: @escaping NetworkCallFactory) { + self.factory = factory + } + + override func id(_ info: NetworkCallInfo) -> String { + return info.id + } + + override func create(_ info: NetworkCallInfo) -> NetworkCall? { + return factory(info) as? NetworkCall + } + + func startOutput(_ call: NetworkCallInfo, _ audio: inout IODataProtocol?, _ video: inout IODataProtocol?) throws { + assert_network_call_queue() + guard self.callInfo?.id == call.id else { print("asd"); return } + + if call.audioSession != nil { + audio = try self.call?.startOutput(call.audioSession!) + } + + if call.videoSession != nil { + video = try self.call?.startOutput(call.videoSession!) + } + } + + func changeQuality(_ info: NetworkCallInfo, _ diff: Int) { + call(info)?.inputContext?.qos.change(diff) + } +} + +func changeCallQuality(_ call: NetworkCallInfo, _ diff: Int) { + NetworkCallController.incoming?.changeQuality(call, diff) + NetworkCallController.outgoing?.changeQuality(call, diff) +} + +func stopCallAsync(_ info: NetworkCallInfo) { + dispatch_async_network_call { + NetworkCallController.incoming?.stop(info) + NetworkCallController.outgoing?.stop(info) + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Proposal +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +struct NetworkCallProposalInfo { + let id: String + let from: String + let to: String + let audio: Bool + let video: Bool + + init(_ id: String, + _ from: String, + _ to: String, + _ audio: Bool, + _ video: Bool) { + self.id = id + self.from = from + self.to = to + self.audio = audio + self.video = video + } +} + +protocol NetworkCallProposalProtocol : SessionProtocol { + + func accept(_ info: NetworkCallProposalInfo) + func decline() +} + +protocol NetworkCallProposalReceiverProtocol { + var callInfo: NetworkCallProposalInfo? { get set } +} + +typealias NetworkCallProposalFactory = (NetworkCallProposalInfo) -> NetworkCallProposalProtocol + +class NetworkCallProposal : NetworkCallProposalProtocol { + + var info: NetworkCallProposalInfo + private var ui: NetworkCallProposalReceiverProtocol? + + init(_ info: NetworkCallProposalInfo) { + self.info = info + } + + init(_ info: NetworkCallProposalInfo, _ ui: NetworkCallProposalReceiverProtocol) { + self.ui = ui + self.info = info + } + + func start() throws { + assert_network_call_queue() + dispatch_sync_on_main { ui?.callInfo = info } + } + + func stop() { + assert_network_call_queue() + dispatch_sync_on_main { ui?.callInfo = nil } + } + + func accept(_ info: NetworkCallProposalInfo) { + assert_network_call_queue() + self.info = info + dispatch_sync_on_main { ui?.callInfo = nil } + } + + func decline() { + assert_network_call_queue() + dispatch_sync_on_main { ui?.callInfo = nil } + } +} + +class NetworkOutgoingCallProposal : NetworkCallProposal { + + override func start() throws { + try super.start() + + Backend.shared.sendCallProposal(info.to, info) + } + + override func stop() { + super.stop() + Backend.shared.sendCallCancel(info.to, info) + } + + override func accept(_ info: NetworkCallProposalInfo) { + super.accept(info) + NetworkCallController.outgoing?.start(NetworkCallInfo(info)) + } +} + +class NetworkIncomingCallProposal : NetworkCallProposal { + + override func stop() { + super.stop() + Backend.shared.sendCallCancel(info.from, info) + } + + override func accept(_ info: NetworkCallProposalInfo) { + super.accept(info) + Backend.shared.sendCallAccept(info.from, info) + } + + override func decline() { + super.decline() + Backend.shared.sendCallDecline(info.from, info) + } +} + +class NetworkCallProposalController : NetworkSingleCallSessionController { + + static var incoming: NetworkCallProposalController? + static var outgoing: NetworkCallProposalController? + + private let factory: NetworkCallProposalFactory + + init(_ factory: @escaping NetworkCallProposalFactory) { + self.factory = factory + } + + override func create(_ info: NetworkCallProposalInfo) -> NetworkCallProposal? { + return factory(info) as? NetworkCallProposal + } + + override func id(_ info: NetworkCallProposalInfo) -> String { + return info.id + } + + override func start(_ info: NetworkCallProposalInfo) { + super.start(info) + + DispatchQueue.networkCall.asyncAfter(deadline: .now() + 10) { + self.timeout(info) + } + } + + func accept(_ info: NetworkCallProposalInfo) { + call?.accept(info) + call = nil + } + + func decline(_ info: NetworkCallProposalInfo) { + call?.decline() + call = nil + } + + func timeout(_ info: NetworkCallProposalInfo) { + stop(info) + } +} + +private func callAsync(_ to: String, _ audio: Bool, _ video: Bool) -> NetworkCallProposalInfo { + let info = NetworkCallProposalInfo(UUID().uuidString, + Model.shared.username!, + to, + audio, + video) + + dispatch_async_network_call { + NetworkCallProposalController.outgoing?.start(info) + } + + return info +} + +func callAudioAsync(_ to: String) -> NetworkCallProposalInfo { + return callAsync(to, true, false) +} + +func callVideoAsync(_ to: String) -> NetworkCallProposalInfo { + return callAsync(to, true, true) +} + diff --git a/apple/Common/Network/NetworkH264.swift b/apple/Common/Network/NetworkH264.swift new file mode 100644 index 0000000..ba1e3fb --- /dev/null +++ b/apple/Common/Network/NetworkH264.swift @@ -0,0 +1,292 @@ + +import AVFoundation + +class NetworkVideoSessionInfo : NetworkIOSessionInfo { + let format: VideoFormat.Factory? + + init(_ id: IOID, _ format: @escaping VideoFormat.Factory) { + self.format = format + super.init(id, data(format)) + } + + override init(_ id: IOID) { + format = nil + super.init(id) + } + + override init(_ id: IOID, _ format: NSData.Factory?) { + if format != nil { + self.format = videoFormat(format!) + } + else { + self.format = nil + } + super.init(id, format) + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// NetworkH264Serializer +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class NetworkH264Serializer : VideoOutputProtocol, IOQoSProtocol { + + private let output: IODataProtocol? + private var qid: String = "" + + init(_ output: IODataProtocol) { + + self.output = output + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // IOQoSProtocol + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + func change(_ toQID: String, _ diff: Int) { + self.qid = toQID + } + + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // VideoOutputProtocol + //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + func process(_ sampleBuffer: CMSampleBuffer) { + do { + let formatDescription: CMFormatDescription = CMSampleBufferGetFormatDescription(sampleBuffer)! + + assert(CMSampleBufferGetNumSamples(sampleBuffer) == 1) + + // timing info + + var timingInfo = CMSampleTimingInfo() + + try checkStatus(CMSampleBufferGetSampleTimingInfo(sampleBuffer, + 0, + &timingInfo), + "CMSampleBufferGetSampleTimingInfo failed") + + // H264 description (SPS) + + var sps: UnsafePointer? + var spsLength: Int = 0 + var count: Int = 0 + + try checkStatus(CMVideoFormatDescriptionGetH264ParameterSetAtIndex(formatDescription, + 0, + &sps, + &spsLength, + &count, + nil), + "An Error occured while getting h264 sps parameter") + + assert(count == 2) // sps and pps + + // H264 description (PPS) + + var pps: UnsafePointer? + var ppsLength: Int = 0 + + try checkStatus(CMVideoFormatDescriptionGetH264ParameterSetAtIndex(formatDescription, + 1, + &pps, + &ppsLength, + &count, + nil), + "An Error occured while getting h264 pps parameter") + + assert(count == 2) // sps and pps + + // H264 data + + let blockBuffer = CMSampleBufferGetDataBuffer(sampleBuffer) + var totalLength = Int() + var length = Int() + var dataPointer: UnsafeMutablePointer? = nil + + try checkStatus(CMBlockBufferGetDataPointer(blockBuffer!, + 0, + &length, + &totalLength, + &dataPointer), "CMBlockBufferGetDataPointer failed") + + assert(length == totalLength) + + // build data + + let s = PacketSerializer() + + s.push(data: VideoTime(timingInfo).ToNSData()) + s.push(string: qid) + s.push(data: NSData(bytes: sps!, length: spsLength)) + s.push(data: NSData(bytes: pps!, length: ppsLength)) + s.push(data: NSData(bytes: dataPointer!, length: Int(totalLength))) + + // output + + AV.shared.videoCaptureQueue.async { self.output?.process(s.data) } + } + catch { + logIOError(error) + } + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// NetworkH264Deserializer +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class NetworkH264Deserializer : IODataProtocol, IOBalancedDataProtocol { + + private let output: VideoOutputProtocol? + + init(_ output: VideoOutputProtocol?) { + self.output = output + } + + func tuning(_ data: NSData) { + process(data) + } + + func belated(_ data: NSData) { + process(data) + } + + func process(_ data: NSData) { + + let d = PacketDeserializer(data) + + let h264Time = d.popData() + _ = d.popSkip() // QoS ID + let h264SPS = d.popData() + let h264PPS = d.popData() + let h264Data = d.popData() + + do { + // format description + + var formatDescription: CMFormatDescription? + + let parameterSetPointers : [UnsafePointer] = [h264SPS.bytes.assumingMemoryBound(to: UInt8.self), + h264PPS.bytes.assumingMemoryBound(to: UInt8.self)] + let parameterSetSizes : [Int] = [h264SPS.length, + h264PPS.length] + + try checkStatus(CMVideoFormatDescriptionCreateFromH264ParameterSets(kCFAllocatorDefault, + 2, + parameterSetPointers, + parameterSetSizes, + 4, + &formatDescription), + "CMVideoFormatDescriptionCreateFromH264ParameterSets failed") + + // block buffer + + var blockBuffer: CMBlockBuffer? + let blockBufferData = UnsafeMutablePointer.allocate(capacity: h264Data.length) + blockBufferData.assign(from: h264Data.bytes.assumingMemoryBound(to: Int8.self), count: h264Data.length) + + try checkStatus(CMBlockBufferCreateWithMemoryBlock(kCFAllocatorDefault, + blockBufferData, + h264Data.length, + kCFAllocatorDefault, + nil, + 0, + h264Data.length, + 0, + &blockBuffer), "createReadonlyBlockBuffer") + + // timing info + + var timingInfo = VideoTime(deserialize: h264Time).ToCMSampleTimingInfo() + + // sample buffer + + var sampleBuffer : CMSampleBuffer? + try checkStatus(CMSampleBufferCreateReady(kCFAllocatorDefault, + blockBuffer, + formatDescription, + 1, + 1, + &timingInfo, + 0, + nil, + &sampleBuffer), "CMSampleBufferCreateReady failed") + + // output + + output?.process(sampleBuffer!) + } + catch { + logIOError(error) + } + } + +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Video format +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +extension VideoFormat { + + func toNetwork() throws -> NSData { + return try JSONSerialization.data(withJSONObject: format.data, + options: JSONSerialization.defaultWritingOptions) as NSData + } + + static func fromNetwork(_ data: NSData) throws -> VideoFormat { + let json = try JSONSerialization.jsonObject(with: data as Data, + options: JSONSerialization.ReadingOptions()) as! [String: Any] + return VideoFormat(IOFormat(json)) + } +} + +func data(_ src: @escaping VideoFormat.Factory) -> NSData.Factory { + return { return try src().toNetwork() } +} + +func videoFormat(_ src: @escaping NSData.Factory) -> VideoFormat.Factory { + return { return try VideoFormat.fromNetwork(src()) } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// NetworkOutputVideo +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class NetworkOutputVideo : NetworkOutput { + + override func process(_ dataID: UUID, _ data: NSData) { + Backend.shared.sendVideo(id, data) { + self.processed(dataID) + } + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// NetworkOutputVideoSession +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class NetworkOutputVideoSession : VideoSessionProtocol { + + let id: IOID + let format: VideoFormat + + init(_ id: IOID, _ format: VideoFormat) { + self.id = id + self.format = format + } + + func start() throws { + Backend.shared.sendVideoSession(NetworkVideoSessionInfo(id, factory(format)), true) + } + + func update(_ format: VideoFormat) throws { + // TODO: send update format + } + + func stop() { + Backend.shared.sendVideoSession(NetworkVideoSessionInfo(id), false) + } +} + diff --git a/apple/Common/Types.swift b/apple/Common/Types.swift new file mode 100644 index 0000000..627451c --- /dev/null +++ b/apple/Common/Types.swift @@ -0,0 +1,7 @@ + +import Foundation + +protocol SessionProtocol { + func start () throws + func stop() +} diff --git a/apple/Common/Utils/AVFoundation.swift b/apple/Common/Utils/AVFoundation.swift new file mode 100644 index 0000000..477b7fd --- /dev/null +++ b/apple/Common/Utils/AVFoundation.swift @@ -0,0 +1,173 @@ + +import AVFoundation + +extension AVCaptureDeviceFormat { + + var dimensions: CMVideoDimensions { + get { + return CMVideoFormatDescriptionGetDimensions(formatDescription) + } + } + + var mediaSubtype:FourCharCode { + get { + return CMFormatDescriptionGetMediaSubType(formatDescription) + } + } +} + +extension AVCaptureDevice { + + static func chatVideoDevice() -> AVCaptureDevice? { + #if os(iOS) + for i in AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo) { + if (i as! AVCaptureDevice).position == .front { + return i as? AVCaptureDevice + } + } + + return nil + #else + return AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) + #endif + } + + func inputFormat(width: Int32) -> AVCaptureDeviceFormat? { + + var result: AVCaptureDeviceFormat? = nil + var diff: Int32 = 0 + + for ii in formats { + let i = ii as! AVCaptureDeviceFormat + let i_diff = Int32(width) - i.dimensions.width + + if result == nil || abs(diff) > abs(i_diff) { + result = i + diff = i_diff + } + } + + return result + } + + func inputFormat(height: Int32) -> AVCaptureDeviceFormat? { + + var result: AVCaptureDeviceFormat? = nil + var diff: Int32 = 0 + + for ii in formats { + let i = ii as! AVCaptureDeviceFormat + let i_diff = Int32(height) - i.dimensions.height + + if result == nil || abs(diff) > abs(i_diff) { + result = i + diff = i_diff + } + } + + return result + } +} + +extension AVCaptureConnection { + + typealias Accessor = ((AVCaptureConnection) throws -> Void) throws -> Void +} + +extension AVCaptureSession { + + typealias Accessor = ((AVCaptureSession) throws -> Void) throws -> Void +} + +extension AVCaptureVideoOrientation { + + var isPortrait: Bool { + get { + return self == AVCaptureVideoOrientation.portrait || self == AVCaptureVideoOrientation.portraitUpsideDown + } + } + + var isLandscape: Bool { + get { + return self == AVCaptureVideoOrientation.landscapeLeft || self == AVCaptureVideoOrientation.landscapeRight + } + } + + func rotates(_ to: AVCaptureVideoOrientation) -> Bool { + if self.isLandscape && to.isPortrait { + return true + } + + if self.isPortrait && to.isLandscape { + return true + } + + return false + } + +} + +private class _AVCaptureVideoPreviewLayer : AVCaptureVideoPreviewLayer { + + override var session: AVCaptureSession! { + didSet { + setNeedsLayout() + } + } +} + +class CaptureVideoPreviewView : AppleView { + + #if os(iOS) + override open class var layerClass: Swift.AnyClass { + return _AVCaptureVideoPreviewLayer.self + } + #else + override func makeBackingLayer() -> CALayer { + return _AVCaptureVideoPreviewLayer() + } + #endif + + var captureLayer: AVCaptureVideoPreviewLayer { + get { + return layer as! AVCaptureVideoPreviewLayer + } + } +} + +class SampleBufferDisplayView : AppleView { + + #if os(iOS) + override open class var layerClass: Swift.AnyClass { + return AVSampleBufferDisplayLayer.self + } + #else + override func makeBackingLayer() -> CALayer { + return AVSampleBufferDisplayLayer() + } + #endif + + var sampleLayer: AVSampleBufferDisplayLayer { + get { + + return layer as! AVSampleBufferDisplayLayer + } + } +} + +func videoConnection(_ layer: AVCaptureVideoPreviewLayer) -> AVCaptureConnection.Accessor { + return { (_ x: (AVCaptureConnection) throws -> Void) in + try x(layer.connection) + } +} + +func videoConnection(_ session: AVCaptureSession.Accessor?) -> AVCaptureConnection.Accessor? { + return { (_ x: (AVCaptureConnection) throws -> Void) in + try session?({ (_ session: AVCaptureSession) throws in + guard let output = session.outputs.first as? AVCaptureOutput else { return } + guard let _ = output.connections.first else { return } + + try x(output.connection(withMediaType: AVMediaTypeVideo)) + }) + } +} diff --git a/apple/Common/Utils/AudioToolbox.swift b/apple/Common/Utils/AudioToolbox.swift new file mode 100644 index 0000000..693cf29 --- /dev/null +++ b/apple/Common/Utils/AudioToolbox.swift @@ -0,0 +1,163 @@ +// +// AudioToolbox.swift +// Chat +// +// Created by Ivan Khvorostinin on 14/06/2017. +// Copyright © 2017 ys1382. All rights reserved. +// + +import AudioToolbox + +class AppleAudioUnit { + + let unit: AudioUnit + + init(_ unit: AudioUnit) { + self.unit = unit + } + + convenience init(_ type: OSType, _ subtype: OSType) throws { + var componentDescription = AudioComponentDescription() + componentDescription.componentType = type + componentDescription.componentSubType = subtype + componentDescription.componentManufacturer = kAudioUnitManufacturer_Apple + componentDescription.componentFlags = 0 + componentDescription.componentFlagsMask = 0 + + let component = AudioComponentFindNext(nil, &componentDescription); + var instance: AudioUnit? + + try checkStatus(AudioComponentInstanceNew(component!, + &instance), + "AudioComponentInstanceNew") + + self.init(instance!) + } + + func initialize() throws { + try checkStatus(AudioUnitInitialize(unit), + "AudioUnitInitialize") + } + + func uninitialize() throws { + try checkStatus(AudioUnitUninitialize(unit), + "AudioUnitUninitialize") + } + + func reset(_ inScope: AudioUnitScope, _ inElement: Int) throws { + try checkStatus(AudioUnitReset(unit, inScope, AudioUnitElement(inElement)), + "AudioUnitReset") + } + + func start() throws { + try checkStatus(AudioOutputUnitStart(unit), + "AudioOutputUnitStart") + } + + func stop() throws { + try checkStatus(AudioOutputUnitStop(unit), + "AudioOutputUnitStop") + } + + func getIOEnabled(_ scope: AudioUnitScope, _ bus: Int) throws -> Bool { + var size: UInt32 = UInt32(MemoryLayout.size) + var res: UInt32 = 0 + try checkStatus(AudioUnitGetProperty(unit, + kAudioOutputUnitProperty_EnableIO, + scope, + UInt32(bus), + &res, + &size), + "AudioUnitGetProperty: kAudioOutputUnitProperty_EnableIO") + return res == 1 + + } + + func setIOEnabled(_ scope: AudioUnitScope, _ bus: Int, _ value: Bool) throws { + var valueCopy = value + #if os(iOS) + try checkStatus(AudioUnitSetProperty(unit, + kAudioOutputUnitProperty_EnableIO, + scope, + UInt32(bus), + &valueCopy, + UInt32(MemoryLayout.size)), + "AudioUnitSetProperty: kAudioOutputUnitProperty_EnableIO") + #endif + } + + func getFormat(_ scope: AudioUnitScope, _ bus: Int) throws -> AudioStreamBasicDescription { + var size: UInt32 = UInt32(MemoryLayout.size) + var res = AudioStreamBasicDescription() + try checkStatus(AudioUnitGetProperty(unit, + kAudioUnitProperty_StreamFormat, + scope, + UInt32(bus), + &res, + &size), + "AudioUnitGetProperty: kAudioUnitProperty_StreamFormat") + return res + + } + + func getFormat(_ scope: AudioUnitScope, _ bus: Int, _ outFormat: inout AudioStreamBasicDescription?) throws { + outFormat = try getFormat(scope, bus) + } + + func setFormat(_ scope: AudioUnitScope, _ bus: Int, _ value: AudioStreamBasicDescription) throws { + var valueCopy = value + try checkStatus(AudioUnitSetProperty(unit, + kAudioUnitProperty_StreamFormat, + scope, + UInt32(bus), + &valueCopy, + UInt32(MemoryLayout.size)), + "AudioUnitSetProperty: kAudioUnitProperty_StreamFormat") + } + + func setCallback(_ scope: AudioUnitScope, _ bus: Int, _ value: inout AURenderCallbackStruct) throws { + try checkStatus(AudioUnitSetProperty(unit, + kAudioOutputUnitProperty_SetInputCallback, + scope, + UInt32(bus), + &value, + UInt32(MemoryLayout.size)), + "AudioUnitSetProperty: kAudioOutputUnitProperty_SetInputCallback") + } + + func setRenderer(_ scope: AudioUnitScope, _ bus: Int, _ value: inout AURenderCallbackStruct) throws { + try checkStatus(AudioUnitSetProperty(unit, + kAudioUnitProperty_SetRenderCallback, + scope, + UInt32(bus), + &value, + UInt32(MemoryLayout.size)), + "AudioUnitSetProperty: kAudioUnitProperty_SetRenderCallback") + } + + func getMatrixVolume(_ scope: AudioUnitScope, _ bus: Int) throws -> Double { + var res: Float32 = 0 + var size: UInt32 = UInt32(MemoryLayout.size) + try checkStatus(AudioUnitGetProperty(unit, + kMatrixMixerParam_Volume, + scope, + UInt32(bus), + &res, + &size), + "AudioUnitGetProperty: kAudioUnitProperty_StreamFormat") + return Double(res) + } + + func getMultiChannelVolume(_ scope: AudioUnitScope, _ bus: Int) throws -> Double { + var res: Float32 = 0 + var size: UInt32 = UInt32(MemoryLayout.size) + try checkStatus(AudioUnitGetProperty(unit, + kMultiChannelMixerParam_Volume, + scope, + UInt32(bus), + &res, + &size), + "AudioUnitGetProperty: kAudioUnitProperty_StreamFormat") + return Double(res) + } +} diff --git a/apple/Common/Utils/CoreAudio.swift b/apple/Common/Utils/CoreAudio.swift new file mode 100644 index 0000000..f64cede --- /dev/null +++ b/apple/Common/Utils/CoreAudio.swift @@ -0,0 +1,85 @@ + +import CoreAudio + +extension AudioStreamBasicDescription { + + typealias Factory = () throws -> AudioStreamBasicDescription? + + // constant bit rate + static func CreateCBR(_ formatID: UInt32, + _ sampleRate: Double, + _ channelCount: UInt32) -> AudioStreamBasicDescription { + var result = AudioStreamBasicDescription() + + result.mSampleRate = sampleRate; + result.mChannelsPerFrame = channelCount; + result.mFormatID = formatID; + + // if we want pcm, default to signed 16-bit little-endian + result.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked + result.mBitsPerChannel = 16; + result.mBytesPerFrame = (result.mBitsPerChannel / 8) * result.mChannelsPerFrame + result.mBytesPerPacket = result.mBytesPerFrame + result.mFramesPerPacket = 1; + + return result + } + + // constant bit rate + static func CreateCBR(_ format: AudioFormat) -> AudioStreamBasicDescription { + var result = AudioStreamBasicDescription.CreateCBR(format.formatID, format.sampleRate, format.channelCount) + + result.mFormatFlags = format.flags + result.mFramesPerPacket = format.framesPerPacket + + return result + } + + // variable bit rate + static func CreateVBR(_ formatID: UInt32, + _ sampleRate: Double, + _ channelCount: UInt32) -> AudioStreamBasicDescription { + var result = AudioStreamBasicDescription() + + result.mSampleRate = sampleRate + result.mChannelsPerFrame = channelCount + result.mFormatID = formatID + + return result + } + + // variable bit rate + static func CreateVBR(_ format: AudioFormat) -> AudioStreamBasicDescription { + var result = AudioStreamBasicDescription.CreateVBR(format.formatID, format.sampleRate, format.channelCount) + + result.mFormatFlags = format.flags + result.mFramesPerPacket = format.framesPerPacket + + return result + } +} + +extension AudioTimeStamp { + + func seconds() -> Double { + return mach_absolute_seconds(mHostTime) + } + + mutating func seconds(_ x: Double) { + mHostTime = mach_absolute_time(seconds: x) + } +} + +extension AudioStreamPacketDescription : InitProtocol { + + static func ToArray(_ ptr: UnsafePointer, + _ num: UInt32) -> [AudioStreamPacketDescription] { + var result = [AudioStreamPacketDescription]() + + for i in 0 ..< num { + result.append(ptr.advanced(by: Int(i)).pointee) + } + + return result + } +} diff --git a/apple/Common/Utils/CoreMedia.swift b/apple/Common/Utils/CoreMedia.swift new file mode 100644 index 0000000..40ebf6c --- /dev/null +++ b/apple/Common/Utils/CoreMedia.swift @@ -0,0 +1,30 @@ + +import CoreMedia + +extension CMVideoDimensions : Equatable { + + public static func ==(lhs: CMVideoDimensions, rhs: CMVideoDimensions) -> Bool { + return lhs.width == rhs.width && lhs.height == rhs.height + } + + + func turn() -> CMVideoDimensions { + return CMVideoDimensions(width: height, height: width) + } + + func bitrate() -> Int32 { + return width * height + } + +} + +extension CMSampleBuffer { + + func seconds() -> Double { + return CMTimeGetSeconds(CMSampleBufferGetPresentationTimeStamp(self)) + } +} + +func CMTimeSetSeconds(_ time: inout CMTime, _ seconds: Float64) { + time.value = CMTimeValue(seconds * Float64(time.timescale)) +} diff --git a/apple/Common/Utils/Defs.swift b/apple/Common/Utils/Defs.swift new file mode 100644 index 0000000..5a28eca --- /dev/null +++ b/apple/Common/Utils/Defs.swift @@ -0,0 +1,29 @@ + +import Foundation + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Typedefs +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +#if os(iOS) + import UIKit + typealias AppleView = UIView + typealias AppleColor = UIColor + typealias AppleApplicationDelegate = UIResponder + typealias AppleStoryboard = UIStoryboard +#else + import Cocoa + typealias AppleView = NSView + typealias AppleColor = NSColor + typealias AppleApplicationDelegate = NSObject + typealias AppleStoryboard = NSStoryboard +#endif + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Lambdas +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +typealias FuncVV = () -> Void +typealias FuncVVT = () throws -> Void +typealias FuncDV = (Double) -> Void +typealias FuncDDV = (Double, Double) -> Void diff --git a/apple/Common/Utils/Dispatch.swift b/apple/Common/Utils/Dispatch.swift new file mode 100644 index 0000000..cd9d2da --- /dev/null +++ b/apple/Common/Utils/Dispatch.swift @@ -0,0 +1,55 @@ + +import Foundation + +fileprivate class _Label { + + let x: String + + init(_ x: String) { + self.x = x + } + +} + +extension DispatchQueue { + + fileprivate static let keyID = DispatchSpecificKey<_Label>() + + static func CreateCheckable(_ label: String) -> DispatchQueue { + let result = DispatchQueue(label: label) + result.setSpecific(key: DispatchQueue.keyID, value: _Label(label)) + return result + } + + static func OnQueue(_ x: DispatchQueue) -> Bool { + return DispatchQueue.getSpecific(key: DispatchQueue.keyID)?.x == x.label + } + + func asyncAfter0_5(_ block: @escaping FuncVV) { + asyncAfter(deadline: .now() + 5) { + block() + } + } +} + +func assert(_ onQueue: DispatchQueue) { + assert(DispatchQueue.OnQueue(onQueue)) +} + +func dispatch_sync_on_main(execute block: () -> Swift.Void) { + if Thread.isMainThread { + block() + } + else { + DispatchQueue.main.sync { block() } + } +} + +func dispatch_sync_on_main(execute block: () throws -> Swift.Void) throws { + if Thread.isMainThread { + try block() + } + else { + try DispatchQueue.main.sync { try block() } + } +} diff --git a/apple/Common/Utils/Foundation.swift b/apple/Common/Utils/Foundation.swift new file mode 100644 index 0000000..1dfd623 --- /dev/null +++ b/apple/Common/Utils/Foundation.swift @@ -0,0 +1,38 @@ + +import Foundation + +extension JSONSerialization { + + static var defaultWritingOptions: JSONSerialization.WritingOptions { + get { + return JSONSerialization.WritingOptions.prettyPrinted + } + } + +} + +extension Array where Element: AnyObject { + mutating func remove(_ object: Element) { + if let index = index(where: { object === $0 }) { + remove(at: index) + } + } +} + +protocol BroadcastProtocol { + init(_ x: [T?]) +} + +extension BroadcastProtocol { + + static func Create(_ x: [T]) -> T? { + if (x.count == 0) { + return nil + } + if (x.count == 1) { + return x.first + } + + return self.init(x) as? T + } +} diff --git a/apple/Common/Utils/Log.swift b/apple/Common/Utils/Log.swift new file mode 100644 index 0000000..1925a18 --- /dev/null +++ b/apple/Common/Utils/Log.swift @@ -0,0 +1,88 @@ + +import Foundation + +fileprivate extension DispatchQueue { + static let logQueue = DispatchQueue(label: "Log") +} + +fileprivate extension OutputStream { + + static let log = CreateLog() + + static func CreateLog() -> OutputStream? { + let url = URL + .appLogs + .appendingPathComponent("\(Date().description) - \(deviceModel()).txt") + + if FileManager.default.fileExists(atPath: URL.appLogs.path) == false { + try! FileManager.default.createDirectory(at: URL.appLogs, + withIntermediateDirectories: true, attributes: nil) + } + + let result = OutputStream(toFileAtPath: url.path, append: true) + result?.open() + return result + } +} + +func logWrite(_ x: String) { + let xx = String(format: "%.5f", app_absolute_seconds()) + ": \(x)" + + #if DEBUG + print(xx) + #else + DispatchQueue.logQueue.async { + OutputStream.log?.write(xx + "\n") + } + #endif +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Pipe: Messages +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +func logMessage(_ message: String) { +#if !DEBUG + logWrite(message) +#endif +} + +func logMessage(_ scope: String, _ message: String) { + logMessage((scope + ": ").padding(toLength: 10, withPad: " ", startingAt: 0) + message) +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Pipe: Important messages +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +func logPrior(_ message: String) { + logWrite(message) +} + +func logPrior(_ scope: String, _ message: String) { + logPrior((scope + ": ").padding(toLength: 10, withPad: " ", startingAt: 0) + message) +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Pipe: Errors +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +func logError(_ scope: String, _ message: String) { + logWrite(scope + " error" + ": " + message) +} + +func logError(_ scope: String, _ error: Error) { + logError(scope + " error" + ": " + String(describing: error)) +} + +func logError(_ message: String) { + logError("global", message) +} + +func checkError(_ status: OSStatus) -> Bool { + if status != noErr { + logError(status.description) + return true + } + return false +} diff --git a/apple/Common/Utils/Protobuf.swift b/apple/Common/Utils/Protobuf.swift new file mode 100644 index 0000000..c48c5cf --- /dev/null +++ b/apple/Common/Utils/Protobuf.swift @@ -0,0 +1,10 @@ + +import Foundation +import ProtocolBuffers + +#if os(iOS) +public protocol GeneratedEnum:RawRepresentable, CustomDebugStringConvertible, CustomStringConvertible, Hashable { + func toString() -> String + static func fromString(_ str:String) throws -> Self +} +#endif diff --git a/apple/Common/Utils/Serialization.swift b/apple/Common/Utils/Serialization.swift new file mode 100644 index 0000000..e0b81c5 --- /dev/null +++ b/apple/Common/Utils/Serialization.swift @@ -0,0 +1,157 @@ + +import Foundation + +class PacketsUpdater { + + let index: Int + + init() { + self.index = 0 + } + + init(_ index: Int) { + self.index = index + } + + func getValue(_ data: NSData, _ value: inout T) { + memcpy(&value, data.bytes.advanced(by: shift(data)), MemoryLayout.size) + } + + func setValue(_ data: inout NSData, _ value: T) { + var copy = value + memcpy(UnsafeMutableRawPointer(mutating: data.bytes.advanced(by: shift(data))), + ©, + MemoryLayout.size) + } + + private func shift(_ data: NSData) -> Int { + return PacketDeserializer(data, index).shift + MemoryLayout.size + } +} + +class PacketSerializer { + + let data = NSMutableData() + + func push(_ value: UnsafeRawPointer, _ size: Int) { + var size32 = UInt32(size) + + data.append(&size32, length: MemoryLayout.size) + data.append(value, length: size) + } + + func push(data: NSData) { + push(data.bytes, data.length) + } + + func push(string: String) { + push(data: string.data(using: .utf8)! as NSData) + } + + func push(array: [T]?) { + var size32 = UInt32((array != nil ? array!.count : 0) * MemoryLayout.size) + + data.append(&size32, length: MemoryLayout.size) + + guard size32 != 0 else { return } + + for var i in array! { + data.append(&i, length: MemoryLayout.size) + } + } +} + +class PacketDeserializer { + private let data: NSData + private(set) var shift = 0 + + init(_ data: NSData) { + self.data = data + } + + convenience init(_ data: NSData, _ index: Int) { + self.init(data) + + for _ in 0 ..< index { + popSkip() + } + } + + private func popSize() -> Int { + var size: UInt32 = 0 + + memcpy(&size, data.bytes.advanced(by: shift), MemoryLayout.size) + shift += MemoryLayout.size + + return Int(size) + } + + func pop(_ value: UnsafeMutableRawPointer) { + let size = popSize() + memcpy(value, data.bytes.advanced(by: shift), size) + shift += size + } + + func pop(array: inout [T]?) { + let size = popSize() + if size == 0 { return } + var i = 0 + + array = [T]() + + while i < size { + var x = T() + + memcpy(&x, data.bytes.advanced(by: shift), MemoryLayout.size) + array!.append(x) + + i += MemoryLayout.size + shift += MemoryLayout.size + } + } + + func pop(data: inout NSData?) { + let size = popSize() + let bytes = malloc(size)! + + memcpy(bytes, self.data.bytes.advanced(by: shift), Int(size)) + shift += Int(size) + + data = NSData(bytesNoCopy: bytes, length: size, freeWhenDone: true) + } + + func popData() -> NSData { + var result: NSData? + pop(data: &result) + return result! + } + + func popString() -> String { + return String(data: popData() as Data, encoding: .utf8)! + } + + func popSkip() -> PacketDeserializer { + shift = popSize() + shift + return self + } +} + +protocol SerializableProtocol : InitProtocol { + + init(deserialize data: NSData) + + func ToNSData() -> NSData +} + +extension SerializableProtocol { + + init(deserialize data: NSData) { + self.init() + memcpy(&self, data.bytes, MemoryLayout.size) + } + + func ToNSData() -> NSData { + var copy = self + return NSData(bytes: ©, length: MemoryLayout.size) + } +} diff --git a/apple/Common/Utils/System.swift b/apple/Common/Utils/System.swift new file mode 100644 index 0000000..bf75204 --- /dev/null +++ b/apple/Common/Utils/System.swift @@ -0,0 +1,127 @@ + +import Foundation + +protocol InitProtocol { + init() +} + +func typeName(_ some: Any) -> String { + return (some is Any.Type) ? "\(some)" : "\(type(of: some))" +} + +func factory(_ src: T) -> () -> T { + return { return src } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Device +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +func deviceModel() -> String { + var size = 0 + sysctlbyname("hw.machine", nil, &size, nil, 0) + var machine = [CChar](repeating: 0, count: size) + sysctlbyname("hw.machine", &machine, &size, nil, 0) + return String(cString: machine) +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Time +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +class HostTimeInfo { + static let shared = HostTimeInfo() + + let numer: UInt32 + let denom: UInt32 + let zero: UInt64 + + init() { + var info = mach_timebase_info_data_t() + mach_timebase_info(&info) + + numer = info.numer + denom = info.denom + zero = mach_absolute_time() + } +} + +func seconds2nano(_ seconds: Double) -> Int64 { + return nano(seconds) +} + +func seconds4nano(_ nano: Int64) -> Double { + return Double(nano) / 1000000000.0 +} + +func milli(_ x: Double) -> Int64 { + return Int64(x * 1000.0) +} + +func micro(_ x: Double) -> Int64 { + return Int64(x * 1000.0 * 1000.0) +} + +func nano(_ x: Double) -> Int64 { + return Int64(x * 1000.0 * 1000.0 * 1000.0) +} + +func mach_absolute_seconds(_ machTime: UInt64) -> Double { + return + seconds4nano( + Int64(Double(machTime * UInt64(HostTimeInfo.shared.numer)) / Double(HostTimeInfo.shared.denom))) +} + +func mach_absolute_seconds() -> Double { + return mach_absolute_seconds(mach_absolute_time()) +} + +func mach_absolute_time(seconds: Double) -> UInt64 { + return + UInt64(seconds2nano( + seconds * Double(HostTimeInfo.shared.denom) / Double(HostTimeInfo.shared.numer))) +} + +func app_absolute_seconds() -> Double { + return mach_absolute_seconds() - mach_absolute_seconds(HostTimeInfo.shared.zero) +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Path +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +extension URL { + + static var appDocuments: URL { + get { + return FileManager.default.urls(for: .documentDirectory, + in: .userDomainMask).first! + } + } + + static var appLogs: URL { + get { + return URL.appDocuments.appendingPathComponent("logs") + } + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Data +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +extension NSData { + typealias Factory = () throws -> NSData +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Stream +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +extension OutputStream { + + func write(_ x: String) { + let data = x.utf8ToData() as NSData + write(UnsafePointer(OpaquePointer(data.bytes)), maxLength: data.length) + } +} diff --git a/apple/Common/Utils/Thread.swift b/apple/Common/Utils/Thread.swift new file mode 100644 index 0000000..acd32fa --- /dev/null +++ b/apple/Common/Utils/Thread.swift @@ -0,0 +1,74 @@ + +import Foundation + +class ChatThread : Thread { + + var runLoop: RunLoop! + var callbacks = [UUID: FuncVV]() + var running: Bool = false + + init(_ name: String) { + super.init() + self.name = name + } + + convenience init(_ type: T) { + self.init(typeName(type)) + } + + override func main() { + runLoop = RunLoop.current + runLoop!.add(NSMachPort(), forMode: .defaultRunLoopMode) + running = true + + while running { + autoreleasepool(invoking: { + runLoop!.run(until: Date().addingTimeInterval(1)) + }) + } + } + + override func start() { + super.start() + sync { /* wait for RunLoop initialization */ } + } + + override func cancel() { + running = false + super.cancel() + } + + func sync(_ callback: @escaping FuncVV) { + if Thread.current == self { + callback() + } + else { + _call(callback, true) + } + } + + func async(_ callback: @escaping FuncVV) { + _call(callback, false) + } + + func _call(_ callback: @escaping FuncVV, _ wait: Bool) { + let id = UUID() + + callbacks[id] = callback + + perform(#selector(_perform(_:)), + on: self, + with: id, + waitUntilDone: wait) + } + + func _perform(_ id: UUID) { + callbacks[id]!() + callbacks.removeValue(forKey: id) + } +} + +func assert_main() { + assert(Thread.isMainThread) +} + diff --git a/apple/Common/Utils/UI.swift b/apple/Common/Utils/UI.swift new file mode 100644 index 0000000..cbd6e66 --- /dev/null +++ b/apple/Common/Utils/UI.swift @@ -0,0 +1,101 @@ +// +// UI.swift +// Chat +// +// Created by Ivan Khvorostinin on 30/05/2017. +// Copyright © 2017 ys1382. All rights reserved. +// + +#if os(iOS) +import UIKit +#else +import Cocoa +#endif + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// View +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +extension AppleView { + + var theLayer: CALayer { + get { + #if os(iOS) + return layer + #else + if layer == nil { + layer = makeBackingLayer() + } + return layer! + #endif + } + } + + @IBInspectable var cornerRadius: CGFloat { + get { + return theLayer.cornerRadius + } + set { + theLayer.cornerRadius = newValue + theLayer.masksToBounds = newValue > 0 + } + } + + @IBInspectable var borderWidth: CGFloat { + get { + return theLayer.borderWidth + } + set { + theLayer.borderWidth = newValue + } + } + + #if os(iOS) + @IBInspectable var borderColor:UIColor? { + get { + return AppleColor(cgColor: theLayer.borderColor!) + } + set { + theLayer.borderColor = newValue?.cgColor + } + } + #else + @IBInspectable var borderColor:NSColor? { + get { + return AppleColor(cgColor: theLayer.borderColor!) + } + set { + theLayer.borderColor = newValue?.cgColor + } + } + #endif + + #if os(OSX) + @IBInspectable var backgroundColor: NSColor? { + get { + if theLayer.backgroundColor != nil { + return AppleColor(cgColor: theLayer.backgroundColor!) + } + else { + return nil + } + } + set { + theLayer.backgroundColor = newValue?.cgColor + } + } + #endif +} + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// View controller +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +func instantiateViewController(_ storyboard: AppleStoryboard) -> T { + #if os(iOS) + return storyboard.instantiateViewController(withIdentifier: typeName(T.self)) as! T + #else + return storyboard.instantiateController(withIdentifier: typeName(T.self)) as! T + #endif +} + diff --git a/apple/common/Wire.proto.swift b/apple/Common/Wire.proto.swift similarity index 76% rename from apple/common/Wire.proto.swift rename to apple/Common/Wire.proto.swift index 4b5c6b8..eae95b3 100644 --- a/apple/common/Wire.proto.swift +++ b/apple/Common/Wire.proto.swift @@ -1,5 +1,5 @@ -/// Generated by the Protocol Buffers 3.2.0 compiler. DO NOT EDIT! -/// Protobuf-swift version: 3.0.13 +/// Generated by the Protocol Buffers 3.3.0 compiler. DO NOT EDIT! +/// Protobuf-swift version: 3.0.16 /// Source file "wire.proto" /// Syntax "Proto3" @@ -31,7 +31,7 @@ final public class Login : GeneratedMessage { return fieldCheck } - public fileprivate(set) var username:String = "" + public fileprivate(set) var username:String! = nil public fileprivate(set) var hasUsername:Bool = false required public init() { @@ -156,7 +156,7 @@ final public class Login : GeneratedMessage { @discardableResult public func clearUsername() -> Login.Builder{ builderResult.hasUsername = false - builderResult.username = "" + builderResult.username = nil return self } override public var internalGetResult:GeneratedMessage { @@ -247,10 +247,10 @@ final public class Contact : GeneratedMessage { return fieldCheck } - public fileprivate(set) var name:String = "" + public fileprivate(set) var name:String! = nil public fileprivate(set) var hasName:Bool = false - public fileprivate(set) var online:Bool = false + public fileprivate(set) var online:Bool! = nil public fileprivate(set) var hasOnline:Bool = false required public init() { @@ -390,7 +390,7 @@ final public class Contact : GeneratedMessage { @discardableResult public func clearName() -> Contact.Builder{ builderResult.hasName = false - builderResult.name = "" + builderResult.name = nil return self } public var online:Bool { @@ -415,7 +415,7 @@ final public class Contact : GeneratedMessage { @discardableResult public func clearOnline() -> Contact.Builder{ builderResult.hasOnline = false - builderResult.online = false + builderResult.online = nil return self } override public var internalGetResult:GeneratedMessage { @@ -514,7 +514,7 @@ final public class Text : GeneratedMessage { return fieldCheck } - public fileprivate(set) var body:String = "" + public fileprivate(set) var body:String! = nil public fileprivate(set) var hasBody:Bool = false required public init() { @@ -639,7 +639,7 @@ final public class Text : GeneratedMessage { @discardableResult public func clearBody() -> Text.Builder{ builderResult.hasBody = false - builderResult.body = "" + builderResult.body = nil return self } override public var internalGetResult:GeneratedMessage { @@ -730,10 +730,10 @@ final public class File : GeneratedMessage { return fieldCheck } - public fileprivate(set) var key:String = "" + public fileprivate(set) var key:String! = nil public fileprivate(set) var hasKey:Bool = false - public fileprivate(set) var data:Data = Data() + public fileprivate(set) var data:Data! = nil public fileprivate(set) var hasData:Bool = false required public init() { @@ -873,7 +873,7 @@ final public class File : GeneratedMessage { @discardableResult public func clearKey() -> File.Builder{ builderResult.hasKey = false - builderResult.key = "" + builderResult.key = nil return self } public var data:Data { @@ -898,7 +898,7 @@ final public class File : GeneratedMessage { @discardableResult public func clearData() -> File.Builder{ builderResult.hasData = false - builderResult.data = Data() + builderResult.data = nil return self } override public var internalGetResult:GeneratedMessage { @@ -985,32 +985,36 @@ final public class File : GeneratedMessage { } -final public class Time : GeneratedMessage { +final public class Call : GeneratedMessage { - public static func == (lhs: Time, rhs: Time) -> Bool { + public static func == (lhs: Call, rhs: Call) -> Bool { if lhs === rhs { return true } var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue) - fieldCheck = fieldCheck && (lhs.hasValue == rhs.hasValue) && (!lhs.hasValue || lhs.value == rhs.value) - fieldCheck = fieldCheck && (lhs.hasScale == rhs.hasScale) && (!lhs.hasScale || lhs.scale == rhs.scale) - fieldCheck = fieldCheck && (lhs.hasFlags == rhs.hasFlags) && (!lhs.hasFlags || lhs.flags == rhs.flags) - fieldCheck = fieldCheck && (lhs.hasEpoch == rhs.hasEpoch) && (!lhs.hasEpoch || lhs.epoch == rhs.epoch) + fieldCheck = fieldCheck && (lhs.hasKey == rhs.hasKey) && (!lhs.hasKey || lhs.key == rhs.key) + fieldCheck = fieldCheck && (lhs.hasTo == rhs.hasTo) && (!lhs.hasTo || lhs.to == rhs.to) + fieldCheck = fieldCheck && (lhs.hasFrom == rhs.hasFrom) && (!lhs.hasFrom || lhs.from == rhs.from) + fieldCheck = fieldCheck && (lhs.hasAudio == rhs.hasAudio) && (!lhs.hasAudio || lhs.audio == rhs.audio) + fieldCheck = fieldCheck && (lhs.hasVideo == rhs.hasVideo) && (!lhs.hasVideo || lhs.video == rhs.video) fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) return fieldCheck } - public fileprivate(set) var value:Int64 = Int64(0) - public fileprivate(set) var hasValue:Bool = false + public fileprivate(set) var key:String! = nil + public fileprivate(set) var hasKey:Bool = false - public fileprivate(set) var scale:Int32 = Int32(0) - public fileprivate(set) var hasScale:Bool = false + public fileprivate(set) var to:String! = nil + public fileprivate(set) var hasTo:Bool = false - public fileprivate(set) var flags:UInt32 = UInt32(0) - public fileprivate(set) var hasFlags:Bool = false + public fileprivate(set) var from:String! = nil + public fileprivate(set) var hasFrom:Bool = false - public fileprivate(set) var epoch:Int64 = Int64(0) - public fileprivate(set) var hasEpoch:Bool = false + public fileprivate(set) var audio:Bool! = nil + public fileprivate(set) var hasAudio:Bool = false + + public fileprivate(set) var video:Bool! = nil + public fileprivate(set) var hasVideo:Bool = false required public init() { super.init() @@ -1019,17 +1023,20 @@ final public class Time : GeneratedMessage { return true } override public func writeTo(codedOutputStream: CodedOutputStream) throws { - if hasValue { - try codedOutputStream.writeInt64(fieldNumber: 1, value:value) + if hasKey { + try codedOutputStream.writeString(fieldNumber: 1, value:key) } - if hasScale { - try codedOutputStream.writeInt32(fieldNumber: 2, value:scale) + if hasTo { + try codedOutputStream.writeString(fieldNumber: 2, value:to) } - if hasFlags { - try codedOutputStream.writeUInt32(fieldNumber: 3, value:flags) + if hasFrom { + try codedOutputStream.writeString(fieldNumber: 3, value:from) } - if hasEpoch { - try codedOutputStream.writeInt64(fieldNumber: 4, value:epoch) + if hasAudio { + try codedOutputStream.writeBool(fieldNumber: 4, value:audio) + } + if hasVideo { + try codedOutputStream.writeBool(fieldNumber: 5, value:video) } try unknownFields.writeTo(codedOutputStream: codedOutputStream) } @@ -1040,39 +1047,42 @@ final public class Time : GeneratedMessage { } serialize_size = 0 - if hasValue { - serialize_size += value.computeInt64Size(fieldNumber: 1) + if hasKey { + serialize_size += key.computeStringSize(fieldNumber: 1) } - if hasScale { - serialize_size += scale.computeInt32Size(fieldNumber: 2) + if hasTo { + serialize_size += to.computeStringSize(fieldNumber: 2) } - if hasFlags { - serialize_size += flags.computeUInt32Size(fieldNumber: 3) + if hasFrom { + serialize_size += from.computeStringSize(fieldNumber: 3) } - if hasEpoch { - serialize_size += epoch.computeInt64Size(fieldNumber: 4) + if hasAudio { + serialize_size += audio.computeBoolSize(fieldNumber: 4) + } + if hasVideo { + serialize_size += video.computeBoolSize(fieldNumber: 5) } serialize_size += unknownFields.serializedSize() memoizedSerializedSize = serialize_size return serialize_size } - public class func getBuilder() -> Time.Builder { - return Time.classBuilder() as! Time.Builder + public class func getBuilder() -> Call.Builder { + return Call.classBuilder() as! Call.Builder } - public func getBuilder() -> Time.Builder { - return classBuilder() as! Time.Builder + public func getBuilder() -> Call.Builder { + return classBuilder() as! Call.Builder } override public class func classBuilder() -> ProtocolBuffersMessageBuilder { - return Time.Builder() + return Call.Builder() } override public func classBuilder() -> ProtocolBuffersMessageBuilder { - return Time.Builder() + return Call.Builder() } - public func toBuilder() throws -> Time.Builder { - return try Time.builderWithPrototype(prototype:self) + public func toBuilder() throws -> Call.Builder { + return try Call.builderWithPrototype(prototype:self) } - public class func builderWithPrototype(prototype:Time) throws -> Time.Builder { - return try Time.Builder().mergeFrom(other:prototype) + public class func builderWithPrototype(prototype:Call) throws -> Call.Builder { + return try Call.Builder().mergeFrom(other:prototype) } override public func encode() throws -> Dictionary { guard isInitialized() else { @@ -1080,39 +1090,45 @@ final public class Time : GeneratedMessage { } var jsonMap:Dictionary = Dictionary() - if hasValue { - jsonMap["value"] = "\(value)" + if hasKey { + jsonMap["key"] = key } - if hasScale { - jsonMap["scale"] = Int(scale) + if hasTo { + jsonMap["to"] = to } - if hasFlags { - jsonMap["flags"] = UInt(flags) + if hasFrom { + jsonMap["from"] = from } - if hasEpoch { - jsonMap["epoch"] = "\(epoch)" + if hasAudio { + jsonMap["audio"] = audio + } + if hasVideo { + jsonMap["video"] = video } return jsonMap } - override class public func decode(jsonMap:Dictionary) throws -> Time { - return try Time.Builder.decodeToBuilder(jsonMap:jsonMap).build() + override class public func decode(jsonMap:Dictionary) throws -> Call { + return try Call.Builder.decodeToBuilder(jsonMap:jsonMap).build() } - override class public func fromJSON(data:Data) throws -> Time { - return try Time.Builder.fromJSONToBuilder(data:data).build() + override class public func fromJSON(data:Data) throws -> Call { + return try Call.Builder.fromJSONToBuilder(data:data).build() } override public func getDescription(indent:String) throws -> String { var output = "" - if hasValue { - output += "\(indent) value: \(value) \n" + if hasKey { + output += "\(indent) key: \(key) \n" } - if hasScale { - output += "\(indent) scale: \(scale) \n" + if hasTo { + output += "\(indent) to: \(to) \n" } - if hasFlags { - output += "\(indent) flags: \(flags) \n" + if hasFrom { + output += "\(indent) from: \(from) \n" } - if hasEpoch { - output += "\(indent) epoch: \(epoch) \n" + if hasAudio { + output += "\(indent) audio: \(audio) \n" + } + if hasVideo { + output += "\(indent) video: \(video) \n" } output += unknownFields.getDescription(indent: indent) return output @@ -1120,17 +1136,20 @@ final public class Time : GeneratedMessage { override public var hashValue:Int { get { var hashCode:Int = 7 - if hasValue { - hashCode = (hashCode &* 31) &+ value.hashValue + if hasKey { + hashCode = (hashCode &* 31) &+ key.hashValue } - if hasScale { - hashCode = (hashCode &* 31) &+ scale.hashValue + if hasTo { + hashCode = (hashCode &* 31) &+ to.hashValue } - if hasFlags { - hashCode = (hashCode &* 31) &+ flags.hashValue + if hasFrom { + hashCode = (hashCode &* 31) &+ from.hashValue } - if hasEpoch { - hashCode = (hashCode &* 31) &+ epoch.hashValue + if hasAudio { + hashCode = (hashCode &* 31) &+ audio.hashValue + } + if hasVideo { + hashCode = (hashCode &* 31) &+ video.hashValue } hashCode = (hashCode &* 31) &+ unknownFields.hashValue return hashCode @@ -1141,120 +1160,145 @@ final public class Time : GeneratedMessage { //Meta information declaration start override public class func className() -> String { - return "Time" + return "Call" } override public func className() -> String { - return "Time" + return "Call" } //Meta information declaration end final public class Builder : GeneratedMessageBuilder { - fileprivate var builderResult:Time = Time() - public func getMessage() -> Time { + fileprivate var builderResult:Call = Call() + public func getMessage() -> Call { return builderResult } required override public init () { super.init() } - public var value:Int64 { + public var key:String { get { - return builderResult.value + return builderResult.key } set (value) { - builderResult.hasValue = true - builderResult.value = value + builderResult.hasKey = true + builderResult.key = value } } - public var hasValue:Bool { + public var hasKey:Bool { get { - return builderResult.hasValue + return builderResult.hasKey } } @discardableResult - public func setValue(_ value:Int64) -> Time.Builder { - self.value = value + public func setKey(_ value:String) -> Call.Builder { + self.key = value return self } @discardableResult - public func clearValue() -> Time.Builder{ - builderResult.hasValue = false - builderResult.value = Int64(0) + public func clearKey() -> Call.Builder{ + builderResult.hasKey = false + builderResult.key = nil return self } - public var scale:Int32 { + public var to:String { get { - return builderResult.scale + return builderResult.to } set (value) { - builderResult.hasScale = true - builderResult.scale = value + builderResult.hasTo = true + builderResult.to = value } } - public var hasScale:Bool { + public var hasTo:Bool { get { - return builderResult.hasScale + return builderResult.hasTo } } @discardableResult - public func setScale(_ value:Int32) -> Time.Builder { - self.scale = value + public func setTo(_ value:String) -> Call.Builder { + self.to = value return self } @discardableResult - public func clearScale() -> Time.Builder{ - builderResult.hasScale = false - builderResult.scale = Int32(0) + public func clearTo() -> Call.Builder{ + builderResult.hasTo = false + builderResult.to = nil return self } - public var flags:UInt32 { + public var from:String { get { - return builderResult.flags + return builderResult.from } set (value) { - builderResult.hasFlags = true - builderResult.flags = value + builderResult.hasFrom = true + builderResult.from = value } } - public var hasFlags:Bool { + public var hasFrom:Bool { get { - return builderResult.hasFlags + return builderResult.hasFrom } } @discardableResult - public func setFlags(_ value:UInt32) -> Time.Builder { - self.flags = value + public func setFrom(_ value:String) -> Call.Builder { + self.from = value return self } @discardableResult - public func clearFlags() -> Time.Builder{ - builderResult.hasFlags = false - builderResult.flags = UInt32(0) + public func clearFrom() -> Call.Builder{ + builderResult.hasFrom = false + builderResult.from = nil return self } - public var epoch:Int64 { + public var audio:Bool { get { - return builderResult.epoch + return builderResult.audio } set (value) { - builderResult.hasEpoch = true - builderResult.epoch = value + builderResult.hasAudio = true + builderResult.audio = value } } - public var hasEpoch:Bool { + public var hasAudio:Bool { get { - return builderResult.hasEpoch + return builderResult.hasAudio } } @discardableResult - public func setEpoch(_ value:Int64) -> Time.Builder { - self.epoch = value + public func setAudio(_ value:Bool) -> Call.Builder { + self.audio = value return self } @discardableResult - public func clearEpoch() -> Time.Builder{ - builderResult.hasEpoch = false - builderResult.epoch = Int64(0) + public func clearAudio() -> Call.Builder{ + builderResult.hasAudio = false + builderResult.audio = nil + return self + } + public var video:Bool { + get { + return builderResult.video + } + set (value) { + builderResult.hasVideo = true + builderResult.video = value + } + } + public var hasVideo:Bool { + get { + return builderResult.hasVideo + } + } + @discardableResult + public func setVideo(_ value:Bool) -> Call.Builder { + self.video = value + return self + } + @discardableResult + public func clearVideo() -> Call.Builder{ + builderResult.hasVideo = false + builderResult.video = nil return self } override public var internalGetResult:GeneratedMessage { @@ -1263,47 +1307,50 @@ final public class Time : GeneratedMessage { } } @discardableResult - override public func clear() -> Time.Builder { - builderResult = Time() + override public func clear() -> Call.Builder { + builderResult = Call() return self } - override public func clone() throws -> Time.Builder { - return try Time.builderWithPrototype(prototype:builderResult) + override public func clone() throws -> Call.Builder { + return try Call.builderWithPrototype(prototype:builderResult) } - override public func build() throws -> Time { + override public func build() throws -> Call { try checkInitialized() return buildPartial() } - public func buildPartial() -> Time { - let returnMe:Time = builderResult + public func buildPartial() -> Call { + let returnMe:Call = builderResult return returnMe } @discardableResult - public func mergeFrom(other:Time) throws -> Time.Builder { - if other == Time() { + public func mergeFrom(other:Call) throws -> Call.Builder { + if other == Call() { return self } - if other.hasValue { - value = other.value + if other.hasKey { + key = other.key } - if other.hasScale { - scale = other.scale + if other.hasTo { + to = other.to } - if other.hasFlags { - flags = other.flags + if other.hasFrom { + from = other.from } - if other.hasEpoch { - epoch = other.epoch + if other.hasAudio { + audio = other.audio + } + if other.hasVideo { + video = other.video } try merge(unknownField: other.unknownFields) return self } @discardableResult - override public func mergeFrom(codedInputStream: CodedInputStream) throws -> Time.Builder { + override public func mergeFrom(codedInputStream: CodedInputStream) throws -> Call.Builder { return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry()) } @discardableResult - override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Time.Builder { + override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Call.Builder { let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(copyFrom:self.unknownFields) while (true) { let protobufTag = try codedInputStream.readTag() @@ -1312,19 +1359,22 @@ final public class Time : GeneratedMessage { self.unknownFields = try unknownFieldsBuilder.build() return self - case 8: - value = try codedInputStream.readInt64() + case 10: + key = try codedInputStream.readString() - case 16: - scale = try codedInputStream.readInt32() + case 18: + to = try codedInputStream.readString() - case 24: - flags = try codedInputStream.readUInt32() + case 26: + from = try codedInputStream.readString() case 32: - epoch = try codedInputStream.readInt64() + audio = try codedInputStream.readBool() - default: + case 40: + video = try codedInputStream.readBool() + + default: if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) { unknownFields = try unknownFieldsBuilder.build() return self @@ -1332,58 +1382,63 @@ final public class Time : GeneratedMessage { } } } - class override public func decodeToBuilder(jsonMap:Dictionary) throws -> Time.Builder { - let resultDecodedBuilder = Time.Builder() - if let jsonValueValue = jsonMap["value"] as? String { - resultDecodedBuilder.value = Int64(jsonValueValue)! - } else if let jsonValueValue = jsonMap["value"] as? Int { - resultDecodedBuilder.value = Int64(jsonValueValue) + class override public func decodeToBuilder(jsonMap:Dictionary) throws -> Call.Builder { + let resultDecodedBuilder = Call.Builder() + if let jsonValueKey = jsonMap["key"] as? String { + resultDecodedBuilder.key = jsonValueKey } - if let jsonValueScale = jsonMap["scale"] as? Int { - resultDecodedBuilder.scale = Int32(jsonValueScale) - } else if let jsonValueScale = jsonMap["scale"] as? String { - resultDecodedBuilder.scale = Int32(jsonValueScale)! + if let jsonValueTo = jsonMap["to"] as? String { + resultDecodedBuilder.to = jsonValueTo } - if let jsonValueFlags = jsonMap["flags"] as? UInt { - resultDecodedBuilder.flags = UInt32(jsonValueFlags) - } else if let jsonValueFlags = jsonMap["flags"] as? String { - resultDecodedBuilder.flags = UInt32(jsonValueFlags)! + if let jsonValueFrom = jsonMap["from"] as? String { + resultDecodedBuilder.from = jsonValueFrom } - if let jsonValueEpoch = jsonMap["epoch"] as? String { - resultDecodedBuilder.epoch = Int64(jsonValueEpoch)! - } else if let jsonValueEpoch = jsonMap["epoch"] as? Int { - resultDecodedBuilder.epoch = Int64(jsonValueEpoch) + if let jsonValueAudio = jsonMap["audio"] as? Bool { + resultDecodedBuilder.audio = jsonValueAudio + } + if let jsonValueVideo = jsonMap["video"] as? Bool { + resultDecodedBuilder.video = jsonValueVideo } return resultDecodedBuilder } - override class public func fromJSONToBuilder(data:Data) throws -> Time.Builder { + override class public func fromJSONToBuilder(data:Data) throws -> Call.Builder { let jsonData = try JSONSerialization.jsonObject(with:data, options: JSONSerialization.ReadingOptions(rawValue: 0)) guard let jsDataCast = jsonData as? Dictionary else { throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") } - return try Time.Builder.decodeToBuilder(jsonMap:jsDataCast) + return try Call.Builder.decodeToBuilder(jsonMap:jsDataCast) } } } -final public class Timestamp : GeneratedMessage { +final public class Time : GeneratedMessage { - public static func == (lhs: Timestamp, rhs: Timestamp) -> Bool { + public static func == (lhs: Time, rhs: Time) -> Bool { if lhs === rhs { return true } var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue) - fieldCheck = fieldCheck && (lhs.hasDuration == rhs.hasDuration) && (!lhs.hasDuration || lhs.duration == rhs.duration) - fieldCheck = fieldCheck && (lhs.hasPresentation == rhs.hasPresentation) && (!lhs.hasPresentation || lhs.presentation == rhs.presentation) + fieldCheck = fieldCheck && (lhs.hasValue == rhs.hasValue) && (!lhs.hasValue || lhs.value == rhs.value) + fieldCheck = fieldCheck && (lhs.hasScale == rhs.hasScale) && (!lhs.hasScale || lhs.scale == rhs.scale) + fieldCheck = fieldCheck && (lhs.hasFlags == rhs.hasFlags) && (!lhs.hasFlags || lhs.flags == rhs.flags) + fieldCheck = fieldCheck && (lhs.hasEpoch == rhs.hasEpoch) && (!lhs.hasEpoch || lhs.epoch == rhs.epoch) fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) return fieldCheck } - public fileprivate(set) var duration:Time! - public fileprivate(set) var hasDuration:Bool = false - public fileprivate(set) var presentation:Time! - public fileprivate(set) var hasPresentation:Bool = false + public fileprivate(set) var value:Int64! = nil + public fileprivate(set) var hasValue:Bool = false + + public fileprivate(set) var scale:Int32! = nil + public fileprivate(set) var hasScale:Bool = false + + public fileprivate(set) var flags:UInt32! = nil + public fileprivate(set) var hasFlags:Bool = false + + public fileprivate(set) var epoch:Int64! = nil + public fileprivate(set) var hasEpoch:Bool = false + required public init() { super.init() } @@ -1391,11 +1446,17 @@ final public class Timestamp : GeneratedMessage { return true } override public func writeTo(codedOutputStream: CodedOutputStream) throws { - if hasDuration { - try codedOutputStream.writeMessage(fieldNumber: 1, value:duration) + if hasValue { + try codedOutputStream.writeInt64(fieldNumber: 1, value:value) } - if hasPresentation { - try codedOutputStream.writeMessage(fieldNumber: 2, value:presentation) + if hasScale { + try codedOutputStream.writeInt32(fieldNumber: 2, value:scale) + } + if hasFlags { + try codedOutputStream.writeUInt32(fieldNumber: 3, value:flags) + } + if hasEpoch { + try codedOutputStream.writeInt64(fieldNumber: 4, value:epoch) } try unknownFields.writeTo(codedOutputStream: codedOutputStream) } @@ -1406,37 +1467,39 @@ final public class Timestamp : GeneratedMessage { } serialize_size = 0 - if hasDuration { - if let varSizeduration = duration?.computeMessageSize(fieldNumber: 1) { - serialize_size += varSizeduration - } + if hasValue { + serialize_size += value.computeInt64Size(fieldNumber: 1) } - if hasPresentation { - if let varSizepresentation = presentation?.computeMessageSize(fieldNumber: 2) { - serialize_size += varSizepresentation - } + if hasScale { + serialize_size += scale.computeInt32Size(fieldNumber: 2) + } + if hasFlags { + serialize_size += flags.computeUInt32Size(fieldNumber: 3) + } + if hasEpoch { + serialize_size += epoch.computeInt64Size(fieldNumber: 4) } serialize_size += unknownFields.serializedSize() memoizedSerializedSize = serialize_size return serialize_size } - public class func getBuilder() -> Timestamp.Builder { - return Timestamp.classBuilder() as! Timestamp.Builder + public class func getBuilder() -> Time.Builder { + return Time.classBuilder() as! Time.Builder } - public func getBuilder() -> Timestamp.Builder { - return classBuilder() as! Timestamp.Builder + public func getBuilder() -> Time.Builder { + return classBuilder() as! Time.Builder } override public class func classBuilder() -> ProtocolBuffersMessageBuilder { - return Timestamp.Builder() + return Time.Builder() } override public func classBuilder() -> ProtocolBuffersMessageBuilder { - return Timestamp.Builder() + return Time.Builder() } - public func toBuilder() throws -> Timestamp.Builder { - return try Timestamp.builderWithPrototype(prototype:self) + public func toBuilder() throws -> Time.Builder { + return try Time.builderWithPrototype(prototype:self) } - public class func builderWithPrototype(prototype:Timestamp) throws -> Timestamp.Builder { - return try Timestamp.Builder().mergeFrom(other:prototype) + public class func builderWithPrototype(prototype:Time) throws -> Time.Builder { + return try Time.Builder().mergeFrom(other:prototype) } override public func encode() throws -> Dictionary { guard isInitialized() else { @@ -1444,35 +1507,39 @@ final public class Timestamp : GeneratedMessage { } var jsonMap:Dictionary = Dictionary() - if hasDuration { - jsonMap["duration"] = try duration.encode() + if hasValue { + jsonMap["value"] = "\(value)" } - if hasPresentation { - jsonMap["presentation"] = try presentation.encode() + if hasScale { + jsonMap["scale"] = Int(scale) + } + if hasFlags { + jsonMap["flags"] = UInt(flags) + } + if hasEpoch { + jsonMap["epoch"] = "\(epoch)" } return jsonMap } - override class public func decode(jsonMap:Dictionary) throws -> Timestamp { - return try Timestamp.Builder.decodeToBuilder(jsonMap:jsonMap).build() + override class public func decode(jsonMap:Dictionary) throws -> Time { + return try Time.Builder.decodeToBuilder(jsonMap:jsonMap).build() } - override class public func fromJSON(data:Data) throws -> Timestamp { - return try Timestamp.Builder.fromJSONToBuilder(data:data).build() + override class public func fromJSON(data:Data) throws -> Time { + return try Time.Builder.fromJSONToBuilder(data:data).build() } override public func getDescription(indent:String) throws -> String { var output = "" - if hasDuration { - output += "\(indent) duration {\n" - if let outDescDuration = duration { - output += try outDescDuration.getDescription(indent: "\(indent) ") - } - output += "\(indent) }\n" + if hasValue { + output += "\(indent) value: \(value) \n" } - if hasPresentation { - output += "\(indent) presentation {\n" - if let outDescPresentation = presentation { - output += try outDescPresentation.getDescription(indent: "\(indent) ") - } - output += "\(indent) }\n" + if hasScale { + output += "\(indent) scale: \(scale) \n" + } + if hasFlags { + output += "\(indent) flags: \(flags) \n" + } + if hasEpoch { + output += "\(indent) epoch: \(epoch) \n" } output += unknownFields.getDescription(indent: indent) return output @@ -1480,15 +1547,17 @@ final public class Timestamp : GeneratedMessage { override public var hashValue:Int { get { var hashCode:Int = 7 - if hasDuration { - if let hashValueduration = duration?.hashValue { - hashCode = (hashCode &* 31) &+ hashValueduration - } + if hasValue { + hashCode = (hashCode &* 31) &+ value.hashValue } - if hasPresentation { - if let hashValuepresentation = presentation?.hashValue { - hashCode = (hashCode &* 31) &+ hashValuepresentation - } + if hasScale { + hashCode = (hashCode &* 31) &+ scale.hashValue + } + if hasFlags { + hashCode = (hashCode &* 31) &+ flags.hashValue + } + if hasEpoch { + hashCode = (hashCode &* 31) &+ epoch.hashValue } hashCode = (hashCode &* 31) &+ unknownFields.hashValue return hashCode @@ -1499,128 +1568,120 @@ final public class Timestamp : GeneratedMessage { //Meta information declaration start override public class func className() -> String { - return "Timestamp" + return "Time" } override public func className() -> String { - return "Timestamp" + return "Time" } //Meta information declaration end final public class Builder : GeneratedMessageBuilder { - fileprivate var builderResult:Timestamp = Timestamp() - public func getMessage() -> Timestamp { + fileprivate var builderResult:Time = Time() + public func getMessage() -> Time { return builderResult } required override public init () { super.init() } - public var duration:Time! { + public var value:Int64 { get { - if durationBuilder_ != nil { - builderResult.duration = durationBuilder_.getMessage() - } - return builderResult.duration + return builderResult.value } set (value) { - builderResult.hasDuration = true - builderResult.duration = value + builderResult.hasValue = true + builderResult.value = value } } - public var hasDuration:Bool { + public var hasValue:Bool { get { - return builderResult.hasDuration - } - } - fileprivate var durationBuilder_:Time.Builder! { - didSet { - builderResult.hasDuration = true - } - } - public func getDurationBuilder() -> Time.Builder { - if durationBuilder_ == nil { - durationBuilder_ = Time.Builder() - builderResult.duration = durationBuilder_.getMessage() - if duration != nil { - try! durationBuilder_.mergeFrom(other: duration) - } + return builderResult.hasValue } - return durationBuilder_ } @discardableResult - public func setDuration(_ value:Time!) -> Timestamp.Builder { - self.duration = value + public func setValue(_ value:Int64) -> Time.Builder { + self.value = value return self } @discardableResult - public func mergeDuration(value:Time) throws -> Timestamp.Builder { - if builderResult.hasDuration { - builderResult.duration = try Time.builderWithPrototype(prototype:builderResult.duration).mergeFrom(other: value).buildPartial() - } else { - builderResult.duration = value + public func clearValue() -> Time.Builder{ + builderResult.hasValue = false + builderResult.value = nil + return self + } + public var scale:Int32 { + get { + return builderResult.scale } - builderResult.hasDuration = true + set (value) { + builderResult.hasScale = true + builderResult.scale = value + } + } + public var hasScale:Bool { + get { + return builderResult.hasScale + } + } + @discardableResult + public func setScale(_ value:Int32) -> Time.Builder { + self.scale = value return self } @discardableResult - public func clearDuration() -> Timestamp.Builder { - durationBuilder_ = nil - builderResult.hasDuration = false - builderResult.duration = nil + public func clearScale() -> Time.Builder{ + builderResult.hasScale = false + builderResult.scale = nil return self } - public var presentation:Time! { + public var flags:UInt32 { get { - if presentationBuilder_ != nil { - builderResult.presentation = presentationBuilder_.getMessage() - } - return builderResult.presentation + return builderResult.flags } set (value) { - builderResult.hasPresentation = true - builderResult.presentation = value + builderResult.hasFlags = true + builderResult.flags = value } } - public var hasPresentation:Bool { + public var hasFlags:Bool { get { - return builderResult.hasPresentation + return builderResult.hasFlags } } - fileprivate var presentationBuilder_:Time.Builder! { - didSet { - builderResult.hasPresentation = true - } - } - public func getPresentationBuilder() -> Time.Builder { - if presentationBuilder_ == nil { - presentationBuilder_ = Time.Builder() - builderResult.presentation = presentationBuilder_.getMessage() - if presentation != nil { - try! presentationBuilder_.mergeFrom(other: presentation) - } - } - return presentationBuilder_ - } @discardableResult - public func setPresentation(_ value:Time!) -> Timestamp.Builder { - self.presentation = value + public func setFlags(_ value:UInt32) -> Time.Builder { + self.flags = value return self } @discardableResult - public func mergePresentation(value:Time) throws -> Timestamp.Builder { - if builderResult.hasPresentation { - builderResult.presentation = try Time.builderWithPrototype(prototype:builderResult.presentation).mergeFrom(other: value).buildPartial() - } else { - builderResult.presentation = value + public func clearFlags() -> Time.Builder{ + builderResult.hasFlags = false + builderResult.flags = nil + return self + } + public var epoch:Int64 { + get { + return builderResult.epoch } - builderResult.hasPresentation = true + set (value) { + builderResult.hasEpoch = true + builderResult.epoch = value + } + } + public var hasEpoch:Bool { + get { + return builderResult.hasEpoch + } + } + @discardableResult + public func setEpoch(_ value:Int64) -> Time.Builder { + self.epoch = value return self } @discardableResult - public func clearPresentation() -> Timestamp.Builder { - presentationBuilder_ = nil - builderResult.hasPresentation = false - builderResult.presentation = nil + public func clearEpoch() -> Time.Builder{ + builderResult.hasEpoch = false + builderResult.epoch = nil return self } override public var internalGetResult:GeneratedMessage { @@ -1629,41 +1690,47 @@ final public class Timestamp : GeneratedMessage { } } @discardableResult - override public func clear() -> Timestamp.Builder { - builderResult = Timestamp() + override public func clear() -> Time.Builder { + builderResult = Time() return self } - override public func clone() throws -> Timestamp.Builder { - return try Timestamp.builderWithPrototype(prototype:builderResult) + override public func clone() throws -> Time.Builder { + return try Time.builderWithPrototype(prototype:builderResult) } - override public func build() throws -> Timestamp { + override public func build() throws -> Time { try checkInitialized() return buildPartial() } - public func buildPartial() -> Timestamp { - let returnMe:Timestamp = builderResult + public func buildPartial() -> Time { + let returnMe:Time = builderResult return returnMe } @discardableResult - public func mergeFrom(other:Timestamp) throws -> Timestamp.Builder { - if other == Timestamp() { + public func mergeFrom(other:Time) throws -> Time.Builder { + if other == Time() { return self } - if (other.hasDuration) { - try mergeDuration(value: other.duration) + if other.hasValue { + value = other.value } - if (other.hasPresentation) { - try mergePresentation(value: other.presentation) + if other.hasScale { + scale = other.scale + } + if other.hasFlags { + flags = other.flags + } + if other.hasEpoch { + epoch = other.epoch } try merge(unknownField: other.unknownFields) return self } @discardableResult - override public func mergeFrom(codedInputStream: CodedInputStream) throws -> Timestamp.Builder { + override public func mergeFrom(codedInputStream: CodedInputStream) throws -> Time.Builder { return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry()) } @discardableResult - override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Timestamp.Builder { + override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Time.Builder { let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(copyFrom:self.unknownFields) while (true) { let protobufTag = try codedInputStream.readTag() @@ -1672,21 +1739,17 @@ final public class Timestamp : GeneratedMessage { self.unknownFields = try unknownFieldsBuilder.build() return self - case 10: - let subBuilder:Time.Builder = Time.Builder() - if hasDuration { - try subBuilder.mergeFrom(other: duration) - } - try codedInputStream.readMessage(builder: subBuilder, extensionRegistry:extensionRegistry) - duration = subBuilder.buildPartial() + case 8: + value = try codedInputStream.readInt64() - case 18: - let subBuilder:Time.Builder = Time.Builder() - if hasPresentation { - try subBuilder.mergeFrom(other: presentation) - } - try codedInputStream.readMessage(builder: subBuilder, extensionRegistry:extensionRegistry) - presentation = subBuilder.buildPartial() + case 16: + scale = try codedInputStream.readInt32() + + case 24: + flags = try codedInputStream.readUInt32() + + case 32: + epoch = try codedInputStream.readInt64() default: if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) { @@ -1696,1056 +1759,2016 @@ final public class Timestamp : GeneratedMessage { } } } - class override public func decodeToBuilder(jsonMap:Dictionary) throws -> Timestamp.Builder { - let resultDecodedBuilder = Timestamp.Builder() - if let jsonValueDuration = jsonMap["duration"] as? Dictionary { - resultDecodedBuilder.duration = try Time.Builder.decodeToBuilder(jsonMap:jsonValueDuration).build() - + class override public func decodeToBuilder(jsonMap:Dictionary) throws -> Time.Builder { + let resultDecodedBuilder = Time.Builder() + if let jsonValueValue = jsonMap["value"] as? String { + resultDecodedBuilder.value = Int64(jsonValueValue)! + } else if let jsonValueValue = jsonMap["value"] as? Int { + resultDecodedBuilder.value = Int64(jsonValueValue) } - if let jsonValuePresentation = jsonMap["presentation"] as? Dictionary { - resultDecodedBuilder.presentation = try Time.Builder.decodeToBuilder(jsonMap:jsonValuePresentation).build() - + if let jsonValueScale = jsonMap["scale"] as? Int { + resultDecodedBuilder.scale = Int32(jsonValueScale) + } else if let jsonValueScale = jsonMap["scale"] as? String { + resultDecodedBuilder.scale = Int32(jsonValueScale)! + } + if let jsonValueFlags = jsonMap["flags"] as? UInt { + resultDecodedBuilder.flags = UInt32(jsonValueFlags) + } else if let jsonValueFlags = jsonMap["flags"] as? String { + resultDecodedBuilder.flags = UInt32(jsonValueFlags)! + } + if let jsonValueEpoch = jsonMap["epoch"] as? String { + resultDecodedBuilder.epoch = Int64(jsonValueEpoch)! + } else if let jsonValueEpoch = jsonMap["epoch"] as? Int { + resultDecodedBuilder.epoch = Int64(jsonValueEpoch) } return resultDecodedBuilder } - override class public func fromJSONToBuilder(data:Data) throws -> Timestamp.Builder { + override class public func fromJSONToBuilder(data:Data) throws -> Time.Builder { let jsonData = try JSONSerialization.jsonObject(with:data, options: JSONSerialization.ReadingOptions(rawValue: 0)) guard let jsDataCast = jsonData as? Dictionary else { throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") } - return try Timestamp.Builder.decodeToBuilder(jsonMap:jsDataCast) + return try Time.Builder.decodeToBuilder(jsonMap:jsDataCast) } } } -final public class Image : GeneratedMessage { +final public class Timestamp : GeneratedMessage { - public static func == (lhs: Image, rhs: Image) -> Bool { + public static func == (lhs: Timestamp, rhs: Timestamp) -> Bool { if lhs === rhs { return true } var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue) - fieldCheck = fieldCheck && (lhs.hasWidth == rhs.hasWidth) && (!lhs.hasWidth || lhs.width == rhs.width) - fieldCheck = fieldCheck && (lhs.hasHeight == rhs.hasHeight) && (!lhs.hasHeight || lhs.height == rhs.height) - fieldCheck = fieldCheck && (lhs.hasFormat == rhs.hasFormat) && (!lhs.hasFormat || lhs.format == rhs.format) - fieldCheck = fieldCheck && (lhs.hasAttachments == rhs.hasAttachments) && (!lhs.hasAttachments || lhs.attachments == rhs.attachments) - fieldCheck = fieldCheck && (lhs.hasData == rhs.hasData) && (!lhs.hasData || lhs.data == rhs.data) + fieldCheck = fieldCheck && (lhs.hasDuration == rhs.hasDuration) && (!lhs.hasDuration || lhs.duration == rhs.duration) + fieldCheck = fieldCheck && (lhs.hasPresentation == rhs.hasPresentation) && (!lhs.hasPresentation || lhs.presentation == rhs.presentation) fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) return fieldCheck } - - - //Nested type declaration start - - final public class AttachmentsEntry : GeneratedMessage { - - public static func == (lhs: Image.AttachmentsEntry, rhs: Image.AttachmentsEntry) -> Bool { - if lhs === rhs { - return true - } - var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue) - fieldCheck = fieldCheck && (lhs.hasKey == rhs.hasKey) && (!lhs.hasKey || lhs.key == rhs.key) - fieldCheck = fieldCheck && (lhs.hasValue == rhs.hasValue) && (!lhs.hasValue || lhs.value == rhs.value) - fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) - return fieldCheck - } - - public fileprivate(set) var key:String = "" - public fileprivate(set) var hasKey:Bool = false - - public fileprivate(set) var value:String = "" - public fileprivate(set) var hasValue:Bool = false - - required public init() { - super.init() + public fileprivate(set) var duration:Time! + public fileprivate(set) var hasDuration:Bool = false + public fileprivate(set) var presentation:Time! + public fileprivate(set) var hasPresentation:Bool = false + required public init() { + super.init() + } + override public func isInitialized() -> Bool { + return true + } + override public func writeTo(codedOutputStream: CodedOutputStream) throws { + if hasDuration { + try codedOutputStream.writeMessage(fieldNumber: 1, value:duration) } - override public func isInitialized() -> Bool { - return true + if hasPresentation { + try codedOutputStream.writeMessage(fieldNumber: 2, value:presentation) } - override public func writeTo(codedOutputStream: CodedOutputStream) throws { - if hasKey { - try codedOutputStream.writeString(fieldNumber: 1, value:key) - } - if hasValue { - try codedOutputStream.writeString(fieldNumber: 2, value:value) - } - try unknownFields.writeTo(codedOutputStream: codedOutputStream) + try unknownFields.writeTo(codedOutputStream: codedOutputStream) + } + override public func serializedSize() -> Int32 { + var serialize_size:Int32 = memoizedSerializedSize + if serialize_size != -1 { + return serialize_size } - override public func serializedSize() -> Int32 { - var serialize_size:Int32 = memoizedSerializedSize - if serialize_size != -1 { - return serialize_size - } - serialize_size = 0 - if hasKey { - serialize_size += key.computeStringSize(fieldNumber: 1) + serialize_size = 0 + if hasDuration { + if let varSizeduration = duration?.computeMessageSize(fieldNumber: 1) { + serialize_size += varSizeduration } - if hasValue { - serialize_size += value.computeStringSize(fieldNumber: 2) + } + if hasPresentation { + if let varSizepresentation = presentation?.computeMessageSize(fieldNumber: 2) { + serialize_size += varSizepresentation } - serialize_size += unknownFields.serializedSize() - memoizedSerializedSize = serialize_size - return serialize_size } - public class func getBuilder() -> Image.AttachmentsEntry.Builder { - return Image.AttachmentsEntry.classBuilder() as! Image.AttachmentsEntry.Builder + serialize_size += unknownFields.serializedSize() + memoizedSerializedSize = serialize_size + return serialize_size + } + public class func getBuilder() -> Timestamp.Builder { + return Timestamp.classBuilder() as! Timestamp.Builder + } + public func getBuilder() -> Timestamp.Builder { + return classBuilder() as! Timestamp.Builder + } + override public class func classBuilder() -> ProtocolBuffersMessageBuilder { + return Timestamp.Builder() + } + override public func classBuilder() -> ProtocolBuffersMessageBuilder { + return Timestamp.Builder() + } + public func toBuilder() throws -> Timestamp.Builder { + return try Timestamp.builderWithPrototype(prototype:self) + } + public class func builderWithPrototype(prototype:Timestamp) throws -> Timestamp.Builder { + return try Timestamp.Builder().mergeFrom(other:prototype) + } + override public func encode() throws -> Dictionary { + guard isInitialized() else { + throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message") } - public func getBuilder() -> Image.AttachmentsEntry.Builder { - return classBuilder() as! Image.AttachmentsEntry.Builder - } - override public class func classBuilder() -> ProtocolBuffersMessageBuilder { - return Image.AttachmentsEntry.Builder() - } - override public func classBuilder() -> ProtocolBuffersMessageBuilder { - return Image.AttachmentsEntry.Builder() - } - public func toBuilder() throws -> Image.AttachmentsEntry.Builder { - return try Image.AttachmentsEntry.builderWithPrototype(prototype:self) - } - public class func builderWithPrototype(prototype:Image.AttachmentsEntry) throws -> Image.AttachmentsEntry.Builder { - return try Image.AttachmentsEntry.Builder().mergeFrom(other:prototype) - } - override public func encode() throws -> Dictionary { - guard isInitialized() else { - throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message") - } - var jsonMap:Dictionary = Dictionary() - if hasKey { - jsonMap["key"] = key - } - if hasValue { - jsonMap["value"] = value - } - return jsonMap - } - override class public func decode(jsonMap:Dictionary) throws -> Image.AttachmentsEntry { - return try Image.AttachmentsEntry.Builder.decodeToBuilder(jsonMap:jsonMap).build() + var jsonMap:Dictionary = Dictionary() + if hasDuration { + jsonMap["duration"] = try duration.encode() } - override class public func fromJSON(data:Data) throws -> Image.AttachmentsEntry { - return try Image.AttachmentsEntry.Builder.fromJSONToBuilder(data:data).build() + if hasPresentation { + jsonMap["presentation"] = try presentation.encode() } - override public func getDescription(indent:String) throws -> String { - var output = "" - if hasKey { - output += "\(indent) key: \(key) \n" + return jsonMap + } + override class public func decode(jsonMap:Dictionary) throws -> Timestamp { + return try Timestamp.Builder.decodeToBuilder(jsonMap:jsonMap).build() + } + override class public func fromJSON(data:Data) throws -> Timestamp { + return try Timestamp.Builder.fromJSONToBuilder(data:data).build() + } + override public func getDescription(indent:String) throws -> String { + var output = "" + if hasDuration { + output += "\(indent) duration {\n" + if let outDescDuration = duration { + output += try outDescDuration.getDescription(indent: "\(indent) ") } - if hasValue { - output += "\(indent) value: \(value) \n" + output += "\(indent) }\n" + } + if hasPresentation { + output += "\(indent) presentation {\n" + if let outDescPresentation = presentation { + output += try outDescPresentation.getDescription(indent: "\(indent) ") } - output += unknownFields.getDescription(indent: indent) - return output + output += "\(indent) }\n" } - override public var hashValue:Int { - get { - var hashCode:Int = 7 - if hasKey { - hashCode = (hashCode &* 31) &+ key.hashValue + output += unknownFields.getDescription(indent: indent) + return output + } + override public var hashValue:Int { + get { + var hashCode:Int = 7 + if hasDuration { + if let hashValueduration = duration?.hashValue { + hashCode = (hashCode &* 31) &+ hashValueduration } - if hasValue { - hashCode = (hashCode &* 31) &+ value.hashValue + } + if hasPresentation { + if let hashValuepresentation = presentation?.hashValue { + hashCode = (hashCode &* 31) &+ hashValuepresentation } - hashCode = (hashCode &* 31) &+ unknownFields.hashValue - return hashCode } + hashCode = (hashCode &* 31) &+ unknownFields.hashValue + return hashCode } + } - //Meta information declaration start + //Meta information declaration start - override public class func className() -> String { - return "Image.AttachmentsEntry" - } - override public func className() -> String { - return "Image.AttachmentsEntry" - } - //Meta information declaration end + override public class func className() -> String { + return "Timestamp" + } + override public func className() -> String { + return "Timestamp" + } + //Meta information declaration end - final public class Builder : GeneratedMessageBuilder { - fileprivate var builderResult:Image.AttachmentsEntry = Image.AttachmentsEntry() - public func getMessage() -> Image.AttachmentsEntry { - return builderResult - } + final public class Builder : GeneratedMessageBuilder { + fileprivate var builderResult:Timestamp = Timestamp() + public func getMessage() -> Timestamp { + return builderResult + } - required override public init () { - super.init() - } - public var key:String { - get { - return builderResult.key - } - set (value) { - builderResult.hasKey = true - builderResult.key = value - } - } - public var hasKey:Bool { - get { - return builderResult.hasKey + required override public init () { + super.init() + } + public var duration:Time! { + get { + if durationBuilder_ != nil { + builderResult.duration = durationBuilder_.getMessage() } + return builderResult.duration } - @discardableResult - public func setKey(_ value:String) -> Image.AttachmentsEntry.Builder { - self.key = value - return self + set (value) { + builderResult.hasDuration = true + builderResult.duration = value } - @discardableResult - public func clearKey() -> Image.AttachmentsEntry.Builder{ - builderResult.hasKey = false - builderResult.key = "" - return self + } + public var hasDuration:Bool { + get { + return builderResult.hasDuration } - public var value:String { - get { - return builderResult.value - } - set (value) { - builderResult.hasValue = true - builderResult.value = value - } + } + fileprivate var durationBuilder_:Time.Builder! { + didSet { + builderResult.hasDuration = true } - public var hasValue:Bool { - get { - return builderResult.hasValue + } + public func getDurationBuilder() -> Time.Builder { + if durationBuilder_ == nil { + durationBuilder_ = Time.Builder() + builderResult.duration = durationBuilder_.getMessage() + if duration != nil { + try! durationBuilder_.mergeFrom(other: duration) } } - @discardableResult - public func setValue(_ value:String) -> Image.AttachmentsEntry.Builder { - self.value = value - return self - } - @discardableResult - public func clearValue() -> Image.AttachmentsEntry.Builder{ - builderResult.hasValue = false - builderResult.value = "" - return self + return durationBuilder_ + } + @discardableResult + public func setDuration(_ value:Time!) -> Timestamp.Builder { + self.duration = value + return self + } + @discardableResult + public func mergeDuration(value:Time) throws -> Timestamp.Builder { + if builderResult.hasDuration { + builderResult.duration = try Time.builderWithPrototype(prototype:builderResult.duration).mergeFrom(other: value).buildPartial() + } else { + builderResult.duration = value } - override public var internalGetResult:GeneratedMessage { - get { - return builderResult + builderResult.hasDuration = true + return self + } + @discardableResult + public func clearDuration() -> Timestamp.Builder { + durationBuilder_ = nil + builderResult.hasDuration = false + builderResult.duration = nil + return self + } + public var presentation:Time! { + get { + if presentationBuilder_ != nil { + builderResult.presentation = presentationBuilder_.getMessage() } + return builderResult.presentation } - @discardableResult - override public func clear() -> Image.AttachmentsEntry.Builder { - builderResult = Image.AttachmentsEntry() - return self - } - override public func clone() throws -> Image.AttachmentsEntry.Builder { - return try Image.AttachmentsEntry.builderWithPrototype(prototype:builderResult) + set (value) { + builderResult.hasPresentation = true + builderResult.presentation = value } - override public func build() throws -> Image.AttachmentsEntry { - try checkInitialized() - return buildPartial() + } + public var hasPresentation:Bool { + get { + return builderResult.hasPresentation } - public func buildPartial() -> Image.AttachmentsEntry { - let returnMe:Image.AttachmentsEntry = builderResult - return returnMe + } + fileprivate var presentationBuilder_:Time.Builder! { + didSet { + builderResult.hasPresentation = true } - @discardableResult - public func mergeFrom(other:Image.AttachmentsEntry) throws -> Image.AttachmentsEntry.Builder { - if other == Image.AttachmentsEntry() { - return self - } - if other.hasKey { - key = other.key + } + public func getPresentationBuilder() -> Time.Builder { + if presentationBuilder_ == nil { + presentationBuilder_ = Time.Builder() + builderResult.presentation = presentationBuilder_.getMessage() + if presentation != nil { + try! presentationBuilder_.mergeFrom(other: presentation) } - if other.hasValue { - value = other.value - } - try merge(unknownField: other.unknownFields) + } + return presentationBuilder_ + } + @discardableResult + public func setPresentation(_ value:Time!) -> Timestamp.Builder { + self.presentation = value + return self + } + @discardableResult + public func mergePresentation(value:Time) throws -> Timestamp.Builder { + if builderResult.hasPresentation { + builderResult.presentation = try Time.builderWithPrototype(prototype:builderResult.presentation).mergeFrom(other: value).buildPartial() + } else { + builderResult.presentation = value + } + builderResult.hasPresentation = true + return self + } + @discardableResult + public func clearPresentation() -> Timestamp.Builder { + presentationBuilder_ = nil + builderResult.hasPresentation = false + builderResult.presentation = nil + return self + } + override public var internalGetResult:GeneratedMessage { + get { + return builderResult + } + } + @discardableResult + override public func clear() -> Timestamp.Builder { + builderResult = Timestamp() + return self + } + override public func clone() throws -> Timestamp.Builder { + return try Timestamp.builderWithPrototype(prototype:builderResult) + } + override public func build() throws -> Timestamp { + try checkInitialized() + return buildPartial() + } + public func buildPartial() -> Timestamp { + let returnMe:Timestamp = builderResult + return returnMe + } + @discardableResult + public func mergeFrom(other:Timestamp) throws -> Timestamp.Builder { + if other == Timestamp() { return self } - @discardableResult - override public func mergeFrom(codedInputStream: CodedInputStream) throws -> Image.AttachmentsEntry.Builder { - return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry()) + if (other.hasDuration) { + try mergeDuration(value: other.duration) } - @discardableResult - override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Image.AttachmentsEntry.Builder { - let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(copyFrom:self.unknownFields) - while (true) { - let protobufTag = try codedInputStream.readTag() - switch protobufTag { - case 0: - self.unknownFields = try unknownFieldsBuilder.build() - return self + if (other.hasPresentation) { + try mergePresentation(value: other.presentation) + } + try merge(unknownField: other.unknownFields) + return self + } + @discardableResult + override public func mergeFrom(codedInputStream: CodedInputStream) throws -> Timestamp.Builder { + return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry()) + } + @discardableResult + override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Timestamp.Builder { + let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(copyFrom:self.unknownFields) + while (true) { + let protobufTag = try codedInputStream.readTag() + switch protobufTag { + case 0: + self.unknownFields = try unknownFieldsBuilder.build() + return self - case 10: - key = try codedInputStream.readString() + case 10: + let subBuilder:Time.Builder = Time.Builder() + if hasDuration { + try subBuilder.mergeFrom(other: duration) + } + try codedInputStream.readMessage(builder: subBuilder, extensionRegistry:extensionRegistry) + duration = subBuilder.buildPartial() - case 18: - value = try codedInputStream.readString() + case 18: + let subBuilder:Time.Builder = Time.Builder() + if hasPresentation { + try subBuilder.mergeFrom(other: presentation) + } + try codedInputStream.readMessage(builder: subBuilder, extensionRegistry:extensionRegistry) + presentation = subBuilder.buildPartial() - default: - if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) { - unknownFields = try unknownFieldsBuilder.build() - return self - } + default: + if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) { + unknownFields = try unknownFieldsBuilder.build() + return self } } } - class override public func decodeToBuilder(jsonMap:Dictionary) throws -> Image.AttachmentsEntry.Builder { - let resultDecodedBuilder = Image.AttachmentsEntry.Builder() - if let jsonValueKey = jsonMap["key"] as? String { - resultDecodedBuilder.key = jsonValueKey - } - if let jsonValueValue = jsonMap["value"] as? String { - resultDecodedBuilder.value = jsonValueValue - } - return resultDecodedBuilder + } + class override public func decodeToBuilder(jsonMap:Dictionary) throws -> Timestamp.Builder { + let resultDecodedBuilder = Timestamp.Builder() + if let jsonValueDuration = jsonMap["duration"] as? Dictionary { + resultDecodedBuilder.duration = try Time.Builder.decodeToBuilder(jsonMap:jsonValueDuration).build() + } - override class public func fromJSONToBuilder(data:Data) throws -> Image.AttachmentsEntry.Builder { - let jsonData = try JSONSerialization.jsonObject(with:data, options: JSONSerialization.ReadingOptions(rawValue: 0)) - guard let jsDataCast = jsonData as? Dictionary else { - throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") - } - return try Image.AttachmentsEntry.Builder.decodeToBuilder(jsonMap:jsDataCast) + if let jsonValuePresentation = jsonMap["presentation"] as? Dictionary { + resultDecodedBuilder.presentation = try Time.Builder.decodeToBuilder(jsonMap:jsonValuePresentation).build() + + } + return resultDecodedBuilder + } + override class public func fromJSONToBuilder(data:Data) throws -> Timestamp.Builder { + let jsonData = try JSONSerialization.jsonObject(with:data, options: JSONSerialization.ReadingOptions(rawValue: 0)) + guard let jsDataCast = jsonData as? Dictionary else { + throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") } + return try Timestamp.Builder.decodeToBuilder(jsonMap:jsDataCast) } + } +} + +final public class Image : GeneratedMessage { + + public static func == (lhs: Image, rhs: Image) -> Bool { + if lhs === rhs { + return true + } + var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue) + fieldCheck = fieldCheck && (lhs.hasWidth == rhs.hasWidth) && (!lhs.hasWidth || lhs.width == rhs.width) + fieldCheck = fieldCheck && (lhs.hasHeight == rhs.hasHeight) && (!lhs.hasHeight || lhs.height == rhs.height) + fieldCheck = fieldCheck && (lhs.hasFormat == rhs.hasFormat) && (!lhs.hasFormat || lhs.format == rhs.format) + fieldCheck = fieldCheck && (lhs.hasAttachments == rhs.hasAttachments) && (!lhs.hasAttachments || lhs.attachments == rhs.attachments) + fieldCheck = fieldCheck && (lhs.hasData == rhs.hasData) && (!lhs.hasData || lhs.data == rhs.data) + fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) + return fieldCheck } - //Nested type declaration end - public fileprivate(set) var width:Int64 = Int64(0) - public fileprivate(set) var hasWidth:Bool = false - public fileprivate(set) var height:Int64 = Int64(0) - public fileprivate(set) var hasHeight:Bool = false + //Nested type declaration start - public fileprivate(set) var format:UInt32 = UInt32(0) - public fileprivate(set) var hasFormat:Bool = false + final public class AttachmentsEntry : GeneratedMessage { - public fileprivate(set) var attachments:Dictionary = Dictionary() + public static func == (lhs: Image.AttachmentsEntry, rhs: Image.AttachmentsEntry) -> Bool { + if lhs === rhs { + return true + } + var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue) + fieldCheck = fieldCheck && (lhs.hasKey == rhs.hasKey) && (!lhs.hasKey || lhs.key == rhs.key) + fieldCheck = fieldCheck && (lhs.hasValue == rhs.hasValue) && (!lhs.hasValue || lhs.value == rhs.value) + fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) + return fieldCheck + } - public fileprivate(set) var hasAttachments:Bool = false - public fileprivate(set) var data:Data = Data() - public fileprivate(set) var hasData:Bool = false + public fileprivate(set) var key:String! = nil + public fileprivate(set) var hasKey:Bool = false - required public init() { - super.init() - } - override public func isInitialized() -> Bool { - return true - } - override public func writeTo(codedOutputStream: CodedOutputStream) throws { - if hasWidth { - try codedOutputStream.writeInt64(fieldNumber: 1, value:width) + public fileprivate(set) var value:String! = nil + public fileprivate(set) var hasValue:Bool = false + + required public init() { + super.init() } - if hasHeight { - try codedOutputStream.writeInt64(fieldNumber: 2, value:height) + override public func isInitialized() -> Bool { + return true } - if hasFormat { - try codedOutputStream.writeUInt32(fieldNumber: 3, value:format) + override public func writeTo(codedOutputStream: CodedOutputStream) throws { + if hasKey { + try codedOutputStream.writeString(fieldNumber: 1, value:key) + } + if hasValue { + try codedOutputStream.writeString(fieldNumber: 2, value:value) + } + try unknownFields.writeTo(codedOutputStream: codedOutputStream) } - if hasAttachments { - for (keyAttachments, valueAttachments) in attachments { - let valueOfAttachments = try! Image.AttachmentsEntry.Builder().setKey(keyAttachments).setValue(valueAttachments).build() - try codedOutputStream.writeMessage(fieldNumber: 4, value:valueOfAttachments) - } + override public func serializedSize() -> Int32 { + var serialize_size:Int32 = memoizedSerializedSize + if serialize_size != -1 { + return serialize_size + } + + serialize_size = 0 + if hasKey { + serialize_size += key.computeStringSize(fieldNumber: 1) + } + if hasValue { + serialize_size += value.computeStringSize(fieldNumber: 2) + } + serialize_size += unknownFields.serializedSize() + memoizedSerializedSize = serialize_size + return serialize_size } - if hasData { - try codedOutputStream.writeData(fieldNumber: 5, value:data) + public class func getBuilder() -> Image.AttachmentsEntry.Builder { + return Image.AttachmentsEntry.classBuilder() as! Image.AttachmentsEntry.Builder } - try unknownFields.writeTo(codedOutputStream: codedOutputStream) - } - override public func serializedSize() -> Int32 { - var serialize_size:Int32 = memoizedSerializedSize - if serialize_size != -1 { - return serialize_size + public func getBuilder() -> Image.AttachmentsEntry.Builder { + return classBuilder() as! Image.AttachmentsEntry.Builder } - - serialize_size = 0 - if hasWidth { - serialize_size += width.computeInt64Size(fieldNumber: 1) + override public class func classBuilder() -> ProtocolBuffersMessageBuilder { + return Image.AttachmentsEntry.Builder() } - if hasHeight { - serialize_size += height.computeInt64Size(fieldNumber: 2) + override public func classBuilder() -> ProtocolBuffersMessageBuilder { + return Image.AttachmentsEntry.Builder() } - if hasFormat { - serialize_size += format.computeUInt32Size(fieldNumber: 3) + public func toBuilder() throws -> Image.AttachmentsEntry.Builder { + return try Image.AttachmentsEntry.builderWithPrototype(prototype:self) } - if hasAttachments { - for (keyAttachments, valueAttachments) in attachments { - let valueOfAttachments = try! Image.AttachmentsEntry.Builder().setKey(keyAttachments).setValue(valueAttachments).build() - serialize_size += valueOfAttachments.computeMessageSize(fieldNumber: 4) - } - } - if hasData { - serialize_size += data.computeDataSize(fieldNumber: 5) - } - serialize_size += unknownFields.serializedSize() - memoizedSerializedSize = serialize_size - return serialize_size - } - public class func getBuilder() -> Image.Builder { - return Image.classBuilder() as! Image.Builder - } - public func getBuilder() -> Image.Builder { - return classBuilder() as! Image.Builder - } - override public class func classBuilder() -> ProtocolBuffersMessageBuilder { - return Image.Builder() - } - override public func classBuilder() -> ProtocolBuffersMessageBuilder { - return Image.Builder() - } - public func toBuilder() throws -> Image.Builder { - return try Image.builderWithPrototype(prototype:self) - } - public class func builderWithPrototype(prototype:Image) throws -> Image.Builder { - return try Image.Builder().mergeFrom(other:prototype) - } - override public func encode() throws -> Dictionary { - guard isInitialized() else { - throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message") + public class func builderWithPrototype(prototype:Image.AttachmentsEntry) throws -> Image.AttachmentsEntry.Builder { + return try Image.AttachmentsEntry.Builder().mergeFrom(other:prototype) } + override public func encode() throws -> Dictionary { + guard isInitialized() else { + throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message") + } - var jsonMap:Dictionary = Dictionary() - if hasWidth { - jsonMap["width"] = "\(width)" - } - if hasHeight { - jsonMap["height"] = "\(height)" - } - if hasFormat { - jsonMap["format"] = UInt(format) - } - if hasAttachments { - var mapAttachments = Dictionary() - for (keyAttachments, valueAttachments) in attachments { - mapAttachments["\(keyAttachments)"] = valueAttachments + var jsonMap:Dictionary = Dictionary() + if hasKey { + jsonMap["key"] = key } - jsonMap["attachments"] = mapAttachments - } - if hasData { - jsonMap["data"] = data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)) - } - return jsonMap - } - override class public func decode(jsonMap:Dictionary) throws -> Image { - return try Image.Builder.decodeToBuilder(jsonMap:jsonMap).build() - } - override class public func fromJSON(data:Data) throws -> Image { - return try Image.Builder.fromJSONToBuilder(data:data).build() - } - override public func getDescription(indent:String) throws -> String { - var output = "" - if hasWidth { - output += "\(indent) width: \(width) \n" - } - if hasHeight { - output += "\(indent) height: \(height) \n" - } - if hasFormat { - output += "\(indent) format: \(format) \n" + if hasValue { + jsonMap["value"] = value + } + return jsonMap } - if hasAttachments { - output += "\(indent) attachments: \(attachments) \n" + override class public func decode(jsonMap:Dictionary) throws -> Image.AttachmentsEntry { + return try Image.AttachmentsEntry.Builder.decodeToBuilder(jsonMap:jsonMap).build() } - if hasData { - output += "\(indent) data: \(data) \n" + override class public func fromJSON(data:Data) throws -> Image.AttachmentsEntry { + return try Image.AttachmentsEntry.Builder.fromJSONToBuilder(data:data).build() } - output += unknownFields.getDescription(indent: indent) - return output - } - override public var hashValue:Int { - get { - var hashCode:Int = 7 - if hasWidth { - hashCode = (hashCode &* 31) &+ width.hashValue - } - if hasHeight { - hashCode = (hashCode &* 31) &+ height.hashValue + override public func getDescription(indent:String) throws -> String { + var output = "" + if hasKey { + output += "\(indent) key: \(key) \n" } - if hasFormat { - hashCode = (hashCode &* 31) &+ format.hashValue + if hasValue { + output += "\(indent) value: \(value) \n" } - if hasAttachments { - for (keyAttachments, valueAttachments) in attachments { - hashCode = (hashCode &* 31) &+ keyAttachments.hashValue - hashCode = (hashCode &* 31) &+ valueAttachments.hashValue + output += unknownFields.getDescription(indent: indent) + return output + } + override public var hashValue:Int { + get { + var hashCode:Int = 7 + if hasKey { + hashCode = (hashCode &* 31) &+ key.hashValue } + if hasValue { + hashCode = (hashCode &* 31) &+ value.hashValue + } + hashCode = (hashCode &* 31) &+ unknownFields.hashValue + return hashCode } - if hasData { - hashCode = (hashCode &* 31) &+ data.hashValue - } - hashCode = (hashCode &* 31) &+ unknownFields.hashValue - return hashCode } - } - //Meta information declaration start - - override public class func className() -> String { - return "Image" - } - override public func className() -> String { - return "Image" - } - //Meta information declaration end + //Meta information declaration start - final public class Builder : GeneratedMessageBuilder { - fileprivate var builderResult:Image = Image() - public func getMessage() -> Image { - return builderResult + override public class func className() -> String { + return "Image.AttachmentsEntry" } - - required override public init () { - super.init() + override public func className() -> String { + return "Image.AttachmentsEntry" } - public var width:Int64 { - get { - return builderResult.width + //Meta information declaration end + + final public class Builder : GeneratedMessageBuilder { + fileprivate var builderResult:Image.AttachmentsEntry = Image.AttachmentsEntry() + public func getMessage() -> Image.AttachmentsEntry { + return builderResult } - set (value) { - builderResult.hasWidth = true - builderResult.width = value + + required override public init () { + super.init() } - } - public var hasWidth:Bool { - get { - return builderResult.hasWidth + public var key:String { + get { + return builderResult.key + } + set (value) { + builderResult.hasKey = true + builderResult.key = value + } } - } - @discardableResult - public func setWidth(_ value:Int64) -> Image.Builder { - self.width = value - return self - } - @discardableResult - public func clearWidth() -> Image.Builder{ - builderResult.hasWidth = false - builderResult.width = Int64(0) - return self - } - public var height:Int64 { - get { - return builderResult.height + public var hasKey:Bool { + get { + return builderResult.hasKey + } } - set (value) { - builderResult.hasHeight = true - builderResult.height = value + @discardableResult + public func setKey(_ value:String) -> Image.AttachmentsEntry.Builder { + self.key = value + return self } - } - public var hasHeight:Bool { - get { - return builderResult.hasHeight + @discardableResult + public func clearKey() -> Image.AttachmentsEntry.Builder{ + builderResult.hasKey = false + builderResult.key = nil + return self } - } - @discardableResult - public func setHeight(_ value:Int64) -> Image.Builder { - self.height = value - return self - } - @discardableResult - public func clearHeight() -> Image.Builder{ - builderResult.hasHeight = false - builderResult.height = Int64(0) - return self - } - public var format:UInt32 { - get { - return builderResult.format + public var value:String { + get { + return builderResult.value + } + set (value) { + builderResult.hasValue = true + builderResult.value = value + } } - set (value) { - builderResult.hasFormat = true - builderResult.format = value + public var hasValue:Bool { + get { + return builderResult.hasValue + } } - } - public var hasFormat:Bool { - get { - return builderResult.hasFormat + @discardableResult + public func setValue(_ value:String) -> Image.AttachmentsEntry.Builder { + self.value = value + return self } - } - @discardableResult - public func setFormat(_ value:UInt32) -> Image.Builder { - self.format = value - return self - } - @discardableResult - public func clearFormat() -> Image.Builder{ - builderResult.hasFormat = false - builderResult.format = UInt32(0) - return self - } - public var hasAttachments:Bool { - get { - return builderResult.hasAttachments - } - } - public var attachments:Dictionary { - get { - return builderResult.attachments - } - set (value) { - builderResult.hasAttachments = true - builderResult.attachments = value - } - } - @discardableResult - public func setAttachments(_ value:Dictionary) -> Image.Builder { - self.attachments = value - return self - } - @discardableResult - public func clearAttachments() -> Image.Builder{ - builderResult.hasAttachments = false - builderResult.attachments = Dictionary() - return self - } - public var data:Data { - get { - return builderResult.data - } - set (value) { - builderResult.hasData = true - builderResult.data = value - } - } - public var hasData:Bool { - get { - return builderResult.hasData + @discardableResult + public func clearValue() -> Image.AttachmentsEntry.Builder{ + builderResult.hasValue = false + builderResult.value = nil + return self } - } - @discardableResult - public func setData(_ value:Data) -> Image.Builder { - self.data = value - return self - } - @discardableResult - public func clearData() -> Image.Builder{ - builderResult.hasData = false - builderResult.data = Data() - return self - } - override public var internalGetResult:GeneratedMessage { - get { - return builderResult + override public var internalGetResult:GeneratedMessage { + get { + return builderResult + } } - } - @discardableResult - override public func clear() -> Image.Builder { - builderResult = Image() - return self - } - override public func clone() throws -> Image.Builder { - return try Image.builderWithPrototype(prototype:builderResult) - } - override public func build() throws -> Image { - try checkInitialized() - return buildPartial() - } - public func buildPartial() -> Image { - let returnMe:Image = builderResult - return returnMe - } - @discardableResult - public func mergeFrom(other:Image) throws -> Image.Builder { - if other == Image() { + @discardableResult + override public func clear() -> Image.AttachmentsEntry.Builder { + builderResult = Image.AttachmentsEntry() return self } - if other.hasWidth { - width = other.width + override public func clone() throws -> Image.AttachmentsEntry.Builder { + return try Image.AttachmentsEntry.builderWithPrototype(prototype:builderResult) } - if other.hasHeight { - height = other.height + override public func build() throws -> Image.AttachmentsEntry { + try checkInitialized() + return buildPartial() } - if other.hasFormat { - format = other.format + public func buildPartial() -> Image.AttachmentsEntry { + let returnMe:Image.AttachmentsEntry = builderResult + return returnMe } - if other.hasAttachments { - attachments = other.attachments + @discardableResult + public func mergeFrom(other:Image.AttachmentsEntry) throws -> Image.AttachmentsEntry.Builder { + if other == Image.AttachmentsEntry() { + return self + } + if other.hasKey { + key = other.key + } + if other.hasValue { + value = other.value + } + try merge(unknownField: other.unknownFields) + return self } - if other.hasData { - data = other.data + @discardableResult + override public func mergeFrom(codedInputStream: CodedInputStream) throws -> Image.AttachmentsEntry.Builder { + return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry()) } - try merge(unknownField: other.unknownFields) - return self - } - @discardableResult - override public func mergeFrom(codedInputStream: CodedInputStream) throws -> Image.Builder { - return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry()) - } - @discardableResult - override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Image.Builder { - let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(copyFrom:self.unknownFields) - while (true) { - let protobufTag = try codedInputStream.readTag() - switch protobufTag { - case 0: - self.unknownFields = try unknownFieldsBuilder.build() - return self - - case 8: - width = try codedInputStream.readInt64() - - case 16: - height = try codedInputStream.readInt64() - - case 24: - format = try codedInputStream.readUInt32() + @discardableResult + override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Image.AttachmentsEntry.Builder { + let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(copyFrom:self.unknownFields) + while (true) { + let protobufTag = try codedInputStream.readTag() + switch protobufTag { + case 0: + self.unknownFields = try unknownFieldsBuilder.build() + return self - case 34: - let subBuilder = Image.AttachmentsEntry.Builder() - try codedInputStream.readMessage(builder: subBuilder, extensionRegistry:extensionRegistry) - let buildOfAttachments = subBuilder.buildPartial() - attachments[buildOfAttachments.key] = buildOfAttachments.value + case 10: + key = try codedInputStream.readString() - case 42: - data = try codedInputStream.readData() + case 18: + value = try codedInputStream.readString() - default: - if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) { - unknownFields = try unknownFieldsBuilder.build() - return self + default: + if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) { + unknownFields = try unknownFieldsBuilder.build() + return self + } } } } - } - class override public func decodeToBuilder(jsonMap:Dictionary) throws -> Image.Builder { - let resultDecodedBuilder = Image.Builder() - if let jsonValueWidth = jsonMap["width"] as? String { - resultDecodedBuilder.width = Int64(jsonValueWidth)! - } else if let jsonValueWidth = jsonMap["width"] as? Int { - resultDecodedBuilder.width = Int64(jsonValueWidth) - } - if let jsonValueHeight = jsonMap["height"] as? String { - resultDecodedBuilder.height = Int64(jsonValueHeight)! - } else if let jsonValueHeight = jsonMap["height"] as? Int { - resultDecodedBuilder.height = Int64(jsonValueHeight) - } - if let jsonValueFormat = jsonMap["format"] as? UInt { - resultDecodedBuilder.format = UInt32(jsonValueFormat) - } else if let jsonValueFormat = jsonMap["format"] as? String { - resultDecodedBuilder.format = UInt32(jsonValueFormat)! - } - if let jsonValueAttachments = jsonMap["attachments"] as? Dictionary { - var mapAttachments = Dictionary() - for (keyAttachments, valueAttachments) in jsonValueAttachments { - guard let keyFromAttachments = String(keyAttachments) else { - throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") - } - mapAttachments[keyFromAttachments] = valueAttachments + class override public func decodeToBuilder(jsonMap:Dictionary) throws -> Image.AttachmentsEntry.Builder { + let resultDecodedBuilder = Image.AttachmentsEntry.Builder() + if let jsonValueKey = jsonMap["key"] as? String { + resultDecodedBuilder.key = jsonValueKey } - resultDecodedBuilder.attachments = mapAttachments - } - if let jsonValueData = jsonMap["data"] as? String { - resultDecodedBuilder.data = Data(base64Encoded:jsonValueData, options: Data.Base64DecodingOptions(rawValue:0))! + if let jsonValueValue = jsonMap["value"] as? String { + resultDecodedBuilder.value = jsonValueValue + } + return resultDecodedBuilder } - return resultDecodedBuilder - } - override class public func fromJSONToBuilder(data:Data) throws -> Image.Builder { - let jsonData = try JSONSerialization.jsonObject(with:data, options: JSONSerialization.ReadingOptions(rawValue: 0)) - guard let jsDataCast = jsonData as? Dictionary else { - throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") + override class public func fromJSONToBuilder(data:Data) throws -> Image.AttachmentsEntry.Builder { + let jsonData = try JSONSerialization.jsonObject(with:data, options: JSONSerialization.ReadingOptions(rawValue: 0)) + guard let jsDataCast = jsonData as? Dictionary else { + throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") + } + return try Image.AttachmentsEntry.Builder.decodeToBuilder(jsonMap:jsDataCast) } - return try Image.Builder.decodeToBuilder(jsonMap:jsDataCast) } - } -} + } -final public class FormatDescription : GeneratedMessage { + //Nested type declaration end - public static func == (lhs: FormatDescription, rhs: FormatDescription) -> Bool { - if lhs === rhs { - return true - } - var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue) - fieldCheck = fieldCheck && (lhs.hasMediaType == rhs.hasMediaType) && (!lhs.hasMediaType || lhs.mediaType == rhs.mediaType) - fieldCheck = fieldCheck && (lhs.hasMediaSubtype == rhs.hasMediaSubtype) && (!lhs.hasMediaSubtype || lhs.mediaSubtype == rhs.mediaSubtype) - fieldCheck = fieldCheck && (lhs.hasExtensions == rhs.hasExtensions) && (!lhs.hasExtensions || lhs.extensions == rhs.extensions) - fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) - return fieldCheck - } + public fileprivate(set) var width:Int64! = nil + public fileprivate(set) var hasWidth:Bool = false + public fileprivate(set) var height:Int64! = nil + public fileprivate(set) var hasHeight:Bool = false + public fileprivate(set) var format:UInt32! = nil + public fileprivate(set) var hasFormat:Bool = false - //Nested type declaration start + public fileprivate(set) var attachments:Dictionary = Dictionary() - final public class ExtensionsEntry : GeneratedMessage { + public fileprivate(set) var hasAttachments:Bool = false + public fileprivate(set) var data:Data! = nil + public fileprivate(set) var hasData:Bool = false - public static func == (lhs: FormatDescription.ExtensionsEntry, rhs: FormatDescription.ExtensionsEntry) -> Bool { - if lhs === rhs { - return true - } - var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue) - fieldCheck = fieldCheck && (lhs.hasKey == rhs.hasKey) && (!lhs.hasKey || lhs.key == rhs.key) - fieldCheck = fieldCheck && (lhs.hasValue == rhs.hasValue) && (!lhs.hasValue || lhs.value == rhs.value) - fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) - return fieldCheck + required public init() { + super.init() + } + override public func isInitialized() -> Bool { + return true + } + override public func writeTo(codedOutputStream: CodedOutputStream) throws { + if hasWidth { + try codedOutputStream.writeInt64(fieldNumber: 1, value:width) + } + if hasHeight { + try codedOutputStream.writeInt64(fieldNumber: 2, value:height) + } + if hasFormat { + try codedOutputStream.writeUInt32(fieldNumber: 3, value:format) + } + if hasAttachments { + for (keyAttachments, valueAttachments) in attachments { + let valueOfAttachments = try! Image.AttachmentsEntry.Builder().setKey(keyAttachments).setValue(valueAttachments).build() + try codedOutputStream.writeMessage(fieldNumber: 4, value:valueOfAttachments) + } + } + if hasData { + try codedOutputStream.writeData(fieldNumber: 5, value:data) + } + try unknownFields.writeTo(codedOutputStream: codedOutputStream) + } + override public func serializedSize() -> Int32 { + var serialize_size:Int32 = memoizedSerializedSize + if serialize_size != -1 { + return serialize_size } - public fileprivate(set) var key:String = "" - public fileprivate(set) var hasKey:Bool = false - - public fileprivate(set) var value:String = "" - public fileprivate(set) var hasValue:Bool = false - - required public init() { - super.init() + serialize_size = 0 + if hasWidth { + serialize_size += width.computeInt64Size(fieldNumber: 1) } - override public func isInitialized() -> Bool { - return true + if hasHeight { + serialize_size += height.computeInt64Size(fieldNumber: 2) } - override public func writeTo(codedOutputStream: CodedOutputStream) throws { - if hasKey { - try codedOutputStream.writeString(fieldNumber: 1, value:key) - } - if hasValue { - try codedOutputStream.writeString(fieldNumber: 2, value:value) - } - try unknownFields.writeTo(codedOutputStream: codedOutputStream) + if hasFormat { + serialize_size += format.computeUInt32Size(fieldNumber: 3) } - override public func serializedSize() -> Int32 { - var serialize_size:Int32 = memoizedSerializedSize - if serialize_size != -1 { - return serialize_size + if hasAttachments { + for (keyAttachments, valueAttachments) in attachments { + let valueOfAttachments = try! Image.AttachmentsEntry.Builder().setKey(keyAttachments).setValue(valueAttachments).build() + serialize_size += valueOfAttachments.computeMessageSize(fieldNumber: 4) } + } + if hasData { + serialize_size += data.computeDataSize(fieldNumber: 5) + } + serialize_size += unknownFields.serializedSize() + memoizedSerializedSize = serialize_size + return serialize_size + } + public class func getBuilder() -> Image.Builder { + return Image.classBuilder() as! Image.Builder + } + public func getBuilder() -> Image.Builder { + return classBuilder() as! Image.Builder + } + override public class func classBuilder() -> ProtocolBuffersMessageBuilder { + return Image.Builder() + } + override public func classBuilder() -> ProtocolBuffersMessageBuilder { + return Image.Builder() + } + public func toBuilder() throws -> Image.Builder { + return try Image.builderWithPrototype(prototype:self) + } + public class func builderWithPrototype(prototype:Image) throws -> Image.Builder { + return try Image.Builder().mergeFrom(other:prototype) + } + override public func encode() throws -> Dictionary { + guard isInitialized() else { + throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message") + } - serialize_size = 0 - if hasKey { - serialize_size += key.computeStringSize(fieldNumber: 1) - } - if hasValue { - serialize_size += value.computeStringSize(fieldNumber: 2) - } - serialize_size += unknownFields.serializedSize() - memoizedSerializedSize = serialize_size - return serialize_size + var jsonMap:Dictionary = Dictionary() + if hasWidth { + jsonMap["width"] = "\(width)" } - public class func getBuilder() -> FormatDescription.ExtensionsEntry.Builder { - return FormatDescription.ExtensionsEntry.classBuilder() as! FormatDescription.ExtensionsEntry.Builder + if hasHeight { + jsonMap["height"] = "\(height)" } - public func getBuilder() -> FormatDescription.ExtensionsEntry.Builder { - return classBuilder() as! FormatDescription.ExtensionsEntry.Builder + if hasFormat { + jsonMap["format"] = UInt(format) } - override public class func classBuilder() -> ProtocolBuffersMessageBuilder { - return FormatDescription.ExtensionsEntry.Builder() + if hasAttachments { + var mapAttachments = Dictionary() + for (keyAttachments, valueAttachments) in attachments { + mapAttachments["\(keyAttachments)"] = valueAttachments + } + jsonMap["attachments"] = mapAttachments } - override public func classBuilder() -> ProtocolBuffersMessageBuilder { - return FormatDescription.ExtensionsEntry.Builder() + if hasData { + jsonMap["data"] = data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)) } - public func toBuilder() throws -> FormatDescription.ExtensionsEntry.Builder { - return try FormatDescription.ExtensionsEntry.builderWithPrototype(prototype:self) + return jsonMap + } + override class public func decode(jsonMap:Dictionary) throws -> Image { + return try Image.Builder.decodeToBuilder(jsonMap:jsonMap).build() + } + override class public func fromJSON(data:Data) throws -> Image { + return try Image.Builder.fromJSONToBuilder(data:data).build() + } + override public func getDescription(indent:String) throws -> String { + var output = "" + if hasWidth { + output += "\(indent) width: \(width) \n" } - public class func builderWithPrototype(prototype:FormatDescription.ExtensionsEntry) throws -> FormatDescription.ExtensionsEntry.Builder { - return try FormatDescription.ExtensionsEntry.Builder().mergeFrom(other:prototype) + if hasHeight { + output += "\(indent) height: \(height) \n" } - override public func encode() throws -> Dictionary { - guard isInitialized() else { - throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message") - } - - var jsonMap:Dictionary = Dictionary() - if hasKey { - jsonMap["key"] = key - } - if hasValue { - jsonMap["value"] = value - } - return jsonMap + if hasFormat { + output += "\(indent) format: \(format) \n" } - override class public func decode(jsonMap:Dictionary) throws -> FormatDescription.ExtensionsEntry { - return try FormatDescription.ExtensionsEntry.Builder.decodeToBuilder(jsonMap:jsonMap).build() + if hasAttachments { + output += "\(indent) attachments: \(attachments) \n" } - override class public func fromJSON(data:Data) throws -> FormatDescription.ExtensionsEntry { - return try FormatDescription.ExtensionsEntry.Builder.fromJSONToBuilder(data:data).build() + if hasData { + output += "\(indent) data: \(data) \n" } - override public func getDescription(indent:String) throws -> String { - var output = "" - if hasKey { - output += "\(indent) key: \(key) \n" + output += unknownFields.getDescription(indent: indent) + return output + } + override public var hashValue:Int { + get { + var hashCode:Int = 7 + if hasWidth { + hashCode = (hashCode &* 31) &+ width.hashValue } - if hasValue { - output += "\(indent) value: \(value) \n" + if hasHeight { + hashCode = (hashCode &* 31) &+ height.hashValue } - output += unknownFields.getDescription(indent: indent) - return output - } - override public var hashValue:Int { - get { - var hashCode:Int = 7 - if hasKey { - hashCode = (hashCode &* 31) &+ key.hashValue - } - if hasValue { - hashCode = (hashCode &* 31) &+ value.hashValue + if hasFormat { + hashCode = (hashCode &* 31) &+ format.hashValue + } + if hasAttachments { + for (keyAttachments, valueAttachments) in attachments { + hashCode = (hashCode &* 31) &+ keyAttachments.hashValue + hashCode = (hashCode &* 31) &+ valueAttachments.hashValue } - hashCode = (hashCode &* 31) &+ unknownFields.hashValue - return hashCode } + if hasData { + hashCode = (hashCode &* 31) &+ data.hashValue + } + hashCode = (hashCode &* 31) &+ unknownFields.hashValue + return hashCode } + } - //Meta information declaration start + //Meta information declaration start - override public class func className() -> String { - return "FormatDescription.ExtensionsEntry" - } - override public func className() -> String { - return "FormatDescription.ExtensionsEntry" - } - //Meta information declaration end + override public class func className() -> String { + return "Image" + } + override public func className() -> String { + return "Image" + } + //Meta information declaration end - final public class Builder : GeneratedMessageBuilder { - fileprivate var builderResult:FormatDescription.ExtensionsEntry = FormatDescription.ExtensionsEntry() - public func getMessage() -> FormatDescription.ExtensionsEntry { - return builderResult - } + final public class Builder : GeneratedMessageBuilder { + fileprivate var builderResult:Image = Image() + public func getMessage() -> Image { + return builderResult + } - required override public init () { - super.init() + required override public init () { + super.init() + } + public var width:Int64 { + get { + return builderResult.width } - public var key:String { - get { - return builderResult.key - } - set (value) { - builderResult.hasKey = true - builderResult.key = value - } + set (value) { + builderResult.hasWidth = true + builderResult.width = value } - public var hasKey:Bool { - get { - return builderResult.hasKey - } + } + public var hasWidth:Bool { + get { + return builderResult.hasWidth } - @discardableResult - public func setKey(_ value:String) -> FormatDescription.ExtensionsEntry.Builder { - self.key = value - return self + } + @discardableResult + public func setWidth(_ value:Int64) -> Image.Builder { + self.width = value + return self + } + @discardableResult + public func clearWidth() -> Image.Builder{ + builderResult.hasWidth = false + builderResult.width = nil + return self + } + public var height:Int64 { + get { + return builderResult.height } - @discardableResult - public func clearKey() -> FormatDescription.ExtensionsEntry.Builder{ - builderResult.hasKey = false - builderResult.key = "" - return self + set (value) { + builderResult.hasHeight = true + builderResult.height = value } - public var value:String { - get { - return builderResult.value - } - set (value) { - builderResult.hasValue = true - builderResult.value = value - } + } + public var hasHeight:Bool { + get { + return builderResult.hasHeight } - public var hasValue:Bool { - get { - return builderResult.hasValue - } + } + @discardableResult + public func setHeight(_ value:Int64) -> Image.Builder { + self.height = value + return self + } + @discardableResult + public func clearHeight() -> Image.Builder{ + builderResult.hasHeight = false + builderResult.height = nil + return self + } + public var format:UInt32 { + get { + return builderResult.format } - @discardableResult - public func setValue(_ value:String) -> FormatDescription.ExtensionsEntry.Builder { - self.value = value - return self + set (value) { + builderResult.hasFormat = true + builderResult.format = value } - @discardableResult - public func clearValue() -> FormatDescription.ExtensionsEntry.Builder{ - builderResult.hasValue = false - builderResult.value = "" - return self + } + public var hasFormat:Bool { + get { + return builderResult.hasFormat } - override public var internalGetResult:GeneratedMessage { - get { - return builderResult - } + } + @discardableResult + public func setFormat(_ value:UInt32) -> Image.Builder { + self.format = value + return self + } + @discardableResult + public func clearFormat() -> Image.Builder{ + builderResult.hasFormat = false + builderResult.format = nil + return self + } + public var hasAttachments:Bool { + get { + return builderResult.hasAttachments } - @discardableResult - override public func clear() -> FormatDescription.ExtensionsEntry.Builder { - builderResult = FormatDescription.ExtensionsEntry() + } + public var attachments:Dictionary { + get { + return builderResult.attachments + } + set (value) { + builderResult.hasAttachments = true + builderResult.attachments = value + } + } + @discardableResult + public func setAttachments(_ value:Dictionary) -> Image.Builder { + self.attachments = value + return self + } + @discardableResult + public func clearAttachments() -> Image.Builder{ + builderResult.hasAttachments = false + builderResult.attachments = Dictionary() + return self + } + public var data:Data { + get { + return builderResult.data + } + set (value) { + builderResult.hasData = true + builderResult.data = value + } + } + public var hasData:Bool { + get { + return builderResult.hasData + } + } + @discardableResult + public func setData(_ value:Data) -> Image.Builder { + self.data = value + return self + } + @discardableResult + public func clearData() -> Image.Builder{ + builderResult.hasData = false + builderResult.data = nil + return self + } + override public var internalGetResult:GeneratedMessage { + get { + return builderResult + } + } + @discardableResult + override public func clear() -> Image.Builder { + builderResult = Image() + return self + } + override public func clone() throws -> Image.Builder { + return try Image.builderWithPrototype(prototype:builderResult) + } + override public func build() throws -> Image { + try checkInitialized() + return buildPartial() + } + public func buildPartial() -> Image { + let returnMe:Image = builderResult + return returnMe + } + @discardableResult + public func mergeFrom(other:Image) throws -> Image.Builder { + if other == Image() { return self } - override public func clone() throws -> FormatDescription.ExtensionsEntry.Builder { - return try FormatDescription.ExtensionsEntry.builderWithPrototype(prototype:builderResult) + if other.hasWidth { + width = other.width } - override public func build() throws -> FormatDescription.ExtensionsEntry { - try checkInitialized() - return buildPartial() + if other.hasHeight { + height = other.height } - public func buildPartial() -> FormatDescription.ExtensionsEntry { - let returnMe:FormatDescription.ExtensionsEntry = builderResult - return returnMe + if other.hasFormat { + format = other.format } - @discardableResult - public func mergeFrom(other:FormatDescription.ExtensionsEntry) throws -> FormatDescription.ExtensionsEntry.Builder { - if other == FormatDescription.ExtensionsEntry() { + if other.hasAttachments { + attachments = other.attachments + } + if other.hasData { + data = other.data + } + try merge(unknownField: other.unknownFields) + return self + } + @discardableResult + override public func mergeFrom(codedInputStream: CodedInputStream) throws -> Image.Builder { + return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry()) + } + @discardableResult + override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Image.Builder { + let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(copyFrom:self.unknownFields) + while (true) { + let protobufTag = try codedInputStream.readTag() + switch protobufTag { + case 0: + self.unknownFields = try unknownFieldsBuilder.build() return self + + case 8: + width = try codedInputStream.readInt64() + + case 16: + height = try codedInputStream.readInt64() + + case 24: + format = try codedInputStream.readUInt32() + + case 34: + let subBuilder = Image.AttachmentsEntry.Builder() + try codedInputStream.readMessage(builder: subBuilder, extensionRegistry:extensionRegistry) + let buildOfAttachments = subBuilder.buildPartial() + attachments[buildOfAttachments.key] = buildOfAttachments.value + + case 42: + data = try codedInputStream.readData() + + default: + if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) { + unknownFields = try unknownFieldsBuilder.build() + return self + } } - if other.hasKey { - key = other.key - } - if other.hasValue { - value = other.value - } - try merge(unknownField: other.unknownFields) - return self } - @discardableResult - override public func mergeFrom(codedInputStream: CodedInputStream) throws -> FormatDescription.ExtensionsEntry.Builder { - return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry()) + } + class override public func decodeToBuilder(jsonMap:Dictionary) throws -> Image.Builder { + let resultDecodedBuilder = Image.Builder() + if let jsonValueWidth = jsonMap["width"] as? String { + resultDecodedBuilder.width = Int64(jsonValueWidth)! + } else if let jsonValueWidth = jsonMap["width"] as? Int { + resultDecodedBuilder.width = Int64(jsonValueWidth) + } + if let jsonValueHeight = jsonMap["height"] as? String { + resultDecodedBuilder.height = Int64(jsonValueHeight)! + } else if let jsonValueHeight = jsonMap["height"] as? Int { + resultDecodedBuilder.height = Int64(jsonValueHeight) + } + if let jsonValueFormat = jsonMap["format"] as? UInt { + resultDecodedBuilder.format = UInt32(jsonValueFormat) + } else if let jsonValueFormat = jsonMap["format"] as? String { + resultDecodedBuilder.format = UInt32(jsonValueFormat)! + } + if let jsonValueAttachments = jsonMap["attachments"] as? Dictionary { + var mapAttachments = Dictionary() + for (keyAttachments, valueAttachments) in jsonValueAttachments { + guard let keyFromAttachments = String(keyAttachments) else { + throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") + } + mapAttachments[keyFromAttachments] = valueAttachments + } + resultDecodedBuilder.attachments = mapAttachments + } + if let jsonValueData = jsonMap["data"] as? String { + resultDecodedBuilder.data = Data(base64Encoded:jsonValueData, options: Data.Base64DecodingOptions(rawValue:0))! + } + return resultDecodedBuilder + } + override class public func fromJSONToBuilder(data:Data) throws -> Image.Builder { + let jsonData = try JSONSerialization.jsonObject(with:data, options: JSONSerialization.ReadingOptions(rawValue: 0)) + guard let jsDataCast = jsonData as? Dictionary else { + throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") + } + return try Image.Builder.decodeToBuilder(jsonMap:jsDataCast) + } + } + +} + +final public class FormatDescription : GeneratedMessage { + + public static func == (lhs: FormatDescription, rhs: FormatDescription) -> Bool { + if lhs === rhs { + return true + } + var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue) + fieldCheck = fieldCheck && (lhs.hasMediaType == rhs.hasMediaType) && (!lhs.hasMediaType || lhs.mediaType == rhs.mediaType) + fieldCheck = fieldCheck && (lhs.hasMediaSubtype == rhs.hasMediaSubtype) && (!lhs.hasMediaSubtype || lhs.mediaSubtype == rhs.mediaSubtype) + fieldCheck = fieldCheck && (lhs.hasExtensions == rhs.hasExtensions) && (!lhs.hasExtensions || lhs.extensions == rhs.extensions) + fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) + return fieldCheck + } + + + + //Nested type declaration start + + final public class ExtensionsEntry : GeneratedMessage { + + public static func == (lhs: FormatDescription.ExtensionsEntry, rhs: FormatDescription.ExtensionsEntry) -> Bool { + if lhs === rhs { + return true + } + var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue) + fieldCheck = fieldCheck && (lhs.hasKey == rhs.hasKey) && (!lhs.hasKey || lhs.key == rhs.key) + fieldCheck = fieldCheck && (lhs.hasValue == rhs.hasValue) && (!lhs.hasValue || lhs.value == rhs.value) + fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) + return fieldCheck + } + + public fileprivate(set) var key:String! = nil + public fileprivate(set) var hasKey:Bool = false + + public fileprivate(set) var value:String! = nil + public fileprivate(set) var hasValue:Bool = false + + required public init() { + super.init() + } + override public func isInitialized() -> Bool { + return true + } + override public func writeTo(codedOutputStream: CodedOutputStream) throws { + if hasKey { + try codedOutputStream.writeString(fieldNumber: 1, value:key) + } + if hasValue { + try codedOutputStream.writeString(fieldNumber: 2, value:value) + } + try unknownFields.writeTo(codedOutputStream: codedOutputStream) + } + override public func serializedSize() -> Int32 { + var serialize_size:Int32 = memoizedSerializedSize + if serialize_size != -1 { + return serialize_size + } + + serialize_size = 0 + if hasKey { + serialize_size += key.computeStringSize(fieldNumber: 1) + } + if hasValue { + serialize_size += value.computeStringSize(fieldNumber: 2) + } + serialize_size += unknownFields.serializedSize() + memoizedSerializedSize = serialize_size + return serialize_size + } + public class func getBuilder() -> FormatDescription.ExtensionsEntry.Builder { + return FormatDescription.ExtensionsEntry.classBuilder() as! FormatDescription.ExtensionsEntry.Builder + } + public func getBuilder() -> FormatDescription.ExtensionsEntry.Builder { + return classBuilder() as! FormatDescription.ExtensionsEntry.Builder + } + override public class func classBuilder() -> ProtocolBuffersMessageBuilder { + return FormatDescription.ExtensionsEntry.Builder() + } + override public func classBuilder() -> ProtocolBuffersMessageBuilder { + return FormatDescription.ExtensionsEntry.Builder() + } + public func toBuilder() throws -> FormatDescription.ExtensionsEntry.Builder { + return try FormatDescription.ExtensionsEntry.builderWithPrototype(prototype:self) + } + public class func builderWithPrototype(prototype:FormatDescription.ExtensionsEntry) throws -> FormatDescription.ExtensionsEntry.Builder { + return try FormatDescription.ExtensionsEntry.Builder().mergeFrom(other:prototype) + } + override public func encode() throws -> Dictionary { + guard isInitialized() else { + throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message") + } + + var jsonMap:Dictionary = Dictionary() + if hasKey { + jsonMap["key"] = key + } + if hasValue { + jsonMap["value"] = value + } + return jsonMap + } + override class public func decode(jsonMap:Dictionary) throws -> FormatDescription.ExtensionsEntry { + return try FormatDescription.ExtensionsEntry.Builder.decodeToBuilder(jsonMap:jsonMap).build() + } + override class public func fromJSON(data:Data) throws -> FormatDescription.ExtensionsEntry { + return try FormatDescription.ExtensionsEntry.Builder.fromJSONToBuilder(data:data).build() + } + override public func getDescription(indent:String) throws -> String { + var output = "" + if hasKey { + output += "\(indent) key: \(key) \n" + } + if hasValue { + output += "\(indent) value: \(value) \n" + } + output += unknownFields.getDescription(indent: indent) + return output + } + override public var hashValue:Int { + get { + var hashCode:Int = 7 + if hasKey { + hashCode = (hashCode &* 31) &+ key.hashValue + } + if hasValue { + hashCode = (hashCode &* 31) &+ value.hashValue + } + hashCode = (hashCode &* 31) &+ unknownFields.hashValue + return hashCode + } + } + + + //Meta information declaration start + + override public class func className() -> String { + return "FormatDescription.ExtensionsEntry" + } + override public func className() -> String { + return "FormatDescription.ExtensionsEntry" + } + //Meta information declaration end + + final public class Builder : GeneratedMessageBuilder { + fileprivate var builderResult:FormatDescription.ExtensionsEntry = FormatDescription.ExtensionsEntry() + public func getMessage() -> FormatDescription.ExtensionsEntry { + return builderResult + } + + required override public init () { + super.init() + } + public var key:String { + get { + return builderResult.key + } + set (value) { + builderResult.hasKey = true + builderResult.key = value + } + } + public var hasKey:Bool { + get { + return builderResult.hasKey + } + } + @discardableResult + public func setKey(_ value:String) -> FormatDescription.ExtensionsEntry.Builder { + self.key = value + return self + } + @discardableResult + public func clearKey() -> FormatDescription.ExtensionsEntry.Builder{ + builderResult.hasKey = false + builderResult.key = nil + return self + } + public var value:String { + get { + return builderResult.value + } + set (value) { + builderResult.hasValue = true + builderResult.value = value + } + } + public var hasValue:Bool { + get { + return builderResult.hasValue + } + } + @discardableResult + public func setValue(_ value:String) -> FormatDescription.ExtensionsEntry.Builder { + self.value = value + return self + } + @discardableResult + public func clearValue() -> FormatDescription.ExtensionsEntry.Builder{ + builderResult.hasValue = false + builderResult.value = nil + return self + } + override public var internalGetResult:GeneratedMessage { + get { + return builderResult + } + } + @discardableResult + override public func clear() -> FormatDescription.ExtensionsEntry.Builder { + builderResult = FormatDescription.ExtensionsEntry() + return self + } + override public func clone() throws -> FormatDescription.ExtensionsEntry.Builder { + return try FormatDescription.ExtensionsEntry.builderWithPrototype(prototype:builderResult) + } + override public func build() throws -> FormatDescription.ExtensionsEntry { + try checkInitialized() + return buildPartial() + } + public func buildPartial() -> FormatDescription.ExtensionsEntry { + let returnMe:FormatDescription.ExtensionsEntry = builderResult + return returnMe + } + @discardableResult + public func mergeFrom(other:FormatDescription.ExtensionsEntry) throws -> FormatDescription.ExtensionsEntry.Builder { + if other == FormatDescription.ExtensionsEntry() { + return self + } + if other.hasKey { + key = other.key + } + if other.hasValue { + value = other.value + } + try merge(unknownField: other.unknownFields) + return self + } + @discardableResult + override public func mergeFrom(codedInputStream: CodedInputStream) throws -> FormatDescription.ExtensionsEntry.Builder { + return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry()) + } + @discardableResult + override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> FormatDescription.ExtensionsEntry.Builder { + let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(copyFrom:self.unknownFields) + while (true) { + let protobufTag = try codedInputStream.readTag() + switch protobufTag { + case 0: + self.unknownFields = try unknownFieldsBuilder.build() + return self + + case 10: + key = try codedInputStream.readString() + + case 18: + value = try codedInputStream.readString() + + default: + if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) { + unknownFields = try unknownFieldsBuilder.build() + return self + } + } + } + } + class override public func decodeToBuilder(jsonMap:Dictionary) throws -> FormatDescription.ExtensionsEntry.Builder { + let resultDecodedBuilder = FormatDescription.ExtensionsEntry.Builder() + if let jsonValueKey = jsonMap["key"] as? String { + resultDecodedBuilder.key = jsonValueKey + } + if let jsonValueValue = jsonMap["value"] as? String { + resultDecodedBuilder.value = jsonValueValue + } + return resultDecodedBuilder + } + override class public func fromJSONToBuilder(data:Data) throws -> FormatDescription.ExtensionsEntry.Builder { + let jsonData = try JSONSerialization.jsonObject(with:data, options: JSONSerialization.ReadingOptions(rawValue: 0)) + guard let jsDataCast = jsonData as? Dictionary else { + throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") + } + return try FormatDescription.ExtensionsEntry.Builder.decodeToBuilder(jsonMap:jsDataCast) + } + } + + } + + //Nested type declaration end + + public fileprivate(set) var mediaType:UInt32! = nil + public fileprivate(set) var hasMediaType:Bool = false + + public fileprivate(set) var mediaSubtype:UInt32! = nil + public fileprivate(set) var hasMediaSubtype:Bool = false + + public fileprivate(set) var extensions:Dictionary = Dictionary() + + public fileprivate(set) var hasExtensions:Bool = false + required public init() { + super.init() + } + override public func isInitialized() -> Bool { + return true + } + override public func writeTo(codedOutputStream: CodedOutputStream) throws { + if hasMediaType { + try codedOutputStream.writeUInt32(fieldNumber: 1, value:mediaType) + } + if hasMediaSubtype { + try codedOutputStream.writeUInt32(fieldNumber: 2, value:mediaSubtype) + } + if hasExtensions { + for (keyExtensions, valueExtensions) in extensions { + let valueOfExtensions = try! FormatDescription.ExtensionsEntry.Builder().setKey(keyExtensions).setValue(valueExtensions).build() + try codedOutputStream.writeMessage(fieldNumber: 3, value:valueOfExtensions) + } + } + try unknownFields.writeTo(codedOutputStream: codedOutputStream) + } + override public func serializedSize() -> Int32 { + var serialize_size:Int32 = memoizedSerializedSize + if serialize_size != -1 { + return serialize_size + } + + serialize_size = 0 + if hasMediaType { + serialize_size += mediaType.computeUInt32Size(fieldNumber: 1) + } + if hasMediaSubtype { + serialize_size += mediaSubtype.computeUInt32Size(fieldNumber: 2) + } + if hasExtensions { + for (keyExtensions, valueExtensions) in extensions { + let valueOfExtensions = try! FormatDescription.ExtensionsEntry.Builder().setKey(keyExtensions).setValue(valueExtensions).build() + serialize_size += valueOfExtensions.computeMessageSize(fieldNumber: 3) + } + } + serialize_size += unknownFields.serializedSize() + memoizedSerializedSize = serialize_size + return serialize_size + } + public class func getBuilder() -> FormatDescription.Builder { + return FormatDescription.classBuilder() as! FormatDescription.Builder + } + public func getBuilder() -> FormatDescription.Builder { + return classBuilder() as! FormatDescription.Builder + } + override public class func classBuilder() -> ProtocolBuffersMessageBuilder { + return FormatDescription.Builder() + } + override public func classBuilder() -> ProtocolBuffersMessageBuilder { + return FormatDescription.Builder() + } + public func toBuilder() throws -> FormatDescription.Builder { + return try FormatDescription.builderWithPrototype(prototype:self) + } + public class func builderWithPrototype(prototype:FormatDescription) throws -> FormatDescription.Builder { + return try FormatDescription.Builder().mergeFrom(other:prototype) + } + override public func encode() throws -> Dictionary { + guard isInitialized() else { + throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message") + } + + var jsonMap:Dictionary = Dictionary() + if hasMediaType { + jsonMap["mediaType"] = UInt(mediaType) + } + if hasMediaSubtype { + jsonMap["mediaSubtype"] = UInt(mediaSubtype) + } + if hasExtensions { + var mapExtensions = Dictionary() + for (keyExtensions, valueExtensions) in extensions { + mapExtensions["\(keyExtensions)"] = valueExtensions + } + jsonMap["extensions"] = mapExtensions + } + return jsonMap + } + override class public func decode(jsonMap:Dictionary) throws -> FormatDescription { + return try FormatDescription.Builder.decodeToBuilder(jsonMap:jsonMap).build() + } + override class public func fromJSON(data:Data) throws -> FormatDescription { + return try FormatDescription.Builder.fromJSONToBuilder(data:data).build() + } + override public func getDescription(indent:String) throws -> String { + var output = "" + if hasMediaType { + output += "\(indent) mediaType: \(mediaType) \n" + } + if hasMediaSubtype { + output += "\(indent) mediaSubtype: \(mediaSubtype) \n" + } + if hasExtensions { + output += "\(indent) extensions: \(extensions) \n" + } + output += unknownFields.getDescription(indent: indent) + return output + } + override public var hashValue:Int { + get { + var hashCode:Int = 7 + if hasMediaType { + hashCode = (hashCode &* 31) &+ mediaType.hashValue + } + if hasMediaSubtype { + hashCode = (hashCode &* 31) &+ mediaSubtype.hashValue + } + if hasExtensions { + for (keyExtensions, valueExtensions) in extensions { + hashCode = (hashCode &* 31) &+ keyExtensions.hashValue + hashCode = (hashCode &* 31) &+ valueExtensions.hashValue + } + } + hashCode = (hashCode &* 31) &+ unknownFields.hashValue + return hashCode + } + } + + + //Meta information declaration start + + override public class func className() -> String { + return "FormatDescription" + } + override public func className() -> String { + return "FormatDescription" + } + //Meta information declaration end + + final public class Builder : GeneratedMessageBuilder { + fileprivate var builderResult:FormatDescription = FormatDescription() + public func getMessage() -> FormatDescription { + return builderResult + } + + required override public init () { + super.init() + } + public var mediaType:UInt32 { + get { + return builderResult.mediaType + } + set (value) { + builderResult.hasMediaType = true + builderResult.mediaType = value + } + } + public var hasMediaType:Bool { + get { + return builderResult.hasMediaType + } + } + @discardableResult + public func setMediaType(_ value:UInt32) -> FormatDescription.Builder { + self.mediaType = value + return self + } + @discardableResult + public func clearMediaType() -> FormatDescription.Builder{ + builderResult.hasMediaType = false + builderResult.mediaType = nil + return self + } + public var mediaSubtype:UInt32 { + get { + return builderResult.mediaSubtype + } + set (value) { + builderResult.hasMediaSubtype = true + builderResult.mediaSubtype = value + } + } + public var hasMediaSubtype:Bool { + get { + return builderResult.hasMediaSubtype + } + } + @discardableResult + public func setMediaSubtype(_ value:UInt32) -> FormatDescription.Builder { + self.mediaSubtype = value + return self + } + @discardableResult + public func clearMediaSubtype() -> FormatDescription.Builder{ + builderResult.hasMediaSubtype = false + builderResult.mediaSubtype = nil + return self + } + public var hasExtensions:Bool { + get { + return builderResult.hasExtensions + } + } + public var extensions:Dictionary { + get { + return builderResult.extensions + } + set (value) { + builderResult.hasExtensions = true + builderResult.extensions = value + } + } + @discardableResult + public func setExtensions(_ value:Dictionary) -> FormatDescription.Builder { + self.extensions = value + return self + } + @discardableResult + public func clearExtensions() -> FormatDescription.Builder{ + builderResult.hasExtensions = false + builderResult.extensions = Dictionary() + return self + } + override public var internalGetResult:GeneratedMessage { + get { + return builderResult + } + } + @discardableResult + override public func clear() -> FormatDescription.Builder { + builderResult = FormatDescription() + return self + } + override public func clone() throws -> FormatDescription.Builder { + return try FormatDescription.builderWithPrototype(prototype:builderResult) + } + override public func build() throws -> FormatDescription { + try checkInitialized() + return buildPartial() + } + public func buildPartial() -> FormatDescription { + let returnMe:FormatDescription = builderResult + return returnMe + } + @discardableResult + public func mergeFrom(other:FormatDescription) throws -> FormatDescription.Builder { + if other == FormatDescription() { + return self + } + if other.hasMediaType { + mediaType = other.mediaType + } + if other.hasMediaSubtype { + mediaSubtype = other.mediaSubtype + } + if other.hasExtensions { + extensions = other.extensions + } + try merge(unknownField: other.unknownFields) + return self + } + @discardableResult + override public func mergeFrom(codedInputStream: CodedInputStream) throws -> FormatDescription.Builder { + return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry()) + } + @discardableResult + override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> FormatDescription.Builder { + let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(copyFrom:self.unknownFields) + while (true) { + let protobufTag = try codedInputStream.readTag() + switch protobufTag { + case 0: + self.unknownFields = try unknownFieldsBuilder.build() + return self + + case 8: + mediaType = try codedInputStream.readUInt32() + + case 16: + mediaSubtype = try codedInputStream.readUInt32() + + case 26: + let subBuilder = FormatDescription.ExtensionsEntry.Builder() + try codedInputStream.readMessage(builder: subBuilder, extensionRegistry:extensionRegistry) + let buildOfExtensions = subBuilder.buildPartial() + extensions[buildOfExtensions.key] = buildOfExtensions.value + + default: + if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) { + unknownFields = try unknownFieldsBuilder.build() + return self + } + } + } + } + class override public func decodeToBuilder(jsonMap:Dictionary) throws -> FormatDescription.Builder { + let resultDecodedBuilder = FormatDescription.Builder() + if let jsonValueMediaType = jsonMap["mediaType"] as? UInt { + resultDecodedBuilder.mediaType = UInt32(jsonValueMediaType) + } else if let jsonValueMediaType = jsonMap["mediaType"] as? String { + resultDecodedBuilder.mediaType = UInt32(jsonValueMediaType)! + } + if let jsonValueMediaSubtype = jsonMap["mediaSubtype"] as? UInt { + resultDecodedBuilder.mediaSubtype = UInt32(jsonValueMediaSubtype) + } else if let jsonValueMediaSubtype = jsonMap["mediaSubtype"] as? String { + resultDecodedBuilder.mediaSubtype = UInt32(jsonValueMediaSubtype)! + } + if let jsonValueExtensions = jsonMap["extensions"] as? Dictionary { + var mapExtensions = Dictionary() + for (keyExtensions, valueExtensions) in jsonValueExtensions { + guard let keyFromExtensions = String(keyExtensions) else { + throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") + } + mapExtensions[keyFromExtensions] = valueExtensions + } + resultDecodedBuilder.extensions = mapExtensions + } + return resultDecodedBuilder + } + override class public func fromJSONToBuilder(data:Data) throws -> FormatDescription.Builder { + let jsonData = try JSONSerialization.jsonObject(with:data, options: JSONSerialization.ReadingOptions(rawValue: 0)) + guard let jsDataCast = jsonData as? Dictionary else { + throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") + } + return try FormatDescription.Builder.decodeToBuilder(jsonMap:jsDataCast) + } + } + +} + +final public class VideoSample : GeneratedMessage { + + public static func == (lhs: VideoSample, rhs: VideoSample) -> Bool { + if lhs === rhs { + return true + } + var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue) + fieldCheck = fieldCheck && (lhs.hasImage == rhs.hasImage) && (!lhs.hasImage || lhs.image == rhs.image) + fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) + return fieldCheck + } + + public fileprivate(set) var image:Image! + public fileprivate(set) var hasImage:Bool = false + required public init() { + super.init() + } + override public func isInitialized() -> Bool { + return true + } + override public func writeTo(codedOutputStream: CodedOutputStream) throws { + if hasImage { + try codedOutputStream.writeMessage(fieldNumber: 1, value:image) + } + try unknownFields.writeTo(codedOutputStream: codedOutputStream) + } + override public func serializedSize() -> Int32 { + var serialize_size:Int32 = memoizedSerializedSize + if serialize_size != -1 { + return serialize_size + } + + serialize_size = 0 + if hasImage { + if let varSizeimage = image?.computeMessageSize(fieldNumber: 1) { + serialize_size += varSizeimage + } + } + serialize_size += unknownFields.serializedSize() + memoizedSerializedSize = serialize_size + return serialize_size + } + public class func getBuilder() -> VideoSample.Builder { + return VideoSample.classBuilder() as! VideoSample.Builder + } + public func getBuilder() -> VideoSample.Builder { + return classBuilder() as! VideoSample.Builder + } + override public class func classBuilder() -> ProtocolBuffersMessageBuilder { + return VideoSample.Builder() + } + override public func classBuilder() -> ProtocolBuffersMessageBuilder { + return VideoSample.Builder() + } + public func toBuilder() throws -> VideoSample.Builder { + return try VideoSample.builderWithPrototype(prototype:self) + } + public class func builderWithPrototype(prototype:VideoSample) throws -> VideoSample.Builder { + return try VideoSample.Builder().mergeFrom(other:prototype) + } + override public func encode() throws -> Dictionary { + guard isInitialized() else { + throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message") + } + + var jsonMap:Dictionary = Dictionary() + if hasImage { + jsonMap["image"] = try image.encode() + } + return jsonMap + } + override class public func decode(jsonMap:Dictionary) throws -> VideoSample { + return try VideoSample.Builder.decodeToBuilder(jsonMap:jsonMap).build() + } + override class public func fromJSON(data:Data) throws -> VideoSample { + return try VideoSample.Builder.fromJSONToBuilder(data:data).build() + } + override public func getDescription(indent:String) throws -> String { + var output = "" + if hasImage { + output += "\(indent) image {\n" + if let outDescImage = image { + output += try outDescImage.getDescription(indent: "\(indent) ") + } + output += "\(indent) }\n" + } + output += unknownFields.getDescription(indent: indent) + return output + } + override public var hashValue:Int { + get { + var hashCode:Int = 7 + if hasImage { + if let hashValueimage = image?.hashValue { + hashCode = (hashCode &* 31) &+ hashValueimage + } + } + hashCode = (hashCode &* 31) &+ unknownFields.hashValue + return hashCode + } + } + + + //Meta information declaration start + + override public class func className() -> String { + return "VideoSample" + } + override public func className() -> String { + return "VideoSample" + } + //Meta information declaration end + + final public class Builder : GeneratedMessageBuilder { + fileprivate var builderResult:VideoSample = VideoSample() + public func getMessage() -> VideoSample { + return builderResult + } + + required override public init () { + super.init() + } + public var image:Image! { + get { + if imageBuilder_ != nil { + builderResult.image = imageBuilder_.getMessage() + } + return builderResult.image + } + set (value) { + builderResult.hasImage = true + builderResult.image = value + } + } + public var hasImage:Bool { + get { + return builderResult.hasImage + } + } + fileprivate var imageBuilder_:Image.Builder! { + didSet { + builderResult.hasImage = true + } + } + public func getImageBuilder() -> Image.Builder { + if imageBuilder_ == nil { + imageBuilder_ = Image.Builder() + builderResult.image = imageBuilder_.getMessage() + if image != nil { + try! imageBuilder_.mergeFrom(other: image) + } + } + return imageBuilder_ + } + @discardableResult + public func setImage(_ value:Image!) -> VideoSample.Builder { + self.image = value + return self + } + @discardableResult + public func mergeImage(value:Image) throws -> VideoSample.Builder { + if builderResult.hasImage { + builderResult.image = try Image.builderWithPrototype(prototype:builderResult.image).mergeFrom(other: value).buildPartial() + } else { + builderResult.image = value + } + builderResult.hasImage = true + return self + } + @discardableResult + public func clearImage() -> VideoSample.Builder { + imageBuilder_ = nil + builderResult.hasImage = false + builderResult.image = nil + return self + } + override public var internalGetResult:GeneratedMessage { + get { + return builderResult + } + } + @discardableResult + override public func clear() -> VideoSample.Builder { + builderResult = VideoSample() + return self + } + override public func clone() throws -> VideoSample.Builder { + return try VideoSample.builderWithPrototype(prototype:builderResult) + } + override public func build() throws -> VideoSample { + try checkInitialized() + return buildPartial() + } + public func buildPartial() -> VideoSample { + let returnMe:VideoSample = builderResult + return returnMe + } + @discardableResult + public func mergeFrom(other:VideoSample) throws -> VideoSample.Builder { + if other == VideoSample() { + return self } - @discardableResult - override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> FormatDescription.ExtensionsEntry.Builder { - let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(copyFrom:self.unknownFields) - while (true) { - let protobufTag = try codedInputStream.readTag() - switch protobufTag { - case 0: - self.unknownFields = try unknownFieldsBuilder.build() - return self - - case 10: - key = try codedInputStream.readString() + if (other.hasImage) { + try mergeImage(value: other.image) + } + try merge(unknownField: other.unknownFields) + return self + } + @discardableResult + override public func mergeFrom(codedInputStream: CodedInputStream) throws -> VideoSample.Builder { + return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry()) + } + @discardableResult + override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> VideoSample.Builder { + let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(copyFrom:self.unknownFields) + while (true) { + let protobufTag = try codedInputStream.readTag() + switch protobufTag { + case 0: + self.unknownFields = try unknownFieldsBuilder.build() + return self - case 18: - value = try codedInputStream.readString() + case 10: + let subBuilder:Image.Builder = Image.Builder() + if hasImage { + try subBuilder.mergeFrom(other: image) + } + try codedInputStream.readMessage(builder: subBuilder, extensionRegistry:extensionRegistry) + image = subBuilder.buildPartial() - default: - if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) { - unknownFields = try unknownFieldsBuilder.build() - return self - } + default: + if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) { + unknownFields = try unknownFieldsBuilder.build() + return self } } } - class override public func decodeToBuilder(jsonMap:Dictionary) throws -> FormatDescription.ExtensionsEntry.Builder { - let resultDecodedBuilder = FormatDescription.ExtensionsEntry.Builder() - if let jsonValueKey = jsonMap["key"] as? String { - resultDecodedBuilder.key = jsonValueKey - } - if let jsonValueValue = jsonMap["value"] as? String { - resultDecodedBuilder.value = jsonValueValue - } - return resultDecodedBuilder + } + class override public func decodeToBuilder(jsonMap:Dictionary) throws -> VideoSample.Builder { + let resultDecodedBuilder = VideoSample.Builder() + if let jsonValueImage = jsonMap["image"] as? Dictionary { + resultDecodedBuilder.image = try Image.Builder.decodeToBuilder(jsonMap:jsonValueImage).build() + } - override class public func fromJSONToBuilder(data:Data) throws -> FormatDescription.ExtensionsEntry.Builder { - let jsonData = try JSONSerialization.jsonObject(with:data, options: JSONSerialization.ReadingOptions(rawValue: 0)) - guard let jsDataCast = jsonData as? Dictionary else { - throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") - } - return try FormatDescription.ExtensionsEntry.Builder.decodeToBuilder(jsonMap:jsDataCast) + return resultDecodedBuilder + } + override class public func fromJSONToBuilder(data:Data) throws -> VideoSample.Builder { + let jsonData = try JSONSerialization.jsonObject(with:data, options: JSONSerialization.ReadingOptions(rawValue: 0)) + guard let jsDataCast = jsonData as? Dictionary else { + throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") } + return try VideoSample.Builder.decodeToBuilder(jsonMap:jsDataCast) } - } - //Nested type declaration end - - public fileprivate(set) var mediaType:UInt32 = UInt32(0) - public fileprivate(set) var hasMediaType:Bool = false +} - public fileprivate(set) var mediaSubtype:UInt32 = UInt32(0) - public fileprivate(set) var hasMediaSubtype:Bool = false +final public class AudioSample : GeneratedMessage { - public fileprivate(set) var extensions:Dictionary = Dictionary() + public static func == (lhs: AudioSample, rhs: AudioSample) -> Bool { + if lhs === rhs { + return true + } + var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue) + fieldCheck = fieldCheck && (lhs.hasImage == rhs.hasImage) && (!lhs.hasImage || lhs.image == rhs.image) + fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) + return fieldCheck + } - public fileprivate(set) var hasExtensions:Bool = false + public fileprivate(set) var image:Image! + public fileprivate(set) var hasImage:Bool = false required public init() { super.init() } @@ -2753,17 +3776,8 @@ final public class FormatDescription : GeneratedMessage { return true } override public func writeTo(codedOutputStream: CodedOutputStream) throws { - if hasMediaType { - try codedOutputStream.writeUInt32(fieldNumber: 1, value:mediaType) - } - if hasMediaSubtype { - try codedOutputStream.writeUInt32(fieldNumber: 2, value:mediaSubtype) - } - if hasExtensions { - for (keyExtensions, valueExtensions) in extensions { - let valueOfExtensions = try! FormatDescription.ExtensionsEntry.Builder().setKey(keyExtensions).setValue(valueExtensions).build() - try codedOutputStream.writeMessage(fieldNumber: 3, value:valueOfExtensions) - } + if hasImage { + try codedOutputStream.writeMessage(fieldNumber: 1, value:image) } try unknownFields.writeTo(codedOutputStream: codedOutputStream) } @@ -2774,39 +3788,32 @@ final public class FormatDescription : GeneratedMessage { } serialize_size = 0 - if hasMediaType { - serialize_size += mediaType.computeUInt32Size(fieldNumber: 1) - } - if hasMediaSubtype { - serialize_size += mediaSubtype.computeUInt32Size(fieldNumber: 2) - } - if hasExtensions { - for (keyExtensions, valueExtensions) in extensions { - let valueOfExtensions = try! FormatDescription.ExtensionsEntry.Builder().setKey(keyExtensions).setValue(valueExtensions).build() - serialize_size += valueOfExtensions.computeMessageSize(fieldNumber: 3) + if hasImage { + if let varSizeimage = image?.computeMessageSize(fieldNumber: 1) { + serialize_size += varSizeimage } } serialize_size += unknownFields.serializedSize() memoizedSerializedSize = serialize_size return serialize_size } - public class func getBuilder() -> FormatDescription.Builder { - return FormatDescription.classBuilder() as! FormatDescription.Builder + public class func getBuilder() -> AudioSample.Builder { + return AudioSample.classBuilder() as! AudioSample.Builder } - public func getBuilder() -> FormatDescription.Builder { - return classBuilder() as! FormatDescription.Builder + public func getBuilder() -> AudioSample.Builder { + return classBuilder() as! AudioSample.Builder } override public class func classBuilder() -> ProtocolBuffersMessageBuilder { - return FormatDescription.Builder() + return AudioSample.Builder() } override public func classBuilder() -> ProtocolBuffersMessageBuilder { - return FormatDescription.Builder() + return AudioSample.Builder() } - public func toBuilder() throws -> FormatDescription.Builder { - return try FormatDescription.builderWithPrototype(prototype:self) + public func toBuilder() throws -> AudioSample.Builder { + return try AudioSample.builderWithPrototype(prototype:self) } - public class func builderWithPrototype(prototype:FormatDescription) throws -> FormatDescription.Builder { - return try FormatDescription.Builder().mergeFrom(other:prototype) + public class func builderWithPrototype(prototype:AudioSample) throws -> AudioSample.Builder { + return try AudioSample.Builder().mergeFrom(other:prototype) } override public func encode() throws -> Dictionary { guard isInitialized() else { @@ -2814,37 +3821,25 @@ final public class FormatDescription : GeneratedMessage { } var jsonMap:Dictionary = Dictionary() - if hasMediaType { - jsonMap["mediaType"] = UInt(mediaType) - } - if hasMediaSubtype { - jsonMap["mediaSubtype"] = UInt(mediaSubtype) - } - if hasExtensions { - var mapExtensions = Dictionary() - for (keyExtensions, valueExtensions) in extensions { - mapExtensions["\(keyExtensions)"] = valueExtensions - } - jsonMap["extensions"] = mapExtensions + if hasImage { + jsonMap["image"] = try image.encode() } return jsonMap } - override class public func decode(jsonMap:Dictionary) throws -> FormatDescription { - return try FormatDescription.Builder.decodeToBuilder(jsonMap:jsonMap).build() + override class public func decode(jsonMap:Dictionary) throws -> AudioSample { + return try AudioSample.Builder.decodeToBuilder(jsonMap:jsonMap).build() } - override class public func fromJSON(data:Data) throws -> FormatDescription { - return try FormatDescription.Builder.fromJSONToBuilder(data:data).build() + override class public func fromJSON(data:Data) throws -> AudioSample { + return try AudioSample.Builder.fromJSONToBuilder(data:data).build() } override public func getDescription(indent:String) throws -> String { var output = "" - if hasMediaType { - output += "\(indent) mediaType: \(mediaType) \n" - } - if hasMediaSubtype { - output += "\(indent) mediaSubtype: \(mediaSubtype) \n" - } - if hasExtensions { - output += "\(indent) extensions: \(extensions) \n" + if hasImage { + output += "\(indent) image {\n" + if let outDescImage = image { + output += try outDescImage.getDescription(indent: "\(indent) ") + } + output += "\(indent) }\n" } output += unknownFields.getDescription(indent: indent) return output @@ -2852,16 +3847,9 @@ final public class FormatDescription : GeneratedMessage { override public var hashValue:Int { get { var hashCode:Int = 7 - if hasMediaType { - hashCode = (hashCode &* 31) &+ mediaType.hashValue - } - if hasMediaSubtype { - hashCode = (hashCode &* 31) &+ mediaSubtype.hashValue - } - if hasExtensions { - for (keyExtensions, valueExtensions) in extensions { - hashCode = (hashCode &* 31) &+ keyExtensions.hashValue - hashCode = (hashCode &* 31) &+ valueExtensions.hashValue + if hasImage { + if let hashValueimage = image?.hashValue { + hashCode = (hashCode &* 31) &+ hashValueimage } } hashCode = (hashCode &* 31) &+ unknownFields.hashValue @@ -2873,95 +3861,74 @@ final public class FormatDescription : GeneratedMessage { //Meta information declaration start override public class func className() -> String { - return "FormatDescription" + return "AudioSample" } override public func className() -> String { - return "FormatDescription" + return "AudioSample" } //Meta information declaration end final public class Builder : GeneratedMessageBuilder { - fileprivate var builderResult:FormatDescription = FormatDescription() - public func getMessage() -> FormatDescription { + fileprivate var builderResult:AudioSample = AudioSample() + public func getMessage() -> AudioSample { return builderResult } required override public init () { super.init() } - public var mediaType:UInt32 { + public var image:Image! { get { - return builderResult.mediaType + if imageBuilder_ != nil { + builderResult.image = imageBuilder_.getMessage() + } + return builderResult.image } set (value) { - builderResult.hasMediaType = true - builderResult.mediaType = value - } - } - public var hasMediaType:Bool { - get { - return builderResult.hasMediaType + builderResult.hasImage = true + builderResult.image = value } } - @discardableResult - public func setMediaType(_ value:UInt32) -> FormatDescription.Builder { - self.mediaType = value - return self - } - @discardableResult - public func clearMediaType() -> FormatDescription.Builder{ - builderResult.hasMediaType = false - builderResult.mediaType = UInt32(0) - return self - } - public var mediaSubtype:UInt32 { + public var hasImage:Bool { get { - return builderResult.mediaSubtype - } - set (value) { - builderResult.hasMediaSubtype = true - builderResult.mediaSubtype = value + return builderResult.hasImage } } - public var hasMediaSubtype:Bool { - get { - return builderResult.hasMediaSubtype + fileprivate var imageBuilder_:Image.Builder! { + didSet { + builderResult.hasImage = true } } - @discardableResult - public func setMediaSubtype(_ value:UInt32) -> FormatDescription.Builder { - self.mediaSubtype = value - return self - } - @discardableResult - public func clearMediaSubtype() -> FormatDescription.Builder{ - builderResult.hasMediaSubtype = false - builderResult.mediaSubtype = UInt32(0) - return self - } - public var hasExtensions:Bool { - get { - return builderResult.hasExtensions + public func getImageBuilder() -> Image.Builder { + if imageBuilder_ == nil { + imageBuilder_ = Image.Builder() + builderResult.image = imageBuilder_.getMessage() + if image != nil { + try! imageBuilder_.mergeFrom(other: image) + } } + return imageBuilder_ } - public var extensions:Dictionary { - get { - return builderResult.extensions - } - set (value) { - builderResult.hasExtensions = true - builderResult.extensions = value - } + @discardableResult + public func setImage(_ value:Image!) -> AudioSample.Builder { + self.image = value + return self } @discardableResult - public func setExtensions(_ value:Dictionary) -> FormatDescription.Builder { - self.extensions = value + public func mergeImage(value:Image) throws -> AudioSample.Builder { + if builderResult.hasImage { + builderResult.image = try Image.builderWithPrototype(prototype:builderResult.image).mergeFrom(other: value).buildPartial() + } else { + builderResult.image = value + } + builderResult.hasImage = true return self } @discardableResult - public func clearExtensions() -> FormatDescription.Builder{ - builderResult.hasExtensions = false - builderResult.extensions = Dictionary() + public func clearImage() -> AudioSample.Builder { + imageBuilder_ = nil + builderResult.hasImage = false + builderResult.image = nil return self } override public var internalGetResult:GeneratedMessage { @@ -2970,44 +3937,38 @@ final public class FormatDescription : GeneratedMessage { } } @discardableResult - override public func clear() -> FormatDescription.Builder { - builderResult = FormatDescription() + override public func clear() -> AudioSample.Builder { + builderResult = AudioSample() return self } - override public func clone() throws -> FormatDescription.Builder { - return try FormatDescription.builderWithPrototype(prototype:builderResult) + override public func clone() throws -> AudioSample.Builder { + return try AudioSample.builderWithPrototype(prototype:builderResult) } - override public func build() throws -> FormatDescription { + override public func build() throws -> AudioSample { try checkInitialized() return buildPartial() } - public func buildPartial() -> FormatDescription { - let returnMe:FormatDescription = builderResult + public func buildPartial() -> AudioSample { + let returnMe:AudioSample = builderResult return returnMe } @discardableResult - public func mergeFrom(other:FormatDescription) throws -> FormatDescription.Builder { - if other == FormatDescription() { + public func mergeFrom(other:AudioSample) throws -> AudioSample.Builder { + if other == AudioSample() { return self } - if other.hasMediaType { - mediaType = other.mediaType - } - if other.hasMediaSubtype { - mediaSubtype = other.mediaSubtype - } - if other.hasExtensions { - extensions = other.extensions + if (other.hasImage) { + try mergeImage(value: other.image) } try merge(unknownField: other.unknownFields) return self } @discardableResult - override public func mergeFrom(codedInputStream: CodedInputStream) throws -> FormatDescription.Builder { + override public func mergeFrom(codedInputStream: CodedInputStream) throws -> AudioSample.Builder { return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry()) } @discardableResult - override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> FormatDescription.Builder { + override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> AudioSample.Builder { let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(copyFrom:self.unknownFields) while (true) { let protobufTag = try codedInputStream.readTag() @@ -3016,17 +3977,13 @@ final public class FormatDescription : GeneratedMessage { self.unknownFields = try unknownFieldsBuilder.build() return self - case 8: - mediaType = try codedInputStream.readUInt32() - - case 16: - mediaSubtype = try codedInputStream.readUInt32() - - case 26: - let subBuilder = FormatDescription.ExtensionsEntry.Builder() + case 10: + let subBuilder:Image.Builder = Image.Builder() + if hasImage { + try subBuilder.mergeFrom(other: image) + } try codedInputStream.readMessage(builder: subBuilder, extensionRegistry:extensionRegistry) - let buildOfExtensions = subBuilder.buildPartial() - extensions[buildOfExtensions.key] = buildOfExtensions.value + image = subBuilder.buildPartial() default: if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) { @@ -3036,61 +3993,42 @@ final public class FormatDescription : GeneratedMessage { } } } - class override public func decodeToBuilder(jsonMap:Dictionary) throws -> FormatDescription.Builder { - let resultDecodedBuilder = FormatDescription.Builder() - if let jsonValueMediaType = jsonMap["mediaType"] as? UInt { - resultDecodedBuilder.mediaType = UInt32(jsonValueMediaType) - } else if let jsonValueMediaType = jsonMap["mediaType"] as? String { - resultDecodedBuilder.mediaType = UInt32(jsonValueMediaType)! - } - if let jsonValueMediaSubtype = jsonMap["mediaSubtype"] as? UInt { - resultDecodedBuilder.mediaSubtype = UInt32(jsonValueMediaSubtype) - } else if let jsonValueMediaSubtype = jsonMap["mediaSubtype"] as? String { - resultDecodedBuilder.mediaSubtype = UInt32(jsonValueMediaSubtype)! - } - if let jsonValueExtensions = jsonMap["extensions"] as? Dictionary { - var mapExtensions = Dictionary() - for (keyExtensions, valueExtensions) in jsonValueExtensions { - guard let keyFromExtensions = String(keyExtensions) else { - throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") - } - mapExtensions[keyFromExtensions] = valueExtensions - } - resultDecodedBuilder.extensions = mapExtensions + class override public func decodeToBuilder(jsonMap:Dictionary) throws -> AudioSample.Builder { + let resultDecodedBuilder = AudioSample.Builder() + if let jsonValueImage = jsonMap["image"] as? Dictionary { + resultDecodedBuilder.image = try Image.Builder.decodeToBuilder(jsonMap:jsonValueImage).build() + } return resultDecodedBuilder } - override class public func fromJSONToBuilder(data:Data) throws -> FormatDescription.Builder { + override class public func fromJSONToBuilder(data:Data) throws -> AudioSample.Builder { let jsonData = try JSONSerialization.jsonObject(with:data, options: JSONSerialization.ReadingOptions(rawValue: 0)) guard let jsDataCast = jsonData as? Dictionary else { throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") } - return try FormatDescription.Builder.decodeToBuilder(jsonMap:jsDataCast) + return try AudioSample.Builder.decodeToBuilder(jsonMap:jsDataCast) } } } -final public class VideoSample : GeneratedMessage { +final public class Av : GeneratedMessage { - public static func == (lhs: VideoSample, rhs: VideoSample) -> Bool { + public static func == (lhs: Av, rhs: Av) -> Bool { if lhs === rhs { return true } var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue) - fieldCheck = fieldCheck && (lhs.hasTimestamp == rhs.hasTimestamp) && (!lhs.hasTimestamp || lhs.timestamp == rhs.timestamp) - fieldCheck = fieldCheck && (lhs.hasImage == rhs.hasImage) && (!lhs.hasImage || lhs.image == rhs.image) - fieldCheck = fieldCheck && (lhs.hasFormat == rhs.hasFormat) && (!lhs.hasFormat || lhs.format == rhs.format) + fieldCheck = fieldCheck && (lhs.hasVideo == rhs.hasVideo) && (!lhs.hasVideo || lhs.video == rhs.video) + fieldCheck = fieldCheck && (lhs.hasAudio == rhs.hasAudio) && (!lhs.hasAudio || lhs.audio == rhs.audio) fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) return fieldCheck } - public fileprivate(set) var timestamp:Timestamp! - public fileprivate(set) var hasTimestamp:Bool = false - public fileprivate(set) var image:Image! - public fileprivate(set) var hasImage:Bool = false - public fileprivate(set) var format:FormatDescription! - public fileprivate(set) var hasFormat:Bool = false + public fileprivate(set) var video:VideoSample! + public fileprivate(set) var hasVideo:Bool = false + public fileprivate(set) var audio:AudioSample! + public fileprivate(set) var hasAudio:Bool = false required public init() { super.init() } @@ -3098,14 +4036,11 @@ final public class VideoSample : GeneratedMessage { return true } override public func writeTo(codedOutputStream: CodedOutputStream) throws { - if hasTimestamp { - try codedOutputStream.writeMessage(fieldNumber: 1, value:timestamp) - } - if hasImage { - try codedOutputStream.writeMessage(fieldNumber: 2, value:image) + if hasVideo { + try codedOutputStream.writeMessage(fieldNumber: 1, value:video) } - if hasFormat { - try codedOutputStream.writeMessage(fieldNumber: 3, value:format) + if hasAudio { + try codedOutputStream.writeMessage(fieldNumber: 2, value:audio) } try unknownFields.writeTo(codedOutputStream: codedOutputStream) } @@ -3116,42 +4051,37 @@ final public class VideoSample : GeneratedMessage { } serialize_size = 0 - if hasTimestamp { - if let varSizetimestamp = timestamp?.computeMessageSize(fieldNumber: 1) { - serialize_size += varSizetimestamp - } - } - if hasImage { - if let varSizeimage = image?.computeMessageSize(fieldNumber: 2) { - serialize_size += varSizeimage + if hasVideo { + if let varSizevideo = video?.computeMessageSize(fieldNumber: 1) { + serialize_size += varSizevideo } } - if hasFormat { - if let varSizeformat = format?.computeMessageSize(fieldNumber: 3) { - serialize_size += varSizeformat + if hasAudio { + if let varSizeaudio = audio?.computeMessageSize(fieldNumber: 2) { + serialize_size += varSizeaudio } } serialize_size += unknownFields.serializedSize() memoizedSerializedSize = serialize_size return serialize_size } - public class func getBuilder() -> VideoSample.Builder { - return VideoSample.classBuilder() as! VideoSample.Builder + public class func getBuilder() -> Av.Builder { + return Av.classBuilder() as! Av.Builder } - public func getBuilder() -> VideoSample.Builder { - return classBuilder() as! VideoSample.Builder + public func getBuilder() -> Av.Builder { + return classBuilder() as! Av.Builder } override public class func classBuilder() -> ProtocolBuffersMessageBuilder { - return VideoSample.Builder() + return Av.Builder() } override public func classBuilder() -> ProtocolBuffersMessageBuilder { - return VideoSample.Builder() + return Av.Builder() } - public func toBuilder() throws -> VideoSample.Builder { - return try VideoSample.builderWithPrototype(prototype:self) + public func toBuilder() throws -> Av.Builder { + return try Av.builderWithPrototype(prototype:self) } - public class func builderWithPrototype(prototype:VideoSample) throws -> VideoSample.Builder { - return try VideoSample.Builder().mergeFrom(other:prototype) + public class func builderWithPrototype(prototype:Av) throws -> Av.Builder { + return try Av.Builder().mergeFrom(other:prototype) } override public func encode() throws -> Dictionary { guard isInitialized() else { @@ -3159,43 +4089,33 @@ final public class VideoSample : GeneratedMessage { } var jsonMap:Dictionary = Dictionary() - if hasTimestamp { - jsonMap["timestamp"] = try timestamp.encode() - } - if hasImage { - jsonMap["image"] = try image.encode() + if hasVideo { + jsonMap["video"] = try video.encode() } - if hasFormat { - jsonMap["format"] = try format.encode() + if hasAudio { + jsonMap["audio"] = try audio.encode() } return jsonMap } - override class public func decode(jsonMap:Dictionary) throws -> VideoSample { - return try VideoSample.Builder.decodeToBuilder(jsonMap:jsonMap).build() + override class public func decode(jsonMap:Dictionary) throws -> Av { + return try Av.Builder.decodeToBuilder(jsonMap:jsonMap).build() } - override class public func fromJSON(data:Data) throws -> VideoSample { - return try VideoSample.Builder.fromJSONToBuilder(data:data).build() + override class public func fromJSON(data:Data) throws -> Av { + return try Av.Builder.fromJSONToBuilder(data:data).build() } override public func getDescription(indent:String) throws -> String { var output = "" - if hasTimestamp { - output += "\(indent) timestamp {\n" - if let outDescTimestamp = timestamp { - output += try outDescTimestamp.getDescription(indent: "\(indent) ") - } - output += "\(indent) }\n" - } - if hasImage { - output += "\(indent) image {\n" - if let outDescImage = image { - output += try outDescImage.getDescription(indent: "\(indent) ") + if hasVideo { + output += "\(indent) video {\n" + if let outDescVideo = video { + output += try outDescVideo.getDescription(indent: "\(indent) ") } output += "\(indent) }\n" } - if hasFormat { - output += "\(indent) format {\n" - if let outDescFormat = format { - output += try outDescFormat.getDescription(indent: "\(indent) ") + if hasAudio { + output += "\(indent) audio {\n" + if let outDescAudio = audio { + output += try outDescAudio.getDescription(indent: "\(indent) ") } output += "\(indent) }\n" } @@ -3205,19 +4125,14 @@ final public class VideoSample : GeneratedMessage { override public var hashValue:Int { get { var hashCode:Int = 7 - if hasTimestamp { - if let hashValuetimestamp = timestamp?.hashValue { - hashCode = (hashCode &* 31) &+ hashValuetimestamp - } - } - if hasImage { - if let hashValueimage = image?.hashValue { - hashCode = (hashCode &* 31) &+ hashValueimage + if hasVideo { + if let hashValuevideo = video?.hashValue { + hashCode = (hashCode &* 31) &+ hashValuevideo } } - if hasFormat { - if let hashValueformat = format?.hashValue { - hashCode = (hashCode &* 31) &+ hashValueformat + if hasAudio { + if let hashValueaudio = audio?.hashValue { + hashCode = (hashCode &* 31) &+ hashValueaudio } } hashCode = (hashCode &* 31) &+ unknownFields.hashValue @@ -3229,182 +4144,128 @@ final public class VideoSample : GeneratedMessage { //Meta information declaration start override public class func className() -> String { - return "VideoSample" + return "Av" } override public func className() -> String { - return "VideoSample" + return "Av" } //Meta information declaration end final public class Builder : GeneratedMessageBuilder { - fileprivate var builderResult:VideoSample = VideoSample() - public func getMessage() -> VideoSample { + fileprivate var builderResult:Av = Av() + public func getMessage() -> Av { return builderResult } required override public init () { super.init() } - public var timestamp:Timestamp! { - get { - if timestampBuilder_ != nil { - builderResult.timestamp = timestampBuilder_.getMessage() - } - return builderResult.timestamp - } - set (value) { - builderResult.hasTimestamp = true - builderResult.timestamp = value - } - } - public var hasTimestamp:Bool { - get { - return builderResult.hasTimestamp - } - } - fileprivate var timestampBuilder_:Timestamp.Builder! { - didSet { - builderResult.hasTimestamp = true - } - } - public func getTimestampBuilder() -> Timestamp.Builder { - if timestampBuilder_ == nil { - timestampBuilder_ = Timestamp.Builder() - builderResult.timestamp = timestampBuilder_.getMessage() - if timestamp != nil { - try! timestampBuilder_.mergeFrom(other: timestamp) - } - } - return timestampBuilder_ - } - @discardableResult - public func setTimestamp(_ value:Timestamp!) -> VideoSample.Builder { - self.timestamp = value - return self - } - @discardableResult - public func mergeTimestamp(value:Timestamp) throws -> VideoSample.Builder { - if builderResult.hasTimestamp { - builderResult.timestamp = try Timestamp.builderWithPrototype(prototype:builderResult.timestamp).mergeFrom(other: value).buildPartial() - } else { - builderResult.timestamp = value - } - builderResult.hasTimestamp = true - return self - } - @discardableResult - public func clearTimestamp() -> VideoSample.Builder { - timestampBuilder_ = nil - builderResult.hasTimestamp = false - builderResult.timestamp = nil - return self - } - public var image:Image! { + public var video:VideoSample! { get { - if imageBuilder_ != nil { - builderResult.image = imageBuilder_.getMessage() + if videoBuilder_ != nil { + builderResult.video = videoBuilder_.getMessage() } - return builderResult.image + return builderResult.video } set (value) { - builderResult.hasImage = true - builderResult.image = value + builderResult.hasVideo = true + builderResult.video = value } } - public var hasImage:Bool { + public var hasVideo:Bool { get { - return builderResult.hasImage + return builderResult.hasVideo } } - fileprivate var imageBuilder_:Image.Builder! { + fileprivate var videoBuilder_:VideoSample.Builder! { didSet { - builderResult.hasImage = true + builderResult.hasVideo = true } } - public func getImageBuilder() -> Image.Builder { - if imageBuilder_ == nil { - imageBuilder_ = Image.Builder() - builderResult.image = imageBuilder_.getMessage() - if image != nil { - try! imageBuilder_.mergeFrom(other: image) + public func getVideoBuilder() -> VideoSample.Builder { + if videoBuilder_ == nil { + videoBuilder_ = VideoSample.Builder() + builderResult.video = videoBuilder_.getMessage() + if video != nil { + try! videoBuilder_.mergeFrom(other: video) } } - return imageBuilder_ + return videoBuilder_ } @discardableResult - public func setImage(_ value:Image!) -> VideoSample.Builder { - self.image = value + public func setVideo(_ value:VideoSample!) -> Av.Builder { + self.video = value return self } @discardableResult - public func mergeImage(value:Image) throws -> VideoSample.Builder { - if builderResult.hasImage { - builderResult.image = try Image.builderWithPrototype(prototype:builderResult.image).mergeFrom(other: value).buildPartial() + public func mergeVideo(value:VideoSample) throws -> Av.Builder { + if builderResult.hasVideo { + builderResult.video = try VideoSample.builderWithPrototype(prototype:builderResult.video).mergeFrom(other: value).buildPartial() } else { - builderResult.image = value + builderResult.video = value } - builderResult.hasImage = true + builderResult.hasVideo = true return self } @discardableResult - public func clearImage() -> VideoSample.Builder { - imageBuilder_ = nil - builderResult.hasImage = false - builderResult.image = nil + public func clearVideo() -> Av.Builder { + videoBuilder_ = nil + builderResult.hasVideo = false + builderResult.video = nil return self } - public var format:FormatDescription! { + public var audio:AudioSample! { get { - if formatBuilder_ != nil { - builderResult.format = formatBuilder_.getMessage() + if audioBuilder_ != nil { + builderResult.audio = audioBuilder_.getMessage() } - return builderResult.format + return builderResult.audio } set (value) { - builderResult.hasFormat = true - builderResult.format = value + builderResult.hasAudio = true + builderResult.audio = value } } - public var hasFormat:Bool { + public var hasAudio:Bool { get { - return builderResult.hasFormat + return builderResult.hasAudio } } - fileprivate var formatBuilder_:FormatDescription.Builder! { + fileprivate var audioBuilder_:AudioSample.Builder! { didSet { - builderResult.hasFormat = true + builderResult.hasAudio = true } } - public func getFormatBuilder() -> FormatDescription.Builder { - if formatBuilder_ == nil { - formatBuilder_ = FormatDescription.Builder() - builderResult.format = formatBuilder_.getMessage() - if format != nil { - try! formatBuilder_.mergeFrom(other: format) + public func getAudioBuilder() -> AudioSample.Builder { + if audioBuilder_ == nil { + audioBuilder_ = AudioSample.Builder() + builderResult.audio = audioBuilder_.getMessage() + if audio != nil { + try! audioBuilder_.mergeFrom(other: audio) } } - return formatBuilder_ + return audioBuilder_ } @discardableResult - public func setFormat(_ value:FormatDescription!) -> VideoSample.Builder { - self.format = value + public func setAudio(_ value:AudioSample!) -> Av.Builder { + self.audio = value return self } @discardableResult - public func mergeFormat(value:FormatDescription) throws -> VideoSample.Builder { - if builderResult.hasFormat { - builderResult.format = try FormatDescription.builderWithPrototype(prototype:builderResult.format).mergeFrom(other: value).buildPartial() + public func mergeAudio(value:AudioSample) throws -> Av.Builder { + if builderResult.hasAudio { + builderResult.audio = try AudioSample.builderWithPrototype(prototype:builderResult.audio).mergeFrom(other: value).buildPartial() } else { - builderResult.format = value + builderResult.audio = value } - builderResult.hasFormat = true + builderResult.hasAudio = true return self } @discardableResult - public func clearFormat() -> VideoSample.Builder { - formatBuilder_ = nil - builderResult.hasFormat = false - builderResult.format = nil + public func clearAudio() -> Av.Builder { + audioBuilder_ = nil + builderResult.hasAudio = false + builderResult.audio = nil return self } override public var internalGetResult:GeneratedMessage { @@ -3413,44 +4274,41 @@ final public class VideoSample : GeneratedMessage { } } @discardableResult - override public func clear() -> VideoSample.Builder { - builderResult = VideoSample() + override public func clear() -> Av.Builder { + builderResult = Av() return self } - override public func clone() throws -> VideoSample.Builder { - return try VideoSample.builderWithPrototype(prototype:builderResult) + override public func clone() throws -> Av.Builder { + return try Av.builderWithPrototype(prototype:builderResult) } - override public func build() throws -> VideoSample { + override public func build() throws -> Av { try checkInitialized() return buildPartial() } - public func buildPartial() -> VideoSample { - let returnMe:VideoSample = builderResult + public func buildPartial() -> Av { + let returnMe:Av = builderResult return returnMe } @discardableResult - public func mergeFrom(other:VideoSample) throws -> VideoSample.Builder { - if other == VideoSample() { + public func mergeFrom(other:Av) throws -> Av.Builder { + if other == Av() { return self } - if (other.hasTimestamp) { - try mergeTimestamp(value: other.timestamp) - } - if (other.hasImage) { - try mergeImage(value: other.image) + if (other.hasVideo) { + try mergeVideo(value: other.video) } - if (other.hasFormat) { - try mergeFormat(value: other.format) + if (other.hasAudio) { + try mergeAudio(value: other.audio) } try merge(unknownField: other.unknownFields) return self } @discardableResult - override public func mergeFrom(codedInputStream: CodedInputStream) throws -> VideoSample.Builder { + override public func mergeFrom(codedInputStream: CodedInputStream) throws -> Av.Builder { return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry()) } @discardableResult - override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> VideoSample.Builder { + override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Av.Builder { let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(copyFrom:self.unknownFields) while (true) { let protobufTag = try codedInputStream.readTag() @@ -3460,28 +4318,20 @@ final public class VideoSample : GeneratedMessage { return self case 10: - let subBuilder:Timestamp.Builder = Timestamp.Builder() - if hasTimestamp { - try subBuilder.mergeFrom(other: timestamp) + let subBuilder:VideoSample.Builder = VideoSample.Builder() + if hasVideo { + try subBuilder.mergeFrom(other: video) } try codedInputStream.readMessage(builder: subBuilder, extensionRegistry:extensionRegistry) - timestamp = subBuilder.buildPartial() + video = subBuilder.buildPartial() case 18: - let subBuilder:Image.Builder = Image.Builder() - if hasImage { - try subBuilder.mergeFrom(other: image) - } - try codedInputStream.readMessage(builder: subBuilder, extensionRegistry:extensionRegistry) - image = subBuilder.buildPartial() - - case 26: - let subBuilder:FormatDescription.Builder = FormatDescription.Builder() - if hasFormat { - try subBuilder.mergeFrom(other: format) + let subBuilder:AudioSample.Builder = AudioSample.Builder() + if hasAudio { + try subBuilder.mergeFrom(other: audio) } try codedInputStream.readMessage(builder: subBuilder, extensionRegistry:extensionRegistry) - format = subBuilder.buildPartial() + audio = subBuilder.buildPartial() default: if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) { @@ -3491,44 +4341,56 @@ final public class VideoSample : GeneratedMessage { } } } - class override public func decodeToBuilder(jsonMap:Dictionary) throws -> VideoSample.Builder { - let resultDecodedBuilder = VideoSample.Builder() - if let jsonValueTimestamp = jsonMap["timestamp"] as? Dictionary { - resultDecodedBuilder.timestamp = try Timestamp.Builder.decodeToBuilder(jsonMap:jsonValueTimestamp).build() - - } - if let jsonValueImage = jsonMap["image"] as? Dictionary { - resultDecodedBuilder.image = try Image.Builder.decodeToBuilder(jsonMap:jsonValueImage).build() + class override public func decodeToBuilder(jsonMap:Dictionary) throws -> Av.Builder { + let resultDecodedBuilder = Av.Builder() + if let jsonValueVideo = jsonMap["video"] as? Dictionary { + resultDecodedBuilder.video = try VideoSample.Builder.decodeToBuilder(jsonMap:jsonValueVideo).build() } - if let jsonValueFormat = jsonMap["format"] as? Dictionary { - resultDecodedBuilder.format = try FormatDescription.Builder.decodeToBuilder(jsonMap:jsonValueFormat).build() + if let jsonValueAudio = jsonMap["audio"] as? Dictionary { + resultDecodedBuilder.audio = try AudioSample.Builder.decodeToBuilder(jsonMap:jsonValueAudio).build() } return resultDecodedBuilder } - override class public func fromJSONToBuilder(data:Data) throws -> VideoSample.Builder { + override class public func fromJSONToBuilder(data:Data) throws -> Av.Builder { let jsonData = try JSONSerialization.jsonObject(with:data, options: JSONSerialization.ReadingOptions(rawValue: 0)) guard let jsDataCast = jsonData as? Dictionary else { throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") } - return try VideoSample.Builder.decodeToBuilder(jsonMap:jsDataCast) + return try Av.Builder.decodeToBuilder(jsonMap:jsDataCast) } } } -final public class AudioSample : GeneratedMessage { +final public class Avsession : GeneratedMessage { - public static func == (lhs: AudioSample, rhs: AudioSample) -> Bool { + public static func == (lhs: Avsession, rhs: Avsession) -> Bool { if lhs === rhs { return true } var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue) + fieldCheck = fieldCheck && (lhs.hasSid == rhs.hasSid) && (!lhs.hasSid || lhs.sid == rhs.sid) + fieldCheck = fieldCheck && (lhs.hasGid == rhs.hasGid) && (!lhs.hasGid || lhs.gid == rhs.gid) + fieldCheck = fieldCheck && (lhs.hasActive == rhs.hasActive) && (!lhs.hasActive || lhs.active == rhs.active) + fieldCheck = fieldCheck && (lhs.hasData == rhs.hasData) && (!lhs.hasData || lhs.data == rhs.data) fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) return fieldCheck } + public fileprivate(set) var sid:String! = nil + public fileprivate(set) var hasSid:Bool = false + + public fileprivate(set) var gid:String! = nil + public fileprivate(set) var hasGid:Bool = false + + public fileprivate(set) var active:Bool! = nil + public fileprivate(set) var hasActive:Bool = false + + public fileprivate(set) var data:Data! = nil + public fileprivate(set) var hasData:Bool = false + required public init() { super.init() } @@ -3536,6 +4398,18 @@ final public class AudioSample : GeneratedMessage { return true } override public func writeTo(codedOutputStream: CodedOutputStream) throws { + if hasSid { + try codedOutputStream.writeString(fieldNumber: 1, value:sid) + } + if hasGid { + try codedOutputStream.writeString(fieldNumber: 2, value:gid) + } + if hasActive { + try codedOutputStream.writeBool(fieldNumber: 3, value:active) + } + if hasData { + try codedOutputStream.writeData(fieldNumber: 4, value:data) + } try unknownFields.writeTo(codedOutputStream: codedOutputStream) } override public func serializedSize() -> Int32 { @@ -3545,74 +4419,222 @@ final public class AudioSample : GeneratedMessage { } serialize_size = 0 + if hasSid { + serialize_size += sid.computeStringSize(fieldNumber: 1) + } + if hasGid { + serialize_size += gid.computeStringSize(fieldNumber: 2) + } + if hasActive { + serialize_size += active.computeBoolSize(fieldNumber: 3) + } + if hasData { + serialize_size += data.computeDataSize(fieldNumber: 4) + } serialize_size += unknownFields.serializedSize() memoizedSerializedSize = serialize_size return serialize_size } - public class func getBuilder() -> AudioSample.Builder { - return AudioSample.classBuilder() as! AudioSample.Builder + public class func getBuilder() -> Avsession.Builder { + return Avsession.classBuilder() as! Avsession.Builder } - public func getBuilder() -> AudioSample.Builder { - return classBuilder() as! AudioSample.Builder + public func getBuilder() -> Avsession.Builder { + return classBuilder() as! Avsession.Builder } override public class func classBuilder() -> ProtocolBuffersMessageBuilder { - return AudioSample.Builder() + return Avsession.Builder() } override public func classBuilder() -> ProtocolBuffersMessageBuilder { - return AudioSample.Builder() + return Avsession.Builder() } - public func toBuilder() throws -> AudioSample.Builder { - return try AudioSample.builderWithPrototype(prototype:self) + public func toBuilder() throws -> Avsession.Builder { + return try Avsession.builderWithPrototype(prototype:self) } - public class func builderWithPrototype(prototype:AudioSample) throws -> AudioSample.Builder { - return try AudioSample.Builder().mergeFrom(other:prototype) + public class func builderWithPrototype(prototype:Avsession) throws -> Avsession.Builder { + return try Avsession.Builder().mergeFrom(other:prototype) } override public func encode() throws -> Dictionary { guard isInitialized() else { throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message") } - - let jsonMap:Dictionary = Dictionary() - return jsonMap - } - override class public func decode(jsonMap:Dictionary) throws -> AudioSample { - return try AudioSample.Builder.decodeToBuilder(jsonMap:jsonMap).build() - } - override class public func fromJSON(data:Data) throws -> AudioSample { - return try AudioSample.Builder.fromJSONToBuilder(data:data).build() - } - override public func getDescription(indent:String) throws -> String { - var output = "" - output += unknownFields.getDescription(indent: indent) - return output - } - override public var hashValue:Int { - get { - var hashCode:Int = 7 - hashCode = (hashCode &* 31) &+ unknownFields.hashValue - return hashCode + + var jsonMap:Dictionary = Dictionary() + if hasSid { + jsonMap["sid"] = sid + } + if hasGid { + jsonMap["gid"] = gid + } + if hasActive { + jsonMap["active"] = active + } + if hasData { + jsonMap["data"] = data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)) + } + return jsonMap + } + override class public func decode(jsonMap:Dictionary) throws -> Avsession { + return try Avsession.Builder.decodeToBuilder(jsonMap:jsonMap).build() + } + override class public func fromJSON(data:Data) throws -> Avsession { + return try Avsession.Builder.fromJSONToBuilder(data:data).build() + } + override public func getDescription(indent:String) throws -> String { + var output = "" + if hasSid { + output += "\(indent) sid: \(sid) \n" + } + if hasGid { + output += "\(indent) gid: \(gid) \n" + } + if hasActive { + output += "\(indent) active: \(active) \n" + } + if hasData { + output += "\(indent) data: \(data) \n" + } + output += unknownFields.getDescription(indent: indent) + return output + } + override public var hashValue:Int { + get { + var hashCode:Int = 7 + if hasSid { + hashCode = (hashCode &* 31) &+ sid.hashValue + } + if hasGid { + hashCode = (hashCode &* 31) &+ gid.hashValue + } + if hasActive { + hashCode = (hashCode &* 31) &+ active.hashValue + } + if hasData { + hashCode = (hashCode &* 31) &+ data.hashValue + } + hashCode = (hashCode &* 31) &+ unknownFields.hashValue + return hashCode + } + } + + + //Meta information declaration start + + override public class func className() -> String { + return "Avsession" + } + override public func className() -> String { + return "Avsession" + } + //Meta information declaration end + + final public class Builder : GeneratedMessageBuilder { + fileprivate var builderResult:Avsession = Avsession() + public func getMessage() -> Avsession { + return builderResult + } + + required override public init () { + super.init() + } + public var sid:String { + get { + return builderResult.sid + } + set (value) { + builderResult.hasSid = true + builderResult.sid = value + } + } + public var hasSid:Bool { + get { + return builderResult.hasSid + } + } + @discardableResult + public func setSid(_ value:String) -> Avsession.Builder { + self.sid = value + return self + } + @discardableResult + public func clearSid() -> Avsession.Builder{ + builderResult.hasSid = false + builderResult.sid = nil + return self + } + public var gid:String { + get { + return builderResult.gid + } + set (value) { + builderResult.hasGid = true + builderResult.gid = value + } + } + public var hasGid:Bool { + get { + return builderResult.hasGid + } + } + @discardableResult + public func setGid(_ value:String) -> Avsession.Builder { + self.gid = value + return self + } + @discardableResult + public func clearGid() -> Avsession.Builder{ + builderResult.hasGid = false + builderResult.gid = nil + return self + } + public var active:Bool { + get { + return builderResult.active + } + set (value) { + builderResult.hasActive = true + builderResult.active = value + } + } + public var hasActive:Bool { + get { + return builderResult.hasActive + } + } + @discardableResult + public func setActive(_ value:Bool) -> Avsession.Builder { + self.active = value + return self + } + @discardableResult + public func clearActive() -> Avsession.Builder{ + builderResult.hasActive = false + builderResult.active = nil + return self } - } - - - //Meta information declaration start - - override public class func className() -> String { - return "AudioSample" - } - override public func className() -> String { - return "AudioSample" - } - //Meta information declaration end - - final public class Builder : GeneratedMessageBuilder { - fileprivate var builderResult:AudioSample = AudioSample() - public func getMessage() -> AudioSample { - return builderResult + public var data:Data { + get { + return builderResult.data + } + set (value) { + builderResult.hasData = true + builderResult.data = value + } } - - required override public init () { - super.init() + public var hasData:Bool { + get { + return builderResult.hasData + } + } + @discardableResult + public func setData(_ value:Data) -> Avsession.Builder { + self.data = value + return self + } + @discardableResult + public func clearData() -> Avsession.Builder{ + builderResult.hasData = false + builderResult.data = nil + return self } override public var internalGetResult:GeneratedMessage { get { @@ -3620,35 +4642,47 @@ final public class AudioSample : GeneratedMessage { } } @discardableResult - override public func clear() -> AudioSample.Builder { - builderResult = AudioSample() + override public func clear() -> Avsession.Builder { + builderResult = Avsession() return self } - override public func clone() throws -> AudioSample.Builder { - return try AudioSample.builderWithPrototype(prototype:builderResult) + override public func clone() throws -> Avsession.Builder { + return try Avsession.builderWithPrototype(prototype:builderResult) } - override public func build() throws -> AudioSample { + override public func build() throws -> Avsession { try checkInitialized() return buildPartial() } - public func buildPartial() -> AudioSample { - let returnMe:AudioSample = builderResult + public func buildPartial() -> Avsession { + let returnMe:Avsession = builderResult return returnMe } @discardableResult - public func mergeFrom(other:AudioSample) throws -> AudioSample.Builder { - if other == AudioSample() { + public func mergeFrom(other:Avsession) throws -> Avsession.Builder { + if other == Avsession() { return self } + if other.hasSid { + sid = other.sid + } + if other.hasGid { + gid = other.gid + } + if other.hasActive { + active = other.active + } + if other.hasData { + data = other.data + } try merge(unknownField: other.unknownFields) return self } @discardableResult - override public func mergeFrom(codedInputStream: CodedInputStream) throws -> AudioSample.Builder { + override public func mergeFrom(codedInputStream: CodedInputStream) throws -> Avsession.Builder { return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry()) } @discardableResult - override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> AudioSample.Builder { + override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Avsession.Builder { let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(copyFrom:self.unknownFields) while (true) { let protobufTag = try codedInputStream.readTag() @@ -3657,6 +4691,18 @@ final public class AudioSample : GeneratedMessage { self.unknownFields = try unknownFieldsBuilder.build() return self + case 10: + sid = try codedInputStream.readString() + + case 18: + gid = try codedInputStream.readString() + + case 24: + active = try codedInputStream.readBool() + + case 34: + data = try codedInputStream.readData() + default: if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) { unknownFields = try unknownFieldsBuilder.build() @@ -3665,38 +4711,48 @@ final public class AudioSample : GeneratedMessage { } } } - class override public func decodeToBuilder(jsonMap:Dictionary) throws -> AudioSample.Builder { - let resultDecodedBuilder = AudioSample.Builder() + class override public func decodeToBuilder(jsonMap:Dictionary) throws -> Avsession.Builder { + let resultDecodedBuilder = Avsession.Builder() + if let jsonValueSid = jsonMap["sid"] as? String { + resultDecodedBuilder.sid = jsonValueSid + } + if let jsonValueGid = jsonMap["gid"] as? String { + resultDecodedBuilder.gid = jsonValueGid + } + if let jsonValueActive = jsonMap["active"] as? Bool { + resultDecodedBuilder.active = jsonValueActive + } + if let jsonValueData = jsonMap["data"] as? String { + resultDecodedBuilder.data = Data(base64Encoded:jsonValueData, options: Data.Base64DecodingOptions(rawValue:0))! + } return resultDecodedBuilder } - override class public func fromJSONToBuilder(data:Data) throws -> AudioSample.Builder { + override class public func fromJSONToBuilder(data:Data) throws -> Avsession.Builder { let jsonData = try JSONSerialization.jsonObject(with:data, options: JSONSerialization.ReadingOptions(rawValue: 0)) guard let jsDataCast = jsonData as? Dictionary else { throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") } - return try AudioSample.Builder.decodeToBuilder(jsonMap:jsDataCast) + return try Avsession.Builder.decodeToBuilder(jsonMap:jsDataCast) } } } -final public class Av : GeneratedMessage { +final public class Avquality : GeneratedMessage { - public static func == (lhs: Av, rhs: Av) -> Bool { + public static func == (lhs: Avquality, rhs: Avquality) -> Bool { if lhs === rhs { return true } var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue) - fieldCheck = fieldCheck && (lhs.hasVideo == rhs.hasVideo) && (!lhs.hasVideo || lhs.video == rhs.video) - fieldCheck = fieldCheck && (lhs.hasAudio == rhs.hasAudio) && (!lhs.hasAudio || lhs.audio == rhs.audio) + fieldCheck = fieldCheck && (lhs.hasDiff == rhs.hasDiff) && (!lhs.hasDiff || lhs.diff == rhs.diff) fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) return fieldCheck } - public fileprivate(set) var video:VideoSample! - public fileprivate(set) var hasVideo:Bool = false - public fileprivate(set) var audio:AudioSample! - public fileprivate(set) var hasAudio:Bool = false + public fileprivate(set) var diff:Int32! = nil + public fileprivate(set) var hasDiff:Bool = false + required public init() { super.init() } @@ -3704,11 +4760,8 @@ final public class Av : GeneratedMessage { return true } override public func writeTo(codedOutputStream: CodedOutputStream) throws { - if hasVideo { - try codedOutputStream.writeMessage(fieldNumber: 1, value:video) - } - if hasAudio { - try codedOutputStream.writeMessage(fieldNumber: 2, value:audio) + if hasDiff { + try codedOutputStream.writeInt32(fieldNumber: 1, value:diff) } try unknownFields.writeTo(codedOutputStream: codedOutputStream) } @@ -3719,37 +4772,30 @@ final public class Av : GeneratedMessage { } serialize_size = 0 - if hasVideo { - if let varSizevideo = video?.computeMessageSize(fieldNumber: 1) { - serialize_size += varSizevideo - } - } - if hasAudio { - if let varSizeaudio = audio?.computeMessageSize(fieldNumber: 2) { - serialize_size += varSizeaudio - } + if hasDiff { + serialize_size += diff.computeInt32Size(fieldNumber: 1) } serialize_size += unknownFields.serializedSize() memoizedSerializedSize = serialize_size return serialize_size } - public class func getBuilder() -> Av.Builder { - return Av.classBuilder() as! Av.Builder + public class func getBuilder() -> Avquality.Builder { + return Avquality.classBuilder() as! Avquality.Builder } - public func getBuilder() -> Av.Builder { - return classBuilder() as! Av.Builder + public func getBuilder() -> Avquality.Builder { + return classBuilder() as! Avquality.Builder } override public class func classBuilder() -> ProtocolBuffersMessageBuilder { - return Av.Builder() + return Avquality.Builder() } override public func classBuilder() -> ProtocolBuffersMessageBuilder { - return Av.Builder() + return Avquality.Builder() } - public func toBuilder() throws -> Av.Builder { - return try Av.builderWithPrototype(prototype:self) + public func toBuilder() throws -> Avquality.Builder { + return try Avquality.builderWithPrototype(prototype:self) } - public class func builderWithPrototype(prototype:Av) throws -> Av.Builder { - return try Av.Builder().mergeFrom(other:prototype) + public class func builderWithPrototype(prototype:Avquality) throws -> Avquality.Builder { + return try Avquality.Builder().mergeFrom(other:prototype) } override public func encode() throws -> Dictionary { guard isInitialized() else { @@ -3757,35 +4803,21 @@ final public class Av : GeneratedMessage { } var jsonMap:Dictionary = Dictionary() - if hasVideo { - jsonMap["video"] = try video.encode() - } - if hasAudio { - jsonMap["audio"] = try audio.encode() + if hasDiff { + jsonMap["diff"] = Int(diff) } return jsonMap } - override class public func decode(jsonMap:Dictionary) throws -> Av { - return try Av.Builder.decodeToBuilder(jsonMap:jsonMap).build() + override class public func decode(jsonMap:Dictionary) throws -> Avquality { + return try Avquality.Builder.decodeToBuilder(jsonMap:jsonMap).build() } - override class public func fromJSON(data:Data) throws -> Av { - return try Av.Builder.fromJSONToBuilder(data:data).build() + override class public func fromJSON(data:Data) throws -> Avquality { + return try Avquality.Builder.fromJSONToBuilder(data:data).build() } override public func getDescription(indent:String) throws -> String { var output = "" - if hasVideo { - output += "\(indent) video {\n" - if let outDescVideo = video { - output += try outDescVideo.getDescription(indent: "\(indent) ") - } - output += "\(indent) }\n" - } - if hasAudio { - output += "\(indent) audio {\n" - if let outDescAudio = audio { - output += try outDescAudio.getDescription(indent: "\(indent) ") - } - output += "\(indent) }\n" + if hasDiff { + output += "\(indent) diff: \(diff) \n" } output += unknownFields.getDescription(indent: indent) return output @@ -3793,15 +4825,8 @@ final public class Av : GeneratedMessage { override public var hashValue:Int { get { var hashCode:Int = 7 - if hasVideo { - if let hashValuevideo = video?.hashValue { - hashCode = (hashCode &* 31) &+ hashValuevideo - } - } - if hasAudio { - if let hashValueaudio = audio?.hashValue { - hashCode = (hashCode &* 31) &+ hashValueaudio - } + if hasDiff { + hashCode = (hashCode &* 31) &+ diff.hashValue } hashCode = (hashCode &* 31) &+ unknownFields.hashValue return hashCode @@ -3812,128 +4837,45 @@ final public class Av : GeneratedMessage { //Meta information declaration start override public class func className() -> String { - return "Av" + return "Avquality" } override public func className() -> String { - return "Av" + return "Avquality" } //Meta information declaration end final public class Builder : GeneratedMessageBuilder { - fileprivate var builderResult:Av = Av() - public func getMessage() -> Av { + fileprivate var builderResult:Avquality = Avquality() + public func getMessage() -> Avquality { return builderResult } required override public init () { super.init() } - public var video:VideoSample! { - get { - if videoBuilder_ != nil { - builderResult.video = videoBuilder_.getMessage() - } - return builderResult.video - } - set (value) { - builderResult.hasVideo = true - builderResult.video = value - } - } - public var hasVideo:Bool { - get { - return builderResult.hasVideo - } - } - fileprivate var videoBuilder_:VideoSample.Builder! { - didSet { - builderResult.hasVideo = true - } - } - public func getVideoBuilder() -> VideoSample.Builder { - if videoBuilder_ == nil { - videoBuilder_ = VideoSample.Builder() - builderResult.video = videoBuilder_.getMessage() - if video != nil { - try! videoBuilder_.mergeFrom(other: video) - } - } - return videoBuilder_ - } - @discardableResult - public func setVideo(_ value:VideoSample!) -> Av.Builder { - self.video = value - return self - } - @discardableResult - public func mergeVideo(value:VideoSample) throws -> Av.Builder { - if builderResult.hasVideo { - builderResult.video = try VideoSample.builderWithPrototype(prototype:builderResult.video).mergeFrom(other: value).buildPartial() - } else { - builderResult.video = value - } - builderResult.hasVideo = true - return self - } - @discardableResult - public func clearVideo() -> Av.Builder { - videoBuilder_ = nil - builderResult.hasVideo = false - builderResult.video = nil - return self - } - public var audio:AudioSample! { + public var diff:Int32 { get { - if audioBuilder_ != nil { - builderResult.audio = audioBuilder_.getMessage() - } - return builderResult.audio + return builderResult.diff } set (value) { - builderResult.hasAudio = true - builderResult.audio = value + builderResult.hasDiff = true + builderResult.diff = value } } - public var hasAudio:Bool { + public var hasDiff:Bool { get { - return builderResult.hasAudio - } - } - fileprivate var audioBuilder_:AudioSample.Builder! { - didSet { - builderResult.hasAudio = true - } - } - public func getAudioBuilder() -> AudioSample.Builder { - if audioBuilder_ == nil { - audioBuilder_ = AudioSample.Builder() - builderResult.audio = audioBuilder_.getMessage() - if audio != nil { - try! audioBuilder_.mergeFrom(other: audio) - } - } - return audioBuilder_ - } - @discardableResult - public func setAudio(_ value:AudioSample!) -> Av.Builder { - self.audio = value - return self - } - @discardableResult - public func mergeAudio(value:AudioSample) throws -> Av.Builder { - if builderResult.hasAudio { - builderResult.audio = try AudioSample.builderWithPrototype(prototype:builderResult.audio).mergeFrom(other: value).buildPartial() - } else { - builderResult.audio = value + return builderResult.hasDiff } - builderResult.hasAudio = true + } + @discardableResult + public func setDiff(_ value:Int32) -> Avquality.Builder { + self.diff = value return self } @discardableResult - public func clearAudio() -> Av.Builder { - audioBuilder_ = nil - builderResult.hasAudio = false - builderResult.audio = nil + public func clearDiff() -> Avquality.Builder{ + builderResult.hasDiff = false + builderResult.diff = nil return self } override public var internalGetResult:GeneratedMessage { @@ -3942,41 +4884,38 @@ final public class Av : GeneratedMessage { } } @discardableResult - override public func clear() -> Av.Builder { - builderResult = Av() + override public func clear() -> Avquality.Builder { + builderResult = Avquality() return self } - override public func clone() throws -> Av.Builder { - return try Av.builderWithPrototype(prototype:builderResult) + override public func clone() throws -> Avquality.Builder { + return try Avquality.builderWithPrototype(prototype:builderResult) } - override public func build() throws -> Av { + override public func build() throws -> Avquality { try checkInitialized() return buildPartial() } - public func buildPartial() -> Av { - let returnMe:Av = builderResult + public func buildPartial() -> Avquality { + let returnMe:Avquality = builderResult return returnMe } @discardableResult - public func mergeFrom(other:Av) throws -> Av.Builder { - if other == Av() { + public func mergeFrom(other:Avquality) throws -> Avquality.Builder { + if other == Avquality() { return self } - if (other.hasVideo) { - try mergeVideo(value: other.video) - } - if (other.hasAudio) { - try mergeAudio(value: other.audio) + if other.hasDiff { + diff = other.diff } try merge(unknownField: other.unknownFields) return self } @discardableResult - override public func mergeFrom(codedInputStream: CodedInputStream) throws -> Av.Builder { + override public func mergeFrom(codedInputStream: CodedInputStream) throws -> Avquality.Builder { return try mergeFrom(codedInputStream: codedInputStream, extensionRegistry:ExtensionRegistry()) } @discardableResult - override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Av.Builder { + override public func mergeFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Avquality.Builder { let unknownFieldsBuilder:UnknownFieldSet.Builder = try UnknownFieldSet.builderWithUnknownFields(copyFrom:self.unknownFields) while (true) { let protobufTag = try codedInputStream.readTag() @@ -3985,21 +4924,8 @@ final public class Av : GeneratedMessage { self.unknownFields = try unknownFieldsBuilder.build() return self - case 10: - let subBuilder:VideoSample.Builder = VideoSample.Builder() - if hasVideo { - try subBuilder.mergeFrom(other: video) - } - try codedInputStream.readMessage(builder: subBuilder, extensionRegistry:extensionRegistry) - video = subBuilder.buildPartial() - - case 18: - let subBuilder:AudioSample.Builder = AudioSample.Builder() - if hasAudio { - try subBuilder.mergeFrom(other: audio) - } - try codedInputStream.readMessage(builder: subBuilder, extensionRegistry:extensionRegistry) - audio = subBuilder.buildPartial() + case 8: + diff = try codedInputStream.readInt32() default: if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) { @@ -4009,24 +4935,21 @@ final public class Av : GeneratedMessage { } } } - class override public func decodeToBuilder(jsonMap:Dictionary) throws -> Av.Builder { - let resultDecodedBuilder = Av.Builder() - if let jsonValueVideo = jsonMap["video"] as? Dictionary { - resultDecodedBuilder.video = try VideoSample.Builder.decodeToBuilder(jsonMap:jsonValueVideo).build() - - } - if let jsonValueAudio = jsonMap["audio"] as? Dictionary { - resultDecodedBuilder.audio = try AudioSample.Builder.decodeToBuilder(jsonMap:jsonValueAudio).build() - + class override public func decodeToBuilder(jsonMap:Dictionary) throws -> Avquality.Builder { + let resultDecodedBuilder = Avquality.Builder() + if let jsonValueDiff = jsonMap["diff"] as? Int { + resultDecodedBuilder.diff = Int32(jsonValueDiff) + } else if let jsonValueDiff = jsonMap["diff"] as? String { + resultDecodedBuilder.diff = Int32(jsonValueDiff)! } return resultDecodedBuilder } - override class public func fromJSONToBuilder(data:Data) throws -> Av.Builder { + override class public func fromJSONToBuilder(data:Data) throws -> Avquality.Builder { let jsonData = try JSONSerialization.jsonObject(with:data, options: JSONSerialization.ReadingOptions(rawValue: 0)) guard let jsDataCast = jsonData as? Dictionary else { throw ProtocolBuffersError.invalidProtocolBuffer("Invalid JSON data") } - return try Av.Builder.decodeToBuilder(jsonMap:jsDataCast) + return try Avquality.Builder.decodeToBuilder(jsonMap:jsDataCast) } } @@ -4047,8 +4970,12 @@ final public class Haber : GeneratedMessage { fieldCheck = fieldCheck && (lhs.hasLogin == rhs.hasLogin) && (!lhs.hasLogin || lhs.login == rhs.login) fieldCheck = fieldCheck && (lhs.contacts == rhs.contacts) fieldCheck = fieldCheck && (lhs.hasText == rhs.hasText) && (!lhs.hasText || lhs.text == rhs.text) - fieldCheck = fieldCheck && (lhs.hasAv == rhs.hasAv) && (!lhs.hasAv || lhs.av == rhs.av) fieldCheck = fieldCheck && (lhs.hasFile == rhs.hasFile) && (!lhs.hasFile || lhs.file == rhs.file) + fieldCheck = fieldCheck && (lhs.hasCall == rhs.hasCall) && (!lhs.hasCall || lhs.call == rhs.call) + fieldCheck = fieldCheck && (lhs.hasAv == rhs.hasAv) && (!lhs.hasAv || lhs.av == rhs.av) + fieldCheck = fieldCheck && (lhs.hasAudioSession == rhs.hasAudioSession) && (!lhs.hasAudioSession || lhs.audioSession == rhs.audioSession) + fieldCheck = fieldCheck && (lhs.hasVideoSession == rhs.hasVideoSession) && (!lhs.hasVideoSession || lhs.videoSession == rhs.videoSession) + fieldCheck = fieldCheck && (lhs.hasAvQuality == rhs.hasAvQuality) && (!lhs.hasAvQuality || lhs.avQuality == rhs.avQuality) fieldCheck = (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) return fieldCheck } @@ -4058,13 +4985,23 @@ final public class Haber : GeneratedMessage { //Enum type declaration start /// Identifies which field is filled in - public enum Which:Int32, CustomDebugStringConvertible, CustomStringConvertible, Hashable { + public enum Which:Int32, GeneratedEnum { case login = 0 case contacts = 1 case presence = 2 case text = 3 case file = 4 case av = 5 + case audioSession = 6 + case videoSession = 7 + case callProposal = 8 + case callCancel = 9 + case callAccept = 10 + case callDecline = 11 + case callStartOutgoing = 12 + case callStartIncoming = 13 + case callQuality = 14 + case callStop = 15 public func toString() -> String { switch self { case .login: return "LOGIN" @@ -4073,9 +5010,19 @@ final public class Haber : GeneratedMessage { case .text: return "TEXT" case .file: return "FILE" case .av: return "AV" + case .audioSession: return "AudioSession" + case .videoSession: return "VideoSession" + case .callProposal: return "CALL_PROPOSAL" + case .callCancel: return "CALL_CANCEL" + case .callAccept: return "CALL_ACCEPT" + case .callDecline: return "CALL_DECLINE" + case .callStartOutgoing: return "CALL_START_OUTGOING" + case .callStartIncoming: return "CALL_START_INCOMING" + case .callQuality: return "CALL_QUALITY" + case .callStop: return "CALL_STOP" } } - public static func fromString(str:String) throws -> Haber.Which { + public static func fromString(_ str:String) throws -> Haber.Which { switch str { case "LOGIN": return .login case "CONTACTS": return .contacts @@ -4083,7 +5030,17 @@ final public class Haber : GeneratedMessage { case "TEXT": return .text case "FILE": return .file case "AV": return .av - default: throw ProtocolBuffersError.invalidProtocolBuffer("Conversion String to Enum has failed.") + case "AudioSession": return .audioSession + case "VideoSession": return .videoSession + case "CALL_PROPOSAL": return .callProposal + case "CALL_CANCEL": return .callCancel + case "CALL_ACCEPT": return .callAccept + case "CALL_DECLINE": return .callDecline + case "CALL_START_OUTGOING": return .callStartOutgoing + case "CALL_START_INCOMING": return .callStartIncoming + case "CALL_QUALITY": return .callQuality + case "CALL_STOP": return .callStop + default: throw ProtocolBuffersError.invalidProtocolBuffer("Conversion failed.") } } public var debugDescription:String { return getDescription() } @@ -4096,6 +5053,16 @@ final public class Haber : GeneratedMessage { case .text: return ".text" case .file: return ".file" case .av: return ".av" + case .audioSession: return ".audioSession" + case .videoSession: return ".videoSession" + case .callProposal: return ".callProposal" + case .callCancel: return ".callCancel" + case .callAccept: return ".callAccept" + case .callDecline: return ".callDecline" + case .callStartOutgoing: return ".callStartOutgoing" + case .callStartIncoming: return ".callStartIncoming" + case .callQuality: return ".callQuality" + case .callStop: return ".callStop" } } public var hashValue:Int { @@ -4108,16 +5075,16 @@ final public class Haber : GeneratedMessage { //Enum type declaration end - public fileprivate(set) var version:UInt32 = UInt32(0) + public fileprivate(set) var version:UInt32! = nil public fileprivate(set) var hasVersion:Bool = false - public fileprivate(set) var sessionId:String = "" + public fileprivate(set) var sessionId:String! = nil public fileprivate(set) var hasSessionId:Bool = false - public fileprivate(set) var from:String = "" + public fileprivate(set) var from:String! = nil public fileprivate(set) var hasFrom:Bool = false - public fileprivate(set) var to:String = "" + public fileprivate(set) var to:String! = nil public fileprivate(set) var hasTo:Bool = false public fileprivate(set) var which:Haber.Which = Haber.Which.login @@ -4127,10 +5094,18 @@ final public class Haber : GeneratedMessage { public fileprivate(set) var contacts:Array = Array() public fileprivate(set) var text:Text! public fileprivate(set) var hasText:Bool = false - public fileprivate(set) var av:Av! - public fileprivate(set) var hasAv:Bool = false public fileprivate(set) var file:File! public fileprivate(set) var hasFile:Bool = false + public fileprivate(set) var call:Call! + public fileprivate(set) var hasCall:Bool = false + public fileprivate(set) var av:Av! + public fileprivate(set) var hasAv:Bool = false + public fileprivate(set) var audioSession:Avsession! + public fileprivate(set) var hasAudioSession:Bool = false + public fileprivate(set) var videoSession:Avsession! + public fileprivate(set) var hasVideoSession:Bool = false + public fileprivate(set) var avQuality:Avquality! + public fileprivate(set) var hasAvQuality:Bool = false required public init() { super.init() } @@ -4151,7 +5126,7 @@ final public class Haber : GeneratedMessage { try codedOutputStream.writeString(fieldNumber: 4, value:to) } if hasWhich { - try codedOutputStream.writeEnum(fieldNumber: 5, value:which.rawValue) + try codedOutputStream.writeEnum(fieldNumber: 15, value:which.rawValue) } if hasLogin { try codedOutputStream.writeMessage(fieldNumber: 101, value:login) @@ -4162,11 +5137,23 @@ final public class Haber : GeneratedMessage { if hasText { try codedOutputStream.writeMessage(fieldNumber: 104, value:text) } + if hasFile { + try codedOutputStream.writeMessage(fieldNumber: 105, value:file) + } + if hasCall { + try codedOutputStream.writeMessage(fieldNumber: 106, value:call) + } if hasAv { - try codedOutputStream.writeMessage(fieldNumber: 105, value:av) + try codedOutputStream.writeMessage(fieldNumber: 107, value:av) } - if hasFile { - try codedOutputStream.writeMessage(fieldNumber: 106, value:file) + if hasAudioSession { + try codedOutputStream.writeMessage(fieldNumber: 108, value:audioSession) + } + if hasVideoSession { + try codedOutputStream.writeMessage(fieldNumber: 109, value:videoSession) + } + if hasAvQuality { + try codedOutputStream.writeMessage(fieldNumber: 110, value:avQuality) } try unknownFields.writeTo(codedOutputStream: codedOutputStream) } @@ -4190,7 +5177,7 @@ final public class Haber : GeneratedMessage { serialize_size += to.computeStringSize(fieldNumber: 4) } if (hasWhich) { - serialize_size += which.rawValue.computeEnumSize(fieldNumber: 5) + serialize_size += which.rawValue.computeEnumSize(fieldNumber: 15) } if hasLogin { if let varSizelogin = login?.computeMessageSize(fieldNumber: 101) { @@ -4205,14 +5192,34 @@ final public class Haber : GeneratedMessage { serialize_size += varSizetext } } + if hasFile { + if let varSizefile = file?.computeMessageSize(fieldNumber: 105) { + serialize_size += varSizefile + } + } + if hasCall { + if let varSizecall = call?.computeMessageSize(fieldNumber: 106) { + serialize_size += varSizecall + } + } if hasAv { - if let varSizeav = av?.computeMessageSize(fieldNumber: 105) { + if let varSizeav = av?.computeMessageSize(fieldNumber: 107) { serialize_size += varSizeav } } - if hasFile { - if let varSizefile = file?.computeMessageSize(fieldNumber: 106) { - serialize_size += varSizefile + if hasAudioSession { + if let varSizeaudioSession = audioSession?.computeMessageSize(fieldNumber: 108) { + serialize_size += varSizeaudioSession + } + } + if hasVideoSession { + if let varSizevideoSession = videoSession?.computeMessageSize(fieldNumber: 109) { + serialize_size += varSizevideoSession + } + } + if hasAvQuality { + if let varSizeavQuality = avQuality?.computeMessageSize(fieldNumber: 110) { + serialize_size += varSizeavQuality } } serialize_size += unknownFields.serializedSize() @@ -4272,11 +5279,23 @@ final public class Haber : GeneratedMessage { if hasText { jsonMap["text"] = try text.encode() } + if hasFile { + jsonMap["file"] = try file.encode() + } + if hasCall { + jsonMap["call"] = try call.encode() + } if hasAv { jsonMap["av"] = try av.encode() } - if hasFile { - jsonMap["file"] = try file.encode() + if hasAudioSession { + jsonMap["audioSession"] = try audioSession.encode() + } + if hasVideoSession { + jsonMap["videoSession"] = try videoSession.encode() + } + if hasAvQuality { + jsonMap["avQuality"] = try avQuality.encode() } return jsonMap } @@ -4324,6 +5343,20 @@ final public class Haber : GeneratedMessage { } output += "\(indent) }\n" } + if hasFile { + output += "\(indent) file {\n" + if let outDescFile = file { + output += try outDescFile.getDescription(indent: "\(indent) ") + } + output += "\(indent) }\n" + } + if hasCall { + output += "\(indent) call {\n" + if let outDescCall = call { + output += try outDescCall.getDescription(indent: "\(indent) ") + } + output += "\(indent) }\n" + } if hasAv { output += "\(indent) av {\n" if let outDescAv = av { @@ -4331,10 +5364,24 @@ final public class Haber : GeneratedMessage { } output += "\(indent) }\n" } - if hasFile { - output += "\(indent) file {\n" - if let outDescFile = file { - output += try outDescFile.getDescription(indent: "\(indent) ") + if hasAudioSession { + output += "\(indent) audioSession {\n" + if let outDescAudioSession = audioSession { + output += try outDescAudioSession.getDescription(indent: "\(indent) ") + } + output += "\(indent) }\n" + } + if hasVideoSession { + output += "\(indent) videoSession {\n" + if let outDescVideoSession = videoSession { + output += try outDescVideoSession.getDescription(indent: "\(indent) ") + } + output += "\(indent) }\n" + } + if hasAvQuality { + output += "\(indent) avQuality {\n" + if let outDescAvQuality = avQuality { + output += try outDescAvQuality.getDescription(indent: "\(indent) ") } output += "\(indent) }\n" } @@ -4372,14 +5419,34 @@ final public class Haber : GeneratedMessage { hashCode = (hashCode &* 31) &+ hashValuetext } } + if hasFile { + if let hashValuefile = file?.hashValue { + hashCode = (hashCode &* 31) &+ hashValuefile + } + } + if hasCall { + if let hashValuecall = call?.hashValue { + hashCode = (hashCode &* 31) &+ hashValuecall + } + } if hasAv { if let hashValueav = av?.hashValue { hashCode = (hashCode &* 31) &+ hashValueav } } - if hasFile { - if let hashValuefile = file?.hashValue { - hashCode = (hashCode &* 31) &+ hashValuefile + if hasAudioSession { + if let hashValueaudioSession = audioSession?.hashValue { + hashCode = (hashCode &* 31) &+ hashValueaudioSession + } + } + if hasVideoSession { + if let hashValuevideoSession = videoSession?.hashValue { + hashCode = (hashCode &* 31) &+ hashValuevideoSession + } + } + if hasAvQuality { + if let hashValueavQuality = avQuality?.hashValue { + hashCode = (hashCode &* 31) &+ hashValueavQuality } } hashCode = (hashCode &* 31) &+ unknownFields.hashValue @@ -4429,7 +5496,7 @@ final public class Haber : GeneratedMessage { @discardableResult public func clearVersion() -> Haber.Builder{ builderResult.hasVersion = false - builderResult.version = UInt32(0) + builderResult.version = nil return self } public var sessionId:String { @@ -4454,7 +5521,7 @@ final public class Haber : GeneratedMessage { @discardableResult public func clearSessionId() -> Haber.Builder{ builderResult.hasSessionId = false - builderResult.sessionId = "" + builderResult.sessionId = nil return self } public var from:String { @@ -4479,7 +5546,7 @@ final public class Haber : GeneratedMessage { @discardableResult public func clearFrom() -> Haber.Builder{ builderResult.hasFrom = false - builderResult.from = "" + builderResult.from = nil return self } public var to:String { @@ -4504,7 +5571,7 @@ final public class Haber : GeneratedMessage { @discardableResult public func clearTo() -> Haber.Builder{ builderResult.hasTo = false - builderResult.to = "" + builderResult.to = nil return self } public var which:Haber.Which { @@ -4660,6 +5727,114 @@ final public class Haber : GeneratedMessage { builderResult.text = nil return self } + public var file:File! { + get { + if fileBuilder_ != nil { + builderResult.file = fileBuilder_.getMessage() + } + return builderResult.file + } + set (value) { + builderResult.hasFile = true + builderResult.file = value + } + } + public var hasFile:Bool { + get { + return builderResult.hasFile + } + } + fileprivate var fileBuilder_:File.Builder! { + didSet { + builderResult.hasFile = true + } + } + public func getFileBuilder() -> File.Builder { + if fileBuilder_ == nil { + fileBuilder_ = File.Builder() + builderResult.file = fileBuilder_.getMessage() + if file != nil { + try! fileBuilder_.mergeFrom(other: file) + } + } + return fileBuilder_ + } + @discardableResult + public func setFile(_ value:File!) -> Haber.Builder { + self.file = value + return self + } + @discardableResult + public func mergeFile(value:File) throws -> Haber.Builder { + if builderResult.hasFile { + builderResult.file = try File.builderWithPrototype(prototype:builderResult.file).mergeFrom(other: value).buildPartial() + } else { + builderResult.file = value + } + builderResult.hasFile = true + return self + } + @discardableResult + public func clearFile() -> Haber.Builder { + fileBuilder_ = nil + builderResult.hasFile = false + builderResult.file = nil + return self + } + public var call:Call! { + get { + if callBuilder_ != nil { + builderResult.call = callBuilder_.getMessage() + } + return builderResult.call + } + set (value) { + builderResult.hasCall = true + builderResult.call = value + } + } + public var hasCall:Bool { + get { + return builderResult.hasCall + } + } + fileprivate var callBuilder_:Call.Builder! { + didSet { + builderResult.hasCall = true + } + } + public func getCallBuilder() -> Call.Builder { + if callBuilder_ == nil { + callBuilder_ = Call.Builder() + builderResult.call = callBuilder_.getMessage() + if call != nil { + try! callBuilder_.mergeFrom(other: call) + } + } + return callBuilder_ + } + @discardableResult + public func setCall(_ value:Call!) -> Haber.Builder { + self.call = value + return self + } + @discardableResult + public func mergeCall(value:Call) throws -> Haber.Builder { + if builderResult.hasCall { + builderResult.call = try Call.builderWithPrototype(prototype:builderResult.call).mergeFrom(other: value).buildPartial() + } else { + builderResult.call = value + } + builderResult.hasCall = true + return self + } + @discardableResult + public func clearCall() -> Haber.Builder { + callBuilder_ = nil + builderResult.hasCall = false + builderResult.call = nil + return self + } public var av:Av! { get { if avBuilder_ != nil { @@ -4714,58 +5889,166 @@ final public class Haber : GeneratedMessage { builderResult.av = nil return self } - public var file:File! { + public var audioSession:Avsession! { get { - if fileBuilder_ != nil { - builderResult.file = fileBuilder_.getMessage() + if audioSessionBuilder_ != nil { + builderResult.audioSession = audioSessionBuilder_.getMessage() } - return builderResult.file + return builderResult.audioSession } set (value) { - builderResult.hasFile = true - builderResult.file = value + builderResult.hasAudioSession = true + builderResult.audioSession = value } } - public var hasFile:Bool { + public var hasAudioSession:Bool { get { - return builderResult.hasFile + return builderResult.hasAudioSession + } + } + fileprivate var audioSessionBuilder_:Avsession.Builder! { + didSet { + builderResult.hasAudioSession = true + } + } + public func getAudioSessionBuilder() -> Avsession.Builder { + if audioSessionBuilder_ == nil { + audioSessionBuilder_ = Avsession.Builder() + builderResult.audioSession = audioSessionBuilder_.getMessage() + if audioSession != nil { + try! audioSessionBuilder_.mergeFrom(other: audioSession) + } + } + return audioSessionBuilder_ + } + @discardableResult + public func setAudioSession(_ value:Avsession!) -> Haber.Builder { + self.audioSession = value + return self + } + @discardableResult + public func mergeAudioSession(value:Avsession) throws -> Haber.Builder { + if builderResult.hasAudioSession { + builderResult.audioSession = try Avsession.builderWithPrototype(prototype:builderResult.audioSession).mergeFrom(other: value).buildPartial() + } else { + builderResult.audioSession = value + } + builderResult.hasAudioSession = true + return self + } + @discardableResult + public func clearAudioSession() -> Haber.Builder { + audioSessionBuilder_ = nil + builderResult.hasAudioSession = false + builderResult.audioSession = nil + return self + } + public var videoSession:Avsession! { + get { + if videoSessionBuilder_ != nil { + builderResult.videoSession = videoSessionBuilder_.getMessage() + } + return builderResult.videoSession + } + set (value) { + builderResult.hasVideoSession = true + builderResult.videoSession = value + } + } + public var hasVideoSession:Bool { + get { + return builderResult.hasVideoSession + } + } + fileprivate var videoSessionBuilder_:Avsession.Builder! { + didSet { + builderResult.hasVideoSession = true + } + } + public func getVideoSessionBuilder() -> Avsession.Builder { + if videoSessionBuilder_ == nil { + videoSessionBuilder_ = Avsession.Builder() + builderResult.videoSession = videoSessionBuilder_.getMessage() + if videoSession != nil { + try! videoSessionBuilder_.mergeFrom(other: videoSession) + } + } + return videoSessionBuilder_ + } + @discardableResult + public func setVideoSession(_ value:Avsession!) -> Haber.Builder { + self.videoSession = value + return self + } + @discardableResult + public func mergeVideoSession(value:Avsession) throws -> Haber.Builder { + if builderResult.hasVideoSession { + builderResult.videoSession = try Avsession.builderWithPrototype(prototype:builderResult.videoSession).mergeFrom(other: value).buildPartial() + } else { + builderResult.videoSession = value + } + builderResult.hasVideoSession = true + return self + } + @discardableResult + public func clearVideoSession() -> Haber.Builder { + videoSessionBuilder_ = nil + builderResult.hasVideoSession = false + builderResult.videoSession = nil + return self + } + public var avQuality:Avquality! { + get { + if avQualityBuilder_ != nil { + builderResult.avQuality = avQualityBuilder_.getMessage() + } + return builderResult.avQuality + } + set (value) { + builderResult.hasAvQuality = true + builderResult.avQuality = value + } + } + public var hasAvQuality:Bool { + get { + return builderResult.hasAvQuality } } - fileprivate var fileBuilder_:File.Builder! { + fileprivate var avQualityBuilder_:Avquality.Builder! { didSet { - builderResult.hasFile = true + builderResult.hasAvQuality = true } } - public func getFileBuilder() -> File.Builder { - if fileBuilder_ == nil { - fileBuilder_ = File.Builder() - builderResult.file = fileBuilder_.getMessage() - if file != nil { - try! fileBuilder_.mergeFrom(other: file) + public func getAvQualityBuilder() -> Avquality.Builder { + if avQualityBuilder_ == nil { + avQualityBuilder_ = Avquality.Builder() + builderResult.avQuality = avQualityBuilder_.getMessage() + if avQuality != nil { + try! avQualityBuilder_.mergeFrom(other: avQuality) } } - return fileBuilder_ + return avQualityBuilder_ } @discardableResult - public func setFile(_ value:File!) -> Haber.Builder { - self.file = value + public func setAvQuality(_ value:Avquality!) -> Haber.Builder { + self.avQuality = value return self } @discardableResult - public func mergeFile(value:File) throws -> Haber.Builder { - if builderResult.hasFile { - builderResult.file = try File.builderWithPrototype(prototype:builderResult.file).mergeFrom(other: value).buildPartial() + public func mergeAvQuality(value:Avquality) throws -> Haber.Builder { + if builderResult.hasAvQuality { + builderResult.avQuality = try Avquality.builderWithPrototype(prototype:builderResult.avQuality).mergeFrom(other: value).buildPartial() } else { - builderResult.file = value + builderResult.avQuality = value } - builderResult.hasFile = true + builderResult.hasAvQuality = true return self } @discardableResult - public func clearFile() -> Haber.Builder { - fileBuilder_ = nil - builderResult.hasFile = false - builderResult.file = nil + public func clearAvQuality() -> Haber.Builder { + avQualityBuilder_ = nil + builderResult.hasAvQuality = false + builderResult.avQuality = nil return self } override public var internalGetResult:GeneratedMessage { @@ -4818,11 +6101,23 @@ final public class Haber : GeneratedMessage { if (other.hasText) { try mergeText(value: other.text) } + if (other.hasFile) { + try mergeFile(value: other.file) + } + if (other.hasCall) { + try mergeCall(value: other.call) + } if (other.hasAv) { try mergeAv(value: other.av) } - if (other.hasFile) { - try mergeFile(value: other.file) + if (other.hasAudioSession) { + try mergeAudioSession(value: other.audioSession) + } + if (other.hasVideoSession) { + try mergeVideoSession(value: other.videoSession) + } + if (other.hasAvQuality) { + try mergeAvQuality(value: other.avQuality) } try merge(unknownField: other.unknownFields) return self @@ -4853,12 +6148,12 @@ final public class Haber : GeneratedMessage { case 34: to = try codedInputStream.readString() - case 40: + case 120: let valueIntwhich = try codedInputStream.readEnum() if let enumswhich = Haber.Which(rawValue:valueIntwhich){ which = enumswhich } else { - try unknownFieldsBuilder.mergeVarintField(fieldNumber: 5, value:Int64(valueIntwhich)) + try unknownFieldsBuilder.mergeVarintField(fieldNumber: 15, value:Int64(valueIntwhich)) } case 810: @@ -4883,6 +6178,22 @@ final public class Haber : GeneratedMessage { text = subBuilder.buildPartial() case 842: + let subBuilder:File.Builder = File.Builder() + if hasFile { + try subBuilder.mergeFrom(other: file) + } + try codedInputStream.readMessage(builder: subBuilder, extensionRegistry:extensionRegistry) + file = subBuilder.buildPartial() + + case 850: + let subBuilder:Call.Builder = Call.Builder() + if hasCall { + try subBuilder.mergeFrom(other: call) + } + try codedInputStream.readMessage(builder: subBuilder, extensionRegistry:extensionRegistry) + call = subBuilder.buildPartial() + + case 858: let subBuilder:Av.Builder = Av.Builder() if hasAv { try subBuilder.mergeFrom(other: av) @@ -4890,13 +6201,29 @@ final public class Haber : GeneratedMessage { try codedInputStream.readMessage(builder: subBuilder, extensionRegistry:extensionRegistry) av = subBuilder.buildPartial() - case 850: - let subBuilder:File.Builder = File.Builder() - if hasFile { - try subBuilder.mergeFrom(other: file) + case 866: + let subBuilder:Avsession.Builder = Avsession.Builder() + if hasAudioSession { + try subBuilder.mergeFrom(other: audioSession) } try codedInputStream.readMessage(builder: subBuilder, extensionRegistry:extensionRegistry) - file = subBuilder.buildPartial() + audioSession = subBuilder.buildPartial() + + case 874: + let subBuilder:Avsession.Builder = Avsession.Builder() + if hasVideoSession { + try subBuilder.mergeFrom(other: videoSession) + } + try codedInputStream.readMessage(builder: subBuilder, extensionRegistry:extensionRegistry) + videoSession = subBuilder.buildPartial() + + case 882: + let subBuilder:Avquality.Builder = Avquality.Builder() + if hasAvQuality { + try subBuilder.mergeFrom(other: avQuality) + } + try codedInputStream.readMessage(builder: subBuilder, extensionRegistry:extensionRegistry) + avQuality = subBuilder.buildPartial() default: if (!(try parse(codedInputStream:codedInputStream, unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:protobufTag))) { @@ -4923,7 +6250,7 @@ final public class Haber : GeneratedMessage { resultDecodedBuilder.to = jsonValueTo } if let jsonValueWhich = jsonMap["which"] as? String { - resultDecodedBuilder.which = try Haber.Which.fromString(str: jsonValueWhich) + resultDecodedBuilder.which = try Haber.Which.fromString(jsonValueWhich) } if let jsonValueLogin = jsonMap["login"] as? Dictionary { resultDecodedBuilder.login = try Login.Builder.decodeToBuilder(jsonMap:jsonValueLogin).build() @@ -4941,13 +6268,29 @@ final public class Haber : GeneratedMessage { if let jsonValueText = jsonMap["text"] as? Dictionary { resultDecodedBuilder.text = try Text.Builder.decodeToBuilder(jsonMap:jsonValueText).build() + } + if let jsonValueFile = jsonMap["file"] as? Dictionary { + resultDecodedBuilder.file = try File.Builder.decodeToBuilder(jsonMap:jsonValueFile).build() + + } + if let jsonValueCall = jsonMap["call"] as? Dictionary { + resultDecodedBuilder.call = try Call.Builder.decodeToBuilder(jsonMap:jsonValueCall).build() + } if let jsonValueAv = jsonMap["av"] as? Dictionary { resultDecodedBuilder.av = try Av.Builder.decodeToBuilder(jsonMap:jsonValueAv).build() } - if let jsonValueFile = jsonMap["file"] as? Dictionary { - resultDecodedBuilder.file = try File.Builder.decodeToBuilder(jsonMap:jsonValueFile).build() + if let jsonValueAudioSession = jsonMap["audioSession"] as? Dictionary { + resultDecodedBuilder.audioSession = try Avsession.Builder.decodeToBuilder(jsonMap:jsonValueAudioSession).build() + + } + if let jsonValueVideoSession = jsonMap["videoSession"] as? Dictionary { + resultDecodedBuilder.videoSession = try Avsession.Builder.decodeToBuilder(jsonMap:jsonValueVideoSession).build() + + } + if let jsonValueAvQuality = jsonMap["avQuality"] as? Dictionary { + resultDecodedBuilder.avQuality = try Avquality.Builder.decodeToBuilder(jsonMap:jsonValueAvQuality).build() } return resultDecodedBuilder @@ -5201,6 +6544,90 @@ extension File.Builder: GeneratedMessageBuilderProtocol { } } } +extension Call: GeneratedMessageProtocol { + public class func parseArrayDelimitedFrom(inputStream: InputStream) throws -> Array { + var mergedArray = Array() + while let value = try parseDelimitedFrom(inputStream: inputStream) { + mergedArray.append(value) + } + return mergedArray + } + public class func parseDelimitedFrom(inputStream: InputStream) throws -> Call? { + return try Call.Builder().mergeDelimitedFrom(inputStream: inputStream)?.build() + } + public class func parseFrom(data: Data) throws -> Call { + return try Call.Builder().mergeFrom(data: data, extensionRegistry:WireRoot.default.extensionRegistry).build() + } + public class func parseFrom(data: Data, extensionRegistry:ExtensionRegistry) throws -> Call { + return try Call.Builder().mergeFrom(data: data, extensionRegistry:extensionRegistry).build() + } + public class func parseFrom(inputStream: InputStream) throws -> Call { + return try Call.Builder().mergeFrom(inputStream: inputStream).build() + } + public class func parseFrom(inputStream: InputStream, extensionRegistry:ExtensionRegistry) throws -> Call { + return try Call.Builder().mergeFrom(inputStream: inputStream, extensionRegistry:extensionRegistry).build() + } + public class func parseFrom(codedInputStream: CodedInputStream) throws -> Call { + return try Call.Builder().mergeFrom(codedInputStream: codedInputStream).build() + } + public class func parseFrom(codedInputStream: CodedInputStream, extensionRegistry:ExtensionRegistry) throws -> Call { + return try Call.Builder().mergeFrom(codedInputStream: codedInputStream, extensionRegistry:extensionRegistry).build() + } + public subscript(key: String) -> Any? { + switch key { + case "key": return self.key + case "to": return self.to + case "from": return self.from + case "audio": return self.audio + case "video": return self.video + default: return nil + } + } +} +extension Call.Builder: GeneratedMessageBuilderProtocol { + public subscript(key: String) -> Any? { + get { + switch key { + case "key": return self.key + case "to": return self.to + case "from": return self.from + case "audio": return self.audio + case "video": return self.video + default: return nil + } + } + set (newSubscriptValue) { + switch key { + case "key": + guard let newSubscriptValue = newSubscriptValue as? String else { + return + } + self.key = newSubscriptValue + case "to": + guard let newSubscriptValue = newSubscriptValue as? String else { + return + } + self.to = newSubscriptValue + case "from": + guard let newSubscriptValue = newSubscriptValue as? String else { + return + } + self.from = newSubscriptValue + case "audio": + guard let newSubscriptValue = newSubscriptValue as? Bool else { + return + } + self.audio = newSubscriptValue + case "video": + guard let newSubscriptValue = newSubscriptValue as? Bool else { + return + } + self.video = newSubscriptValue + default: return + } + } + } +} extension Time: GeneratedMessageProtocol { public class func parseArrayDelimitedFrom(inputStream: InputStream) throws -> Array