xref: /haiku/src/add-ons/media/plugins/http_streamer/HTTPMediaIO.cpp (revision 40dca224fc1c1a0e7e92d8eb97b61e4db95b8c00)
1 /*
2  * Copyright 2016, Dario Casalinuovo
3  * Distributed under the terms of the MIT License.
4  */
5 
6 
7 #include "HTTPMediaIO.h"
8 
9 #include <Handler.h>
10 #include <UrlProtocolRoster.h>
11 
12 #include <stdio.h>
13 
14 
15 class FileListener : public BUrlProtocolAsynchronousListener
16 {
17 public:
18 		FileListener(BAdapterIO* owner)
19 			:
20 			BUrlProtocolAsynchronousListener(true),
21 			fRequest(NULL),
22 			fAdapterIO(owner),
23 			fTotalSize(0)
24 		{
25 			fInputAdapter = fAdapterIO->BuildInputAdapter();
26 		}
27 
28 		virtual ~FileListener() {};
29 
30 		bool ConnectionSuccessful() const
31 		{
32 			return fRequest != NULL;
33 		}
34 
35 		void ConnectionOpened(BUrlRequest* request)
36 		{
37 			if (fRequest != NULL)
38 				fRequest->Stop();
39 
40 			fRequest = request;
41 			fTotalSize = request->Result().Length();
42 		}
43 
44 		void DataReceived(BUrlRequest* request, const char* data,
45 			off_t position, ssize_t size)
46 		{
47 			if (request != fRequest)
48 				delete request;
49 
50 			fInputAdapter->Write(data, size);
51 		}
52 
53 		void RequestCompleted(BUrlRequest* request, bool success)
54 		{
55 			if (request != fRequest)
56 				return;
57 
58 			fRequest = NULL;
59 			delete request;
60 		}
61 
62 		off_t		TotalSize() const
63 		{
64 			return fTotalSize;
65 		}
66 
67 private:
68 		BUrlRequest*	fRequest;
69 		BAdapterIO*		fAdapterIO;
70 		BInputAdapter*	fInputAdapter;
71 		off_t			fTotalSize;
72 };
73 
74 
75 HTTPMediaIO::HTTPMediaIO(BUrl* url)
76 	:
77 	BAdapterIO(
78 		B_MEDIA_STREAMING | B_MEDIA_SEEK_BACKWARD,
79 		B_INFINITE_TIMEOUT),
80 	fInitErr(B_OK)
81 {
82 	fContext = new BUrlContext();
83 	fContext->AcquireReference();
84 
85 	fListener = new FileListener(this);
86 
87 	fReq = BUrlProtocolRoster::MakeRequest(*url,
88 		fListener, fContext);
89 
90 	fReq->Run();
91 }
92 
93 
94 HTTPMediaIO::~HTTPMediaIO()
95 {
96 	delete fReq;
97 	delete fListener;
98 
99 	fContext->ReleaseReference();
100 	delete fContext;
101 }
102 
103 
104 status_t
105 HTTPMediaIO::InitCheck() const
106 {
107 	return fInitErr;
108 }
109 
110 
111 ssize_t
112 HTTPMediaIO::WriteAt(off_t position, const void* buffer, size_t size)
113 {
114 	return B_NOT_SUPPORTED;
115 }
116 
117 
118 status_t
119 HTTPMediaIO::SetSize(off_t size)
120 {
121 	return B_NOT_SUPPORTED;
122 }
123 
124 
125 status_t
126 HTTPMediaIO::GetSize(off_t* size) const
127 {
128 	*size = fListener->TotalSize();
129 	return B_OK;
130 }
131