RTSP Stream not receiving frames - c#

I am trying to use RTSPClientSharp (https://github.com/BogdanovKirill/RtspClientSharp) to receive an RTSP stream (currently testing with rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mp4) in which the uri works with any other RTSP stream tester I try. In my application it never receives a frame and gets stuck using "rtspClient.ConnectAsync().Wait".
Uri RTSPURL = new Uri("rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mp4");
CancellationToken token = new CancellationToken();
var credentials = new NetworkCredential("", "");
var connectionParameters = new ConnectionParameters(RTSPURL, credentials);
connectionParameters.RtpTransport = RtpTransportProtocol.TCP;
using (var rtspClient = new RtspClient(connectionParameters))
{
rtspClient.ConnectAsync(token).Wait();
rtspClient.ReceiveAsync(token).Wait();
Console.WriteLine("Using RTSPClient");
rtspClient.FrameReceived += (sender, frame) =>
{
Console.WriteLine("Got Frame");
using (MemoryStream memStream = new MemoryStream(frame.FrameSegment.Array, 0, frame.FrameSegment.Array.Count(), true))
{
bmp = new Bitmap(memStream);
}
};
}
Any help would be greatly appreciated!
I'm not receiving any errors so I haven't tried much. Also if I remove the .Wait following the Async functions it doesn't receive any frames.

Related

send and receive image using flask-restful (python API) and C# client

I am trying to send image to python code from Xamarin forms (cross platform), I'm using flask-restful (python API) to build web server and call it from the Xamarin app , so first I converted image to base 64:
Image2.Source = ImageSource.FromStream(() => file.GetStream());
var stream = file.GetStream();
var bytes = new byte[stream.Length];
await stream.ReadAsync(bytes, 0, (int)stream.Length);
base64 = System.Convert.ToBase64String(bytes);
and the post code in xamarin:
var imageContent = new MultipartFormDataContent
{
{ new StringContent(base64), "ImageData" }
};
var httpClient = new HttpClient();
var imageResponse = await httpClient.PostAsync("http://localhost:52524/", imageContent);
//
var resultImageContent = imageResponse.Content.ReadAsStringAsync().Result;
if (resultImageContent != null)
{
//some code here
}
now how I can receive the image from the python code.

Not receiving JSON data from Microsoft FaceAPI

I am trying to get JSON data from a picture using Microsoft's FaceAPI. I am receiving a StatusCode OK, but am not getting anything significant back. I have verified that the MemoryStream has the right data (which I am getting from an Image control) by saving it to a file.
private async Task<string> GetJSON()
{
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "mykey");
// Request parameters
queryString["returnFaceId"] = "true";
queryString["returnFaceLandmarks"] = "false";
var uri = "https://api.projectoxford.ai/face/v1.0/detect?" + queryString;
HttpResponseMessage response;
// Request body
byte[] byteData = ImageToByte();
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response = await client.PostAsync(uri, content);
}
return "";
}
private byte[] ImageToByte()
{
using (MemoryStream stream = new MemoryStream())
{
videoBox.Dispatcher.Invoke(delegate
{
var encoder = new PngBitmapEncoder();
var flippedBitmap = new TransformedBitmap();
flippedBitmap.BeginInit();
flippedBitmap.Source = (BitmapSource)videoBox.Source;
var transform = new ScaleTransform(-1, 1);
flippedBitmap.Transform = transform;
flippedBitmap.EndInit();
encoder.Frames.Add(BitmapFrame.Create(flippedBitmap));
encoder.Save(stream);
});
using (FileStream test = new FileStream("snapshot.bmp", FileMode.Create))
{
stream.Position = 0;
stream.CopyTo(test);
}
return stream.ToArray();
}
}
You'll want to call await response.Content.ReadAsStringAsync() to get the JSON.
Alternatively, you can use the Microsoft.ProjectOxford.Face NuGet package which does the plumbing for you, plus provide C# types thereby relieving you the tedium of parsing the JSON.
I am not a c# programmer but after looking at your code, method GetJSON is returning hard coded empty string that might be the cause you are not getting anything back from the server after invoking this method or second reason could be your asynchronous server configuration is not working properly thus its returning blank first and doing actual operation later.

Stream.ReadAsync() on first invoke very slow

I am writing a class to handle file downloads and i am using this code [simplified]:
var webRequest = (HttpWebRequest)WebRequest.Create(downloadOperation.Link);
webRequest.Proxy = null;
using (var webResponse = await webRequest.GetResponseAsync())
{
using (var downloadStream = webResponse.GetResponseStream())
{
using (var outputFileWriteStream = await outputFile.OpenStreamForWriteAsync())
{
var buffer = new byte[4096];
var downloadedBytes = 0;
var totalBytes = webResponse.ContentLength;
while (downloadedBytes < totalBytes)
{
//*************************THIS LINE TAKES ABOUT 32 SECONDS TO EXECUTE ON FIRST INVOKE, ALL NEXT INVOKES TAKE ABOUT 120MS***************************
var currentRead = await downloadStream.ReadAsync(buffer, 0, buffer.Length);
//*******************************************************************************************************************************************************************
await outputFileWriteStream.WriteAsync(buffer, 0, currentRead);
}
}
}
}
Can you please explain to me why is it taking that long on first invoke and not on the next ones? I am worried that it is downloading the entire file on the first read.
Note that the files are usually between 3~15MB.
I am worried that it is downloading the entire file on the first read.
That's precisely what's happening. You can change that by setting webRequest.AllowReadStreamBuffering to false.
So i found a way to fix this problem, but it doesn't use WebRequest class.
I am now using the HttpClient found in (Windows.Web.Http).
Here is the fixed code:
var client = new Windows.Web.Http.HttpClient(); // prepare the http client
//get the response from the server
using (var webResponse = await client.GetAsync(downloadOperation.Link, HttpCompletionOption.ResponseHeadersRead)) //***********Node the HttpCompletionOption.ResponseHeaderRead, this means that the operation completes as soon as the client receives the http headers instead of waiting for the entire response content to be read
{
using (var downloadStream = (await webResponse.Content.ReadAsInputStreamAsync()).AsStreamForRead() )
{
using (var outputFileWriteStream = await outputFile.OpenStreamForWriteAsync())
{
var buffer = new byte[4096];
var downloadedBytes = 0;
var totalBytes = webResponse.ContentLength;
while (downloadedBytes < totalBytes)
{
//*************************THIS LINE NO LONGER TAKES A LONG TIME TO PERFORM FIRST READ***************************
var currentRead = await downloadStream.ReadAsync(buffer, 0, buffer.Length);
//*******************************************************************************************************************************************************************
await outputFileWriteStream.WriteAsync(buffer, 0, currentRead);
}
}
}
}
Hope this will help someone out there ;)
thank you all

Unknown / empty background task after calling BackgroundDownloadAsync or BackgroundUploadAsync from Live SDK

Any idea why there will be an "empty" task listed under Lifecycle Events whenever a call to BackgrouDownloadAsync or BackgroundUploadAsync is made?
I can't post a picture yet. Please refer to the originally post in http://social.msdn.microsoft.com/Forums/en-US/39944e7d-feb2-4e06-b980-6ff41588ec50/unknown-empty-background-task?forum=wpdevelop
Here's what I did to replace BackgroundDownloadAsync and BackgroundUploadAsync, omitting any try-catch and error checking codes. These calls will not cause the empty entry in "Lifecycle Events" drop-down. Not sure if it is due to issue in VS 2013.
To download (this is messy, there must be another way)
LiveConnectClient connectClient = new LiveConnectClient(this.Session);
LiveOperationResult _opResult = await connectClient.GetAsync(FileID + "/content");
dynamic _result = _opResult.Result;
CancellationTokenSource cts = new CancellationTokenSource();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri(_result.location as string, UriKind.Absolute));
HttpResponseMessage response = await httpClient.SendRequestAsync(request, HttpCompletionOption.ResponseHeadersRead).AsTask(cts.Token);
using (var _stream = (await OutputFile.OpenStreamForWriteAsync()).AsOutputStream())
{
await response.Content.WriteToStreamAsync(_stream).AsTask(cts.Token);
await _stream.FlushAsync();
}
To upload
LiveConnectClient connectClient = new LiveConnectClient(this.Session);
using (Stream stream = await InputFile.OpenStreamForReadAsync())
{
using (StreamReader reader = new StreamReader(stream))
{
LiveOperationResult _opResult = await connectClient.PutAsync(Awesome2FolderID + "/files/" + OneDriveFilename, reader.ReadToEnd());
}
}

Using Catchoom in C# WP8.1 project

i want to use catchoom in c# , but not able to find any sample could any one please provide any sample code if have.
i have got this sample of curl
curl -F "image=#CATask1-Correct.png" -F "token=sometoken" https://r.catchoom.com/v1/search
Can some one covert this to c# ?
I tried to convert it as shown below:
Here's my code:
public static async Task<string> Upload(byte[] image)
{
using (var client = new HttpClient())
{
// string boundary = "---XXX---";
using (var content = new MultipartFormDataContent())
{
string token = "sometoken";
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(token);
writer.Flush();
stream.Position = 0;
// adding Token and Image to the request
content.Add(new StreamContent(stream), "token");
content.Add(new StreamContent(new MemoryStream(image)), "bilddatei", "upload.jpg");
using (
var message = await client.PostAsync("https://r.catchoom.com/v1/search", content))
{
var input = await message.Content.ReadAsStringAsync();
return input;
}
}
}
}
then I called the method in the on-click event handler:
private async void mybtn_Click(object sender, RoutedEventArgs e)
{
// converting the image to a byte array
BitmapImage bitmapImage = new BitmapImage(new Uri("http://www.familyfuntwincities.com/wp-content/uploads/2013/09/apple_red_1_clipart.png?s=128&g=1"));
RandomAccessStreamReference rasr = RandomAccessStreamReference.CreateFromUri(bitmapImage.UriSource);
var streamWithContent = await rasr.OpenReadAsync();
byte[] buffer = new byte[streamWithContent.Size];
await streamWithContent.ReadAsync(buffer.AsBuffer(), (uint)streamWithContent.Size, InputStreamOptions.None);
// calling the upload method
string output = await Upload(buffer);
mytext1.Text = output;
}
but I keep getting "image is missing" error from the catchoom server although I managed to upload the image to other servers in the same way ( without the token part of course).
My question is: How to add multipule part content? what's the right boundary between the Token part and the image part in order to be recognized by catchoom?
Here is what worked for me:
public static async Task<string> Test(string token, Stream stream, string fileName)
{
HttpClient client = new HttpClient();
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StringContent(token), "token");
content.Add(new StreamContent(stream), "image", fileName);
var resp = await client.PostAsync("https://r.catchoom.com/v1/search", content);
return await resp.Content.ReadAsStringAsync();
}
If you wanted to use the image you listed in your sample, here is how I would fetch it:
HttpClient client = new HttpClient();
var stream = await client.GetStreamAsync("http://www.familyfuntwincities.com/wp-content/uploads/2013/09/apple_red_1_clipart.png?s=128&g=1");
return await Test("<SOME_TOKEN_VALUE>", stream, "apple.png");
However the API claims that the image is unsupported due to alpha transparency. You can find some other samples that show you how to strip alpha transparency if that is important. The above code worked fine for images that don't have alpha transparency.

Categories