1 use { 2 super::{ 3 common::Common, 4 define, 5 define::SessionType, 6 errors::{SessionError, SessionErrorValue}, 7 }, 8 crate::{ 9 amf0::Amf0ValueType, 10 channels::define::ChannelEventProducer, 11 chunk::{ 12 define::CHUNK_SIZE, 13 unpacketizer::{ChunkUnpacketizer, UnpackResult}, 14 }, 15 config, handshake, 16 handshake::{define::ServerHandshakeState, handshake_server::HandshakeServer}, 17 messages::{define::RtmpMessageData, parser::MessageParser}, 18 netconnection::writer::NetConnection, 19 netstream::writer::NetStreamWriter, 20 protocol_control_messages::writer::ProtocolControlMessagesWriter, 21 user_control_messages::writer::EventMessagesWriter, 22 }, 23 bytes::BytesMut, 24 bytesio::{bytes_writer::AsyncBytesWriter, bytesio::BytesIO}, 25 std::{collections::HashMap, sync::Arc, time::Duration}, 26 tokio::{net::TcpStream, sync::Mutex}, 27 uuid::Uuid, 28 }; 29 30 enum ServerSessionState { 31 Handshake, 32 ReadChunk, 33 // OnConnect, 34 // OnCreateStream, 35 //Publish, 36 Play, 37 } 38 39 pub struct ServerSession { 40 pub app_name: String, 41 pub stream_name: String, 42 43 io: Arc<Mutex<BytesIO>>, 44 handshaker: HandshakeServer, 45 46 unpacketizer: ChunkUnpacketizer, 47 48 state: ServerSessionState, 49 50 pub common: Common, 51 52 bytesio_data: BytesMut, 53 has_remaing_data: bool, 54 55 /* Used to mark the subscriber's the data producer 56 in channels and delete it from map when unsubscribe 57 is called. */ 58 pub subscriber_id: Uuid, 59 60 connect_command_object: Option<HashMap<String, Amf0ValueType>>, 61 } 62 63 impl ServerSession { 64 pub fn new(stream: TcpStream, event_producer: ChannelEventProducer) -> Self { 65 let net_io = Arc::new(Mutex::new(BytesIO::new(stream))); 66 let subscriber_id = Uuid::new_v4(); 67 Self { 68 app_name: String::from(""), 69 stream_name: String::from(""), 70 71 io: Arc::clone(&net_io), 72 handshaker: HandshakeServer::new(Arc::clone(&net_io)), 73 74 unpacketizer: ChunkUnpacketizer::new(), 75 76 state: ServerSessionState::Handshake, 77 78 common: Common::new(Arc::clone(&net_io), event_producer, SessionType::Server), 79 80 subscriber_id, 81 bytesio_data: BytesMut::new(), 82 has_remaing_data: false, 83 84 connect_command_object: None, 85 } 86 } 87 88 pub async fn run(&mut self) -> Result<(), SessionError> { 89 loop { 90 match self.state { 91 ServerSessionState::Handshake => { 92 self.handshake().await?; 93 } 94 ServerSessionState::ReadChunk => { 95 self.read_parse_chunks().await?; 96 } 97 ServerSessionState::Play => { 98 self.play().await?; 99 } 100 } 101 } 102 103 //Ok(()) 104 } 105 106 async fn handshake(&mut self) -> Result<(), SessionError> { 107 let mut bytes_len = 0; 108 109 while bytes_len < handshake::define::RTMP_HANDSHAKE_SIZE { 110 self.bytesio_data = self.io.lock().await.read().await?; 111 bytes_len += self.bytesio_data.len(); 112 self.handshaker.extend_data(&self.bytesio_data[..]); 113 } 114 115 self.handshaker.handshake().await?; 116 117 match self.handshaker.state() { 118 ServerHandshakeState::Finish => { 119 self.state = ServerSessionState::ReadChunk; 120 121 let left_bytes = self.handshaker.get_remaining_bytes(); 122 if left_bytes.len() > 0 { 123 self.unpacketizer.extend_data(&left_bytes[..]); 124 self.has_remaing_data = true; 125 } 126 log::info!("[ S->C ] [send_set_chunk_size] "); 127 self.send_set_chunk_size().await?; 128 return Ok(()); 129 } 130 _ => {} 131 } 132 133 Ok(()) 134 } 135 136 async fn read_parse_chunks(&mut self) -> Result<(), SessionError> { 137 if !self.has_remaing_data { 138 match self 139 .io 140 .lock() 141 .await 142 .read_timeout(Duration::from_secs(2)) 143 .await 144 { 145 Ok(data) => { 146 self.bytesio_data = data; 147 } 148 Err(err) => { 149 self.common 150 .unpublish_to_channels(self.app_name.clone(), self.stream_name.clone()) 151 .await?; 152 153 return Err(SessionError { 154 value: SessionErrorValue::BytesIOError(err), 155 }); 156 } 157 } 158 159 self.unpacketizer.extend_data(&self.bytesio_data[..]); 160 } 161 162 self.has_remaing_data = false; 163 164 loop { 165 let result = self.unpacketizer.read_chunks(); 166 167 if let Ok(rv) = result { 168 match rv { 169 UnpackResult::Chunks(chunks) => { 170 for chunk_info in chunks { 171 let timestamp = chunk_info.message_header.timestamp; 172 let msg_stream_id = chunk_info.message_header.msg_streamd_id; 173 174 let mut msg = MessageParser::new(chunk_info).parse()?; 175 self.process_messages(&mut msg, &msg_stream_id, ×tamp) 176 .await?; 177 } 178 } 179 _ => {} 180 } 181 } else { 182 break; 183 } 184 } 185 Ok(()) 186 } 187 188 async fn play(&mut self) -> Result<(), SessionError> { 189 match self.common.send_channel_data().await { 190 Ok(_) => {} 191 192 Err(err) => { 193 self.common 194 .unsubscribe_from_channels( 195 self.app_name.clone(), 196 self.stream_name.clone(), 197 self.subscriber_id, 198 ) 199 .await?; 200 return Err(err); 201 } 202 } 203 204 Ok(()) 205 } 206 207 pub async fn send_set_chunk_size(&mut self) -> Result<(), SessionError> { 208 let mut controlmessage = 209 ProtocolControlMessagesWriter::new(AsyncBytesWriter::new(self.io.clone())); 210 controlmessage.write_set_chunk_size(CHUNK_SIZE).await?; 211 212 Ok(()) 213 } 214 215 pub async fn process_messages( 216 &mut self, 217 rtmp_msg: &mut RtmpMessageData, 218 msg_stream_id: &u32, 219 timestamp: &u32, 220 ) -> Result<(), SessionError> { 221 match rtmp_msg { 222 RtmpMessageData::Amf0Command { 223 command_name, 224 transaction_id, 225 command_object, 226 others, 227 } => { 228 self.on_amf0_command_message( 229 msg_stream_id, 230 command_name, 231 transaction_id, 232 command_object, 233 others, 234 ) 235 .await? 236 } 237 RtmpMessageData::SetChunkSize { chunk_size } => { 238 self.on_set_chunk_size(chunk_size.clone() as usize)?; 239 } 240 RtmpMessageData::AudioData { data } => { 241 self.common.on_audio_data(data, timestamp)?; 242 } 243 RtmpMessageData::VideoData { data } => { 244 self.common.on_video_data(data, timestamp)?; 245 } 246 RtmpMessageData::AmfData { raw_data } => { 247 self.common.on_meta_data(raw_data, timestamp)?; 248 } 249 250 _ => {} 251 } 252 Ok(()) 253 } 254 255 pub async fn on_amf0_command_message( 256 &mut self, 257 stream_id: &u32, 258 command_name: &Amf0ValueType, 259 transaction_id: &Amf0ValueType, 260 command_object: &Amf0ValueType, 261 others: &mut Vec<Amf0ValueType>, 262 ) -> Result<(), SessionError> { 263 let empty_cmd_name = &String::new(); 264 let cmd_name = match command_name { 265 Amf0ValueType::UTF8String(str) => str, 266 _ => empty_cmd_name, 267 }; 268 269 let transaction_id = match transaction_id { 270 Amf0ValueType::Number(number) => number, 271 _ => &0.0, 272 }; 273 274 let empty_cmd_obj: HashMap<String, Amf0ValueType> = HashMap::new(); 275 let obj = match command_object { 276 Amf0ValueType::Object(obj) => obj, 277 _ => &empty_cmd_obj, 278 }; 279 280 match cmd_name.as_str() { 281 "connect" => { 282 log::info!("[ S<-C ] [connect] "); 283 self.on_connect(&transaction_id, &obj).await?; 284 } 285 "createStream" => { 286 log::info!("[ S<-C ] [create stream] "); 287 self.on_create_stream(transaction_id).await?; 288 } 289 "deleteStream" => { 290 if others.len() > 0 { 291 let stream_id = match others.pop() { 292 Some(val) => match val { 293 Amf0ValueType::Number(streamid) => streamid, 294 _ => 0.0, 295 }, 296 _ => 0.0, 297 }; 298 log::info!( 299 "[ S<-C ] [delete stream] app_name: {}, stream_name: {}", 300 self.app_name, 301 self.stream_name 302 ); 303 304 self.on_delete_stream(transaction_id, &stream_id).await?; 305 } 306 } 307 "play" => { 308 log::info!( 309 "[ S<-C ] [play] app_name: {}, stream_name: {}", 310 self.app_name, 311 self.stream_name 312 ); 313 self.unpacketizer.session_type = config::SERVER_PULL; 314 self.on_play(transaction_id, stream_id, others).await?; 315 } 316 "publish" => { 317 self.unpacketizer.session_type = config::SERVER_PUSH; 318 self.on_publish(transaction_id, stream_id, others).await?; 319 } 320 _ => {} 321 } 322 323 Ok(()) 324 } 325 326 fn on_set_chunk_size(&mut self, chunk_size: usize) -> Result<(), SessionError> { 327 self.unpacketizer.update_max_chunk_size(chunk_size); 328 Ok(()) 329 } 330 331 async fn on_connect( 332 &mut self, 333 transaction_id: &f64, 334 command_obj: &HashMap<String, Amf0ValueType>, 335 ) -> Result<(), SessionError> { 336 self.connect_command_object = Some(command_obj.clone()); 337 let mut control_message = 338 ProtocolControlMessagesWriter::new(AsyncBytesWriter::new(self.io.clone())); 339 log::info!("[ S->C ] [set window_acknowledgement_size]"); 340 control_message 341 .write_window_acknowledgement_size(define::WINDOW_ACKNOWLEDGEMENT_SIZE) 342 .await?; 343 344 log::info!("[ S->C ] [set set_peer_bandwidth]",); 345 control_message 346 .write_set_peer_bandwidth( 347 define::PEER_BANDWIDTH, 348 define::peer_bandwidth_limit_type::DYNAMIC, 349 ) 350 .await?; 351 352 let obj_encoding = command_obj.get("objectEncoding"); 353 let encoding = match obj_encoding { 354 Some(Amf0ValueType::Number(encoding)) => encoding, 355 _ => &define::OBJENCODING_AMF0, 356 }; 357 358 let app_name = command_obj.get("app"); 359 self.app_name = match app_name { 360 Some(Amf0ValueType::UTF8String(app)) => app.clone(), 361 _ => { 362 return Err(SessionError { 363 value: SessionErrorValue::NoAppName, 364 }); 365 } 366 }; 367 368 let mut netconnection = NetConnection::new(Arc::clone(&self.io)); 369 log::info!("[ S->C ] [set connect_response]",); 370 netconnection 371 .write_connect_response( 372 &transaction_id, 373 &define::FMSVER.to_string(), 374 &define::CAPABILITIES, 375 &String::from("NetConnection.Connect.Success"), 376 &define::LEVEL.to_string(), 377 &String::from("Connection Succeeded."), 378 encoding, 379 ) 380 .await?; 381 382 Ok(()) 383 } 384 385 pub async fn on_create_stream(&mut self, transaction_id: &f64) -> Result<(), SessionError> { 386 let mut netconnection = NetConnection::new(Arc::clone(&self.io)); 387 netconnection 388 .write_create_stream_response(transaction_id, &define::STREAM_ID) 389 .await?; 390 391 log::info!( 392 "[ S->C ] [create_stream_response] app_name: {}", 393 self.app_name, 394 ); 395 396 Ok(()) 397 } 398 399 pub async fn on_delete_stream( 400 &mut self, 401 transaction_id: &f64, 402 stream_id: &f64, 403 ) -> Result<(), SessionError> { 404 self.common 405 .unpublish_to_channels(self.app_name.clone(), self.stream_name.clone()) 406 .await?; 407 408 let mut netstream = NetStreamWriter::new(Arc::clone(&self.io)); 409 netstream 410 .write_on_status( 411 transaction_id, 412 &"status".to_string(), 413 &"NetStream.DeleteStream.Suceess".to_string(), 414 &"".to_string(), 415 ) 416 .await?; 417 418 //self.unsubscribe_from_channels().await?; 419 log::info!( 420 "[ S->C ] [delete stream success] app_name: {}, stream_name: {}", 421 self.app_name, 422 self.stream_name 423 ); 424 log::trace!("{}", stream_id); 425 426 Ok(()) 427 } 428 pub async fn on_play( 429 &mut self, 430 transaction_id: &f64, 431 stream_id: &u32, 432 other_values: &mut Vec<Amf0ValueType>, 433 ) -> Result<(), SessionError> { 434 let length = other_values.len() as u8; 435 let mut index: u8 = 0; 436 437 let mut stream_name: Option<String> = None; 438 let mut start: Option<f64> = None; 439 let mut duration: Option<f64> = None; 440 let mut reset: Option<bool> = None; 441 442 loop { 443 if index >= length { 444 break; 445 } 446 index = index + 1; 447 stream_name = match other_values.remove(0) { 448 Amf0ValueType::UTF8String(val) => Some(val), 449 _ => None, 450 }; 451 452 if index >= length { 453 break; 454 } 455 index = index + 1; 456 start = match other_values.remove(0) { 457 Amf0ValueType::Number(val) => Some(val), 458 _ => None, 459 }; 460 461 if index >= length { 462 break; 463 } 464 index = index + 1; 465 duration = match other_values.remove(0) { 466 Amf0ValueType::Number(val) => Some(val), 467 _ => None, 468 }; 469 470 if index >= length { 471 break; 472 } 473 //index = index + 1; 474 reset = match other_values.remove(0) { 475 Amf0ValueType::Boolean(val) => Some(val), 476 _ => None, 477 }; 478 break; 479 } 480 481 let mut event_messages = EventMessagesWriter::new(AsyncBytesWriter::new(self.io.clone())); 482 event_messages.write_stream_begin(stream_id.clone()).await?; 483 log::info!( 484 "[ S->C ] [stream begin] app_name: {}, stream_name: {}", 485 self.app_name, 486 self.stream_name 487 ); 488 log::trace!( 489 "{} {} {}", 490 start.is_some(), 491 duration.is_some(), 492 reset.is_some() 493 ); 494 495 let mut netstream = NetStreamWriter::new(Arc::clone(&self.io)); 496 netstream 497 .write_on_status( 498 transaction_id, 499 &"status".to_string(), 500 &"NetStream.Play.Reset".to_string(), 501 &"reset".to_string(), 502 ) 503 .await?; 504 505 netstream 506 .write_on_status( 507 transaction_id, 508 &"status".to_string(), 509 &"NetStream.Play.Start".to_string(), 510 &"play start".to_string(), 511 ) 512 .await?; 513 514 netstream 515 .write_on_status( 516 transaction_id, 517 &"status".to_string(), 518 &"NetStream.Data.Start".to_string(), 519 &"data start.".to_string(), 520 ) 521 .await?; 522 523 netstream 524 .write_on_status( 525 transaction_id, 526 &"status".to_string(), 527 &"NetStream.Play.PublishNotify".to_string(), 528 &"play publish notify.".to_string(), 529 ) 530 .await?; 531 532 event_messages 533 .write_stream_is_record(stream_id.clone()) 534 .await?; 535 log::info!( 536 "[ S->C ] [stream is record] app_name: {}, stream_name: {}", 537 self.app_name, 538 self.stream_name 539 ); 540 self.stream_name = stream_name.clone().unwrap(); 541 self.common 542 .subscribe_from_channels( 543 self.app_name.clone(), 544 stream_name.unwrap(), 545 self.subscriber_id, 546 ) 547 .await?; 548 549 self.state = ServerSessionState::Play; 550 551 Ok(()) 552 } 553 554 pub async fn on_publish( 555 &mut self, 556 transaction_id: &f64, 557 stream_id: &u32, 558 other_values: &mut Vec<Amf0ValueType>, 559 ) -> Result<(), SessionError> { 560 let length = other_values.len(); 561 562 if length < 2 { 563 return Err(SessionError { 564 value: SessionErrorValue::Amf0ValueCountNotCorrect, 565 }); 566 } 567 568 let stream_name = match other_values.remove(0) { 569 Amf0ValueType::UTF8String(val) => val, 570 _ => { 571 return Err(SessionError { 572 value: SessionErrorValue::Amf0ValueCountNotCorrect, 573 }); 574 } 575 }; 576 577 self.stream_name = stream_name; 578 579 let _ = match other_values.remove(0) { 580 Amf0ValueType::UTF8String(val) => val, 581 _ => { 582 return Err(SessionError { 583 value: SessionErrorValue::Amf0ValueCountNotCorrect, 584 }); 585 } 586 }; 587 588 log::info!( 589 "[ S<-C ] [publish] app_name: {}, stream_name: {}", 590 self.app_name, 591 self.stream_name 592 ); 593 594 log::info!( 595 "[ S->C ] [stream begin] app_name: {}, stream_name: {}", 596 self.app_name, 597 self.stream_name 598 ); 599 600 let mut event_messages = EventMessagesWriter::new(AsyncBytesWriter::new(self.io.clone())); 601 event_messages.write_stream_begin(stream_id.clone()).await?; 602 603 let mut netstream = NetStreamWriter::new(Arc::clone(&self.io)); 604 netstream 605 .write_on_status( 606 transaction_id, 607 &"status".to_string(), 608 &"NetStream.Publish.Start".to_string(), 609 &"".to_string(), 610 ) 611 .await?; 612 log::info!( 613 "[ S->C ] [NetStream.Publish.Start] app_name: {}, stream_name: {}", 614 self.app_name, 615 self.stream_name 616 ); 617 618 self.common 619 .publish_to_channels(self.app_name.clone(), self.stream_name.clone()) 620 .await?; 621 622 Ok(()) 623 } 624 } 625