blob: 06c3d63e3862170a9d45df0f598acd44dcec20c1 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#ifndef RTC_BASE_STREAM_H_
12#define RTC_BASE_STREAM_H_
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020014#include <stdio.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000015
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020016#include <memory>
17
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "rtc_base/buffer.h"
Steve Anton10542f22019-01-11 09:11:00 -080019#include "rtc_base/constructor_magic.h"
20#include "rtc_base/critical_section.h"
21#include "rtc_base/message_handler.h"
22#include "rtc_base/message_queue.h"
Artem Titove41c4332018-07-25 15:04:28 +020023#include "rtc_base/third_party/sigslot/sigslot.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020024
25namespace rtc {
26
27///////////////////////////////////////////////////////////////////////////////
28// StreamInterface is a generic asynchronous stream interface, supporting read,
29// write, and close operations, and asynchronous signalling of state changes.
30// The interface is designed with file, memory, and socket implementations in
31// mind. Some implementations offer extended operations, such as seeking.
32///////////////////////////////////////////////////////////////////////////////
33
34// The following enumerations are declared outside of the StreamInterface
35// class for brevity in use.
36
37// The SS_OPENING state indicates that the stream will signal open or closed
38// in the future.
39enum StreamState { SS_CLOSED, SS_OPENING, SS_OPEN };
40
41// Stream read/write methods return this value to indicate various success
42// and failure conditions described below.
43enum StreamResult { SR_ERROR, SR_SUCCESS, SR_BLOCK, SR_EOS };
44
45// StreamEvents are used to asynchronously signal state transitionss. The flags
46// may be combined.
47// SE_OPEN: The stream has transitioned to the SS_OPEN state
48// SE_CLOSE: The stream has transitioned to the SS_CLOSED state
49// SE_READ: Data is available, so Read is likely to not return SR_BLOCK
50// SE_WRITE: Data can be written, so Write is likely to not return SR_BLOCK
51enum StreamEvent { SE_OPEN = 1, SE_READ = 2, SE_WRITE = 4, SE_CLOSE = 8 };
52
53class Thread;
54
55struct StreamEventData : public MessageData {
56 int events, error;
Yves Gerey665174f2018-06-19 15:03:05 +020057 StreamEventData(int ev, int er) : events(ev), error(er) {}
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020058};
59
60class StreamInterface : public MessageHandler {
61 public:
Yves Gerey665174f2018-06-19 15:03:05 +020062 enum { MSG_POST_EVENT = 0xF1F1, MSG_MAX = MSG_POST_EVENT };
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020063
64 ~StreamInterface() override;
65
66 virtual StreamState GetState() const = 0;
67
68 // Read attempts to fill buffer of size buffer_len. Write attempts to send
69 // data_len bytes stored in data. The variables read and write are set only
70 // on SR_SUCCESS (see below). Likewise, error is only set on SR_ERROR.
71 // Read and Write return a value indicating:
72 // SR_ERROR: an error occurred, which is returned in a non-null error
73 // argument. Interpretation of the error requires knowledge of the
74 // stream's concrete type, which limits its usefulness.
75 // SR_SUCCESS: some number of bytes were successfully written, which is
76 // returned in a non-null read/write argument.
77 // SR_BLOCK: the stream is in non-blocking mode, and the operation would
78 // block, or the stream is in SS_OPENING state.
79 // SR_EOS: the end-of-stream has been reached, or the stream is in the
80 // SS_CLOSED state.
Yves Gerey665174f2018-06-19 15:03:05 +020081 virtual StreamResult Read(void* buffer,
82 size_t buffer_len,
83 size_t* read,
84 int* error) = 0;
85 virtual StreamResult Write(const void* data,
86 size_t data_len,
87 size_t* written,
88 int* error) = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020089 // Attempt to transition to the SS_CLOSED state. SE_CLOSE will not be
90 // signalled as a result of this call.
91 virtual void Close() = 0;
92
93 // Streams may signal one or more StreamEvents to indicate state changes.
94 // The first argument identifies the stream on which the state change occured.
95 // The second argument is a bit-wise combination of StreamEvents.
96 // If SE_CLOSE is signalled, then the third argument is the associated error
97 // code. Otherwise, the value is undefined.
98 // Note: Not all streams will support asynchronous event signalling. However,
99 // SS_OPENING and SR_BLOCK returned from stream member functions imply that
100 // certain events will be raised in the future.
101 sigslot::signal3<StreamInterface*, int, int> SignalEvent;
102
103 // Like calling SignalEvent, but posts a message to the specified thread,
104 // which will call SignalEvent. This helps unroll the stack and prevent
105 // re-entrancy.
106 void PostEvent(Thread* t, int events, int err);
107 // Like the aforementioned method, but posts to the current thread.
108 void PostEvent(int events, int err);
109
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200110 // Return true if flush is successful.
111 virtual bool Flush();
112
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200113 //
114 // CONVENIENCE METHODS
115 //
116 // These methods are implemented in terms of other methods, for convenience.
117 //
118
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200119 // WriteAll is a helper function which repeatedly calls Write until all the
120 // data is written, or something other than SR_SUCCESS is returned. Note that
121 // unlike Write, the argument 'written' is always set, and may be non-zero
122 // on results other than SR_SUCCESS. The remaining arguments have the
123 // same semantics as Write.
Yves Gerey665174f2018-06-19 15:03:05 +0200124 StreamResult WriteAll(const void* data,
125 size_t data_len,
126 size_t* written,
127 int* error);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200128
129 // Similar to ReadAll. Calls Read until buffer_len bytes have been read, or
130 // until a non-SR_SUCCESS result is returned. 'read' is always set.
Yves Gerey665174f2018-06-19 15:03:05 +0200131 StreamResult ReadAll(void* buffer,
132 size_t buffer_len,
133 size_t* read,
134 int* error);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200135
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200136 protected:
137 StreamInterface();
138
139 // MessageHandler Interface
140 void OnMessage(Message* msg) override;
141
142 private:
143 RTC_DISALLOW_COPY_AND_ASSIGN(StreamInterface);
144};
145
146///////////////////////////////////////////////////////////////////////////////
147// StreamAdapterInterface is a convenient base-class for adapting a stream.
148// By default, all operations are pass-through. Override the methods that you
149// require adaptation. Streams should really be upgraded to reference-counted.
150// In the meantime, use the owned flag to indicate whether the adapter should
151// own the adapted stream.
152///////////////////////////////////////////////////////////////////////////////
153
154class StreamAdapterInterface : public StreamInterface,
155 public sigslot::has_slots<> {
156 public:
157 explicit StreamAdapterInterface(StreamInterface* stream, bool owned = true);
158
159 // Core Stream Interface
160 StreamState GetState() const override;
161 StreamResult Read(void* buffer,
162 size_t buffer_len,
163 size_t* read,
164 int* error) override;
165 StreamResult Write(const void* data,
166 size_t data_len,
167 size_t* written,
168 int* error) override;
169 void Close() override;
170
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200171 bool Flush() override;
172
173 void Attach(StreamInterface* stream, bool owned = true);
174 StreamInterface* Detach();
175
176 protected:
177 ~StreamAdapterInterface() override;
178
179 // Note that the adapter presents itself as the origin of the stream events,
180 // since users of the adapter may not recognize the adapted object.
181 virtual void OnEvent(StreamInterface* stream, int events, int err);
182 StreamInterface* stream() { return stream_; }
183
184 private:
185 StreamInterface* stream_;
186 bool owned_;
187 RTC_DISALLOW_COPY_AND_ASSIGN(StreamAdapterInterface);
188};
189
190///////////////////////////////////////////////////////////////////////////////
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200191// FileStream is a simple implementation of a StreamInterface, which does not
192// support asynchronous notification.
193///////////////////////////////////////////////////////////////////////////////
194
195class FileStream : public StreamInterface {
196 public:
197 FileStream();
198 ~FileStream() override;
199
200 // The semantics of filename and mode are the same as stdio's fopen
201 virtual bool Open(const std::string& filename, const char* mode, int* error);
Yves Gerey665174f2018-06-19 15:03:05 +0200202 virtual bool OpenShare(const std::string& filename,
203 const char* mode,
204 int shflag,
205 int* error);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200206
207 // By default, reads and writes are buffered for efficiency. Disabling
208 // buffering causes writes to block until the bytes on disk are updated.
209 virtual bool DisableBuffering();
210
211 StreamState GetState() const override;
212 StreamResult Read(void* buffer,
213 size_t buffer_len,
214 size_t* read,
215 int* error) override;
216 StreamResult Write(const void* data,
217 size_t data_len,
218 size_t* written,
219 int* error) override;
220 void Close() override;
Niels Möller1a86b782019-01-14 12:48:53 +0100221 virtual bool SetPosition(size_t position);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200222
223 bool Flush() override;
224
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200225 protected:
226 virtual void DoClose();
227
228 FILE* file_;
229
230 private:
231 RTC_DISALLOW_COPY_AND_ASSIGN(FileStream);
232};
233
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200234// FifoBuffer allows for efficient, thread-safe buffering of data between
235// writer and reader. As the data can wrap around the end of the buffer,
236// MemoryStreamBase can't help us here.
237
Niels Möllera8fa2d02018-10-31 10:19:50 +0100238class FifoBuffer final : public StreamInterface {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200239 public:
240 // Creates a FIFO buffer with the specified capacity.
241 explicit FifoBuffer(size_t length);
242 // Creates a FIFO buffer with the specified capacity and owner
243 FifoBuffer(size_t length, Thread* owner);
244 ~FifoBuffer() override;
245 // Gets the amount of data currently readable from the buffer.
246 bool GetBuffered(size_t* data_len) const;
247 // Resizes the buffer to the specified capacity. Fails if data_length_ > size
248 bool SetCapacity(size_t length);
249
250 // Read into |buffer| with an offset from the current read position, offset
251 // is specified in number of bytes.
252 // This method doesn't adjust read position nor the number of available
253 // bytes, user has to call ConsumeReadData() to do this.
Yves Gerey665174f2018-06-19 15:03:05 +0200254 StreamResult ReadOffset(void* buffer,
255 size_t bytes,
256 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200257 size_t* bytes_read);
258
259 // Write |buffer| with an offset from the current write position, offset is
260 // specified in number of bytes.
261 // This method doesn't adjust the number of buffered bytes, user has to call
262 // ConsumeWriteBuffer() to do this.
Yves Gerey665174f2018-06-19 15:03:05 +0200263 StreamResult WriteOffset(const void* buffer,
264 size_t bytes,
265 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200266 size_t* bytes_written);
267
268 // StreamInterface methods
269 StreamState GetState() const override;
270 StreamResult Read(void* buffer,
271 size_t bytes,
272 size_t* bytes_read,
273 int* error) override;
274 StreamResult Write(const void* buffer,
275 size_t bytes,
276 size_t* bytes_written,
277 int* error) override;
278 void Close() override;
Niels Möller1a86b782019-01-14 12:48:53 +0100279
280 // Seek to a byte offset from the beginning of the stream. Returns false if
281 // the stream does not support seeking, or cannot seek to the specified
282 // position.
283 bool SetPosition(size_t position);
284
285 // Get the byte offset of the current position from the start of the stream.
286 // Returns false if the position is not known.
287 bool GetPosition(size_t* position) const;
288
289 // Seek to the start of the stream.
290 bool Rewind() { return SetPosition(0); }
291
Niels Möllera8fa2d02018-10-31 10:19:50 +0100292 // GetReadData returns a pointer to a buffer which is owned by the stream.
293 // The buffer contains data_len bytes. null is returned if no data is
294 // available, or if the method fails. If the caller processes the data, it
295 // must call ConsumeReadData with the number of processed bytes. GetReadData
296 // does not require a matching call to ConsumeReadData if the data is not
297 // processed. Read and ConsumeReadData invalidate the buffer returned by
298 // GetReadData.
299 const void* GetReadData(size_t* data_len);
300 void ConsumeReadData(size_t used);
301 // GetWriteBuffer returns a pointer to a buffer which is owned by the stream.
302 // The buffer has a capacity of buf_len bytes. null is returned if there is
303 // no buffer available, or if the method fails. The call may write data to
304 // the buffer, and then call ConsumeWriteBuffer with the number of bytes
305 // written. GetWriteBuffer does not require a matching call to
306 // ConsumeWriteData if no data is written. Write and
307 // ConsumeWriteData invalidate the buffer returned by GetWriteBuffer.
308 void* GetWriteBuffer(size_t* buf_len);
309 void ConsumeWriteBuffer(size_t used);
310
311 // Return the number of Write()-able bytes remaining before end-of-stream.
312 // Returns false if not known.
313 bool GetWriteRemaining(size_t* size) const;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200314
315 private:
316 // Helper method that implements ReadOffset. Caller must acquire a lock
317 // when calling this method.
danilchap3c6abd22017-09-06 05:46:29 -0700318 StreamResult ReadOffsetLocked(void* buffer,
319 size_t bytes,
320 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200321 size_t* bytes_read)
danilchap3c6abd22017-09-06 05:46:29 -0700322 RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200323
324 // Helper method that implements WriteOffset. Caller must acquire a lock
325 // when calling this method.
danilchap3c6abd22017-09-06 05:46:29 -0700326 StreamResult WriteOffsetLocked(const void* buffer,
327 size_t bytes,
328 size_t offset,
329 size_t* bytes_written)
330 RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200331
332 // keeps the opened/closed state of the stream
danilchap3c6abd22017-09-06 05:46:29 -0700333 StreamState state_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200334 // the allocated buffer
danilchap3c6abd22017-09-06 05:46:29 -0700335 std::unique_ptr<char[]> buffer_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200336 // size of the allocated buffer
danilchap3c6abd22017-09-06 05:46:29 -0700337 size_t buffer_length_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200338 // amount of readable data in the buffer
danilchap3c6abd22017-09-06 05:46:29 -0700339 size_t data_length_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200340 // offset to the readable data
danilchap3c6abd22017-09-06 05:46:29 -0700341 size_t read_position_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200342 // stream callbacks are dispatched on this thread
343 Thread* owner_;
344 // object lock
345 CriticalSection crit_;
346 RTC_DISALLOW_COPY_AND_ASSIGN(FifoBuffer);
347};
348
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200349} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000350
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200351#endif // RTC_BASE_STREAM_H_