Tim
Tim

Reputation: 81

Correct way to read live camera stream using Indy TIdHttp

I have an app written in Delphi 11. I have used a TIdHttp client to receive a live stream from a camera. The data is received in the OnWork event.

My code looks something like this

procedure TStreamingThread.IdHttpLiveStreamWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
var
  MemoryStream: TMemoryStream;
  BytesToRead: NativeInt;
begin
  MemoryStream := TMemoryStream.Create;
  try
    BytesToRead := IdHttpLiveStream.Response.ContentStream.Position - LastPosition;
    //read from where we got up to last time to the end of the stream
    IdHttpLiveStream.Response.ContentStream.Position := LastPosition;

    MemoryStream.CopyFrom(IdHttpLiveStream.Response.ContentStream, BytesToRead);
    //extract the jpg data from the stream and use it update the screen
    
    //update LastPosition so that we are ready for the next time
    LastPosition := LastPosition + BytesToRead;
  finally   
    MemoryStream.Free;
  end;

I use the extracted jpg data to update a TPicture and it is all working.

My question is regarding ContentStream. Isn't it going to keep increasing in size and eventually cause an out of memory error? Should I be resetting it and if so how?

Upvotes: 2

Views: 338

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 597305

Yes, the ContentStream would continue to be written to, so if you use a target stream like TMemoryStream then it's going to keep growing. You would have to Clear() it each time you consume from it. Otherwise, you might consider using TIdEventStream instead with its OnWrite event.

That being said, TIdHTTP is not really designed to handle streaming media. However, depending on the actual format of the response, you might have some options. For instance, if the media data is being sent using HTTP chunks, you can use the TIdHTTP.OnChunkReceived event. Or, if the media type is 'multipart/...' such as 'multipart/x-mixed-replace' (or if the data is chunked), you can use the hoNoReadMultipartMIME (or hoNoReadChunked) option flag to tell TIdHTTP not to read the response body at all, allowing you to read the body yourself using the IOHandler directly.

Upvotes: 1

Related Questions