public void HandleRequest(string url, HybridDSP.Net.HTTP.HTTPServerRequest request, HybridDSP.Net.HTTP.HTTPServerResponse response) { lock (sync) { if (Thread.CurrentThread.Name != null) Thread.CurrentThread.Name = "RTMPProxy"; RTMP rtmp = null; try { NameValueCollection paramsHash = System.Web.HttpUtility.ParseQueryString(new Uri(url).Query); Logger.Log("RTMP Request Parameters:"); foreach (var param in paramsHash.AllKeys) Logger.Log(string.Format("{0}={1}", param, paramsHash[param])); Link link = new Link(); if (paramsHash["rtmpurl"] != null) link = Link.FromRtmpUrl(new Uri(paramsHash["rtmpurl"])); if (paramsHash["app"] != null) link.app = paramsHash["app"]; if (paramsHash["tcUrl"] != null) link.tcUrl = paramsHash["tcUrl"]; if (paramsHash["hostname"] != null) link.hostname = paramsHash["hostname"]; if (paramsHash["port"] != null) link.port = int.Parse(paramsHash["port"]); if (paramsHash["playpath"] != null) link.playpath = paramsHash["playpath"]; if (paramsHash["subscribepath"] != null) link.subscribepath = paramsHash["subscribepath"]; if (paramsHash["pageurl"] != null) link.pageUrl = paramsHash["pageurl"]; if (paramsHash["swfurl"] != null) link.swfUrl = paramsHash["swfurl"]; if (paramsHash["swfsize"] != null) link.SWFSize = int.Parse(paramsHash["swfsize"]); if (paramsHash["swfhash"] != null) link.SWFHash = Link.ArrayFromHexString(paramsHash["swfhash"]); if (paramsHash["swfVfy"] != null) { link.swfUrl = paramsHash["swfVfy"]; link.swfVerify = true; } if (paramsHash["live"] != null) bool.TryParse(paramsHash["live"], out link.bLiveStream); if (paramsHash["auth"] != null) link.auth = paramsHash["auth"]; if (paramsHash["token"] != null) link.token = paramsHash["token"]; if (paramsHash["conn"] != null) link.extras = Link.ParseAMF(paramsHash["conn"]); if (link.tcUrl != null && link.tcUrl.ToLower().StartsWith("rtmpe")) link.protocol = Protocol.RTMPE; if (link.swfVerify) link.GetSwf(); rtmp = new RTMP() { Link = link }; ConnectAndGetStream(rtmp, request, response, ref invalidHeader); } finally { if (rtmp != null) rtmp.Close(); } Logger.Log("Request finished."); } }
public static void ConnectAndGetStream(RTMP rtmp, HybridDSP.Net.HTTP.HTTPServerRequest request, HybridDSP.Net.HTTP.HTTPServerResponse response, ref bool invalidHeader) { Stream responseStream = null; try { bool connected = rtmp.Connect(); if (connected) { request.KeepAlive = true; // keep connection alive response.ContentType = "video/x-flv"; response.KeepAlive = true; //response.ChunkedTransferEncoding = true; FLVStream fs = new FLVStream(); fs.WriteFLV(rtmp, delegate() { // we must set a content length for the File Source filter, otherwise it thinks we have no content // but don't set a length if it is our user agent, so a download will always be complete if (request.Get("User-Agent") != HeadWeb.HeadWebSettings.Instance.UserAgent) response.ContentLength = fs.EstimatedLength; responseStream = response.Send(); return responseStream; }, response._session._socket); invalidHeader = rtmp.invalidRTMPHeader; if (responseStream != null) { if (request.Get("User-Agent") != HeadWeb.HeadWebSettings.Instance.UserAgent) { // keep appending "0" - bytes until we filled the estimated length when sending data to the File Source filter long zeroBytes = fs.EstimatedLength - fs.Length; while (zeroBytes > 0) { int chunk = (int)Math.Min(4096, zeroBytes); byte[] buffer = new byte[chunk]; responseStream.Write(buffer, 0, chunk); zeroBytes -= chunk; } } responseStream.Close(); } } else { response.StatusAndReason = HybridDSP.Net.HTTP.HTTPServerResponse.HTTPStatus.HTTP_INTERNAL_SERVER_ERROR; response.Send().Close(); } } catch (Exception ex) { Logger.Log(ex.ToString()); if (responseStream != null) { responseStream.Close(); } else { // no data to play was ever received and send to the requesting client -> send an error now response.ContentLength = 0; response.StatusAndReason = HybridDSP.Net.HTTP.HTTPServerResponse.HTTPStatus.HTTP_INTERNAL_SERVER_ERROR; response.Send().Close(); } } }
public void WriteFLV(RTMP rtmp, DataReadyHandler DataReady, System.Net.Sockets.Socket socket) { // rtmp must be connected and ready for playback data if (!rtmp.IsConnected() || !rtmp.Playing) return; Stream outputStream = null; // we will be writing in chunks, so use our own stream MemoryStream ms = new MemoryStream(); // header ms.Write(FLVStream.flvHeader, 0, FLVStream.flvHeader.Length); // write stream uint timeStamp = 0; int result = 0; int packets = 0; int httpChunkSize = 1024 * 10; // first chunk should be big enough so the direct show filter can get all the info and do some buffering int reconnects = 0; do { try { int retries = 0; do { RTMPPacket packet = null; result = rtmp.GetNextMediaPacket(out packet); if (result == 1) { if (!WriteStream(packet, ms, out timeStamp)) break; packets++; if (packets > 10 && ms.Length > httpChunkSize) { if (outputStream == null) // first time writing data { if (rtmp.CombinedTracksLength > 0) { EstimatedLength = rtmp.CombinedTracksLength + (rtmp.CombinedTracksLength / rtmp.InChunkSize) * 11; } else if (rtmp.CombinedBitrates > 0) { EstimatedLength = (long)(rtmp.CombinedBitrates * 1000 / 8 * (rtmp.Duration <= 0 ? 10800 : rtmp.Duration)); // set 3h if no duration in metadata } else { // nothing was in the metadata -> just use duration and a bitrate of 2000 EstimatedLength = (long)(2000 * 1000 / 8 * (rtmp.Duration <= 0 ? 10800 : rtmp.Duration)); // set 3h if no duration in metadata } EstimatedLength = (long)((double)EstimatedLength * 1.5d); if (EstimatedLength > 0x7fffffff) EstimatedLength = 0x7fffffff; // honor 2GB size limit outputStream = DataReady(); // get the stream httpChunkSize = 1024; // reduce chunksize } byte[] buffer = ms.ToArray(); outputStream.Write(buffer, 0, buffer.Length); Length += (uint)buffer.Length; ms = new MemoryStream(); } } else if (result == 0) { if (retries > 0) { rtmp.invalidRTMPHeader = true; break; } /* Did we already try pausing, and it still didn't work? */ if (rtmp.Pausing == 3) { // Only one try at reconnecting... retries = 1; if (!rtmp.ReconnectStream()) { rtmp.invalidRTMPHeader = true; Logger.Log("Failed to reconnect the stream."); break; } } else if (!rtmp.ToggleStream()) { rtmp.invalidRTMPHeader = true; Logger.Log("Failed to resume the stream."); break; } } } while (result != 2 && rtmp.Playing && socket.Connected); } catch (Exception ex) { Logger.Log(ex.ToString()); } finally { // if data already received and connection now closed - try reconnecting rtmp if (result != 2 && timeStamp > 0 && reconnects < 1) { Logger.Log("Connection failed before playback ended - trying reconnect"); rtmp.Link.seekTime = timeStamp; reconnects++; if (rtmp.Connect()) reconnects = 0; } } } while (reconnects <= 1 && result != 2 && rtmp.Playing && socket.Connected); }