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); }