blob: 718c12e9863b64e6b1e8f0c658023bc639712141 [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 // Seek to a byte offset from the beginning of the stream. Returns false if
111 // the stream does not support seeking, or cannot seek to the specified
112 // position.
113 virtual bool SetPosition(size_t position);
114
115 // Get the byte offset of the current position from the start of the stream.
116 // Returns false if the position is not known.
117 virtual bool GetPosition(size_t* position) const;
118
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200119 // Return true if flush is successful.
120 virtual bool Flush();
121
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200122 //
123 // CONVENIENCE METHODS
124 //
125 // These methods are implemented in terms of other methods, for convenience.
126 //
127
128 // Seek to the start of the stream.
129 inline bool Rewind() { return SetPosition(0); }
130
131 // WriteAll is a helper function which repeatedly calls Write until all the
132 // data is written, or something other than SR_SUCCESS is returned. Note that
133 // unlike Write, the argument 'written' is always set, and may be non-zero
134 // on results other than SR_SUCCESS. The remaining arguments have the
135 // same semantics as Write.
Yves Gerey665174f2018-06-19 15:03:05 +0200136 StreamResult WriteAll(const void* data,
137 size_t data_len,
138 size_t* written,
139 int* error);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200140
141 // Similar to ReadAll. Calls Read until buffer_len bytes have been read, or
142 // until a non-SR_SUCCESS result is returned. 'read' is always set.
Yves Gerey665174f2018-06-19 15:03:05 +0200143 StreamResult ReadAll(void* buffer,
144 size_t buffer_len,
145 size_t* read,
146 int* error);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200147
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200148 protected:
149 StreamInterface();
150
151 // MessageHandler Interface
152 void OnMessage(Message* msg) override;
153
154 private:
155 RTC_DISALLOW_COPY_AND_ASSIGN(StreamInterface);
156};
157
158///////////////////////////////////////////////////////////////////////////////
159// StreamAdapterInterface is a convenient base-class for adapting a stream.
160// By default, all operations are pass-through. Override the methods that you
161// require adaptation. Streams should really be upgraded to reference-counted.
162// In the meantime, use the owned flag to indicate whether the adapter should
163// own the adapted stream.
164///////////////////////////////////////////////////////////////////////////////
165
166class StreamAdapterInterface : public StreamInterface,
167 public sigslot::has_slots<> {
168 public:
169 explicit StreamAdapterInterface(StreamInterface* stream, bool owned = true);
170
171 // Core Stream Interface
172 StreamState GetState() const override;
173 StreamResult Read(void* buffer,
174 size_t buffer_len,
175 size_t* read,
176 int* error) override;
177 StreamResult Write(const void* data,
178 size_t data_len,
179 size_t* written,
180 int* error) override;
181 void Close() override;
182
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200183 bool SetPosition(size_t position) override;
184 bool GetPosition(size_t* position) const override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200185 bool Flush() override;
186
187 void Attach(StreamInterface* stream, bool owned = true);
188 StreamInterface* Detach();
189
190 protected:
191 ~StreamAdapterInterface() override;
192
193 // Note that the adapter presents itself as the origin of the stream events,
194 // since users of the adapter may not recognize the adapted object.
195 virtual void OnEvent(StreamInterface* stream, int events, int err);
196 StreamInterface* stream() { return stream_; }
197
198 private:
199 StreamInterface* stream_;
200 bool owned_;
201 RTC_DISALLOW_COPY_AND_ASSIGN(StreamAdapterInterface);
202};
203
204///////////////////////////////////////////////////////////////////////////////
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200205// FileStream is a simple implementation of a StreamInterface, which does not
206// support asynchronous notification.
207///////////////////////////////////////////////////////////////////////////////
208
209class FileStream : public StreamInterface {
210 public:
211 FileStream();
212 ~FileStream() override;
213
214 // The semantics of filename and mode are the same as stdio's fopen
215 virtual bool Open(const std::string& filename, const char* mode, int* error);
Yves Gerey665174f2018-06-19 15:03:05 +0200216 virtual bool OpenShare(const std::string& filename,
217 const char* mode,
218 int shflag,
219 int* error);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200220
221 // By default, reads and writes are buffered for efficiency. Disabling
222 // buffering causes writes to block until the bytes on disk are updated.
223 virtual bool DisableBuffering();
224
225 StreamState GetState() const override;
226 StreamResult Read(void* buffer,
227 size_t buffer_len,
228 size_t* read,
229 int* error) override;
230 StreamResult Write(const void* data,
231 size_t data_len,
232 size_t* written,
233 int* error) override;
234 void Close() override;
235 bool SetPosition(size_t position) override;
236 bool GetPosition(size_t* position) const override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200237
238 bool Flush() override;
239
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200240 protected:
241 virtual void DoClose();
242
243 FILE* file_;
244
245 private:
246 RTC_DISALLOW_COPY_AND_ASSIGN(FileStream);
247};
248
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200249// FifoBuffer allows for efficient, thread-safe buffering of data between
250// writer and reader. As the data can wrap around the end of the buffer,
251// MemoryStreamBase can't help us here.
252
Niels Möllera8fa2d02018-10-31 10:19:50 +0100253class FifoBuffer final : public StreamInterface {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200254 public:
255 // Creates a FIFO buffer with the specified capacity.
256 explicit FifoBuffer(size_t length);
257 // Creates a FIFO buffer with the specified capacity and owner
258 FifoBuffer(size_t length, Thread* owner);
259 ~FifoBuffer() override;
260 // Gets the amount of data currently readable from the buffer.
261 bool GetBuffered(size_t* data_len) const;
262 // Resizes the buffer to the specified capacity. Fails if data_length_ > size
263 bool SetCapacity(size_t length);
264
265 // Read into |buffer| with an offset from the current read position, offset
266 // is specified in number of bytes.
267 // This method doesn't adjust read position nor the number of available
268 // bytes, user has to call ConsumeReadData() to do this.
Yves Gerey665174f2018-06-19 15:03:05 +0200269 StreamResult ReadOffset(void* buffer,
270 size_t bytes,
271 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200272 size_t* bytes_read);
273
274 // Write |buffer| with an offset from the current write position, offset is
275 // specified in number of bytes.
276 // This method doesn't adjust the number of buffered bytes, user has to call
277 // ConsumeWriteBuffer() to do this.
Yves Gerey665174f2018-06-19 15:03:05 +0200278 StreamResult WriteOffset(const void* buffer,
279 size_t bytes,
280 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200281 size_t* bytes_written);
282
283 // StreamInterface methods
284 StreamState GetState() const override;
285 StreamResult Read(void* buffer,
286 size_t bytes,
287 size_t* bytes_read,
288 int* error) override;
289 StreamResult Write(const void* buffer,
290 size_t bytes,
291 size_t* bytes_written,
292 int* error) override;
293 void Close() override;
Niels Möllera8fa2d02018-10-31 10:19:50 +0100294 // GetReadData returns a pointer to a buffer which is owned by the stream.
295 // The buffer contains data_len bytes. null is returned if no data is
296 // available, or if the method fails. If the caller processes the data, it
297 // must call ConsumeReadData with the number of processed bytes. GetReadData
298 // does not require a matching call to ConsumeReadData if the data is not
299 // processed. Read and ConsumeReadData invalidate the buffer returned by
300 // GetReadData.
301 const void* GetReadData(size_t* data_len);
302 void ConsumeReadData(size_t used);
303 // GetWriteBuffer returns a pointer to a buffer which is owned by the stream.
304 // The buffer has a capacity of buf_len bytes. null is returned if there is
305 // no buffer available, or if the method fails. The call may write data to
306 // the buffer, and then call ConsumeWriteBuffer with the number of bytes
307 // written. GetWriteBuffer does not require a matching call to
308 // ConsumeWriteData if no data is written. Write and
309 // ConsumeWriteData invalidate the buffer returned by GetWriteBuffer.
310 void* GetWriteBuffer(size_t* buf_len);
311 void ConsumeWriteBuffer(size_t used);
312
313 // Return the number of Write()-able bytes remaining before end-of-stream.
314 // Returns false if not known.
315 bool GetWriteRemaining(size_t* size) const;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200316
317 private:
318 // Helper method that implements ReadOffset. Caller must acquire a lock
319 // when calling this method.
danilchap3c6abd22017-09-06 05:46:29 -0700320 StreamResult ReadOffsetLocked(void* buffer,
321 size_t bytes,
322 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200323 size_t* bytes_read)
danilchap3c6abd22017-09-06 05:46:29 -0700324 RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200325
326 // Helper method that implements WriteOffset. Caller must acquire a lock
327 // when calling this method.
danilchap3c6abd22017-09-06 05:46:29 -0700328 StreamResult WriteOffsetLocked(const void* buffer,
329 size_t bytes,
330 size_t offset,
331 size_t* bytes_written)
332 RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200333
334 // keeps the opened/closed state of the stream
danilchap3c6abd22017-09-06 05:46:29 -0700335 StreamState state_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200336 // the allocated buffer
danilchap3c6abd22017-09-06 05:46:29 -0700337 std::unique_ptr<char[]> buffer_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200338 // size of the allocated buffer
danilchap3c6abd22017-09-06 05:46:29 -0700339 size_t buffer_length_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200340 // amount of readable data in the buffer
danilchap3c6abd22017-09-06 05:46:29 -0700341 size_t data_length_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200342 // offset to the readable data
danilchap3c6abd22017-09-06 05:46:29 -0700343 size_t read_position_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200344 // stream callbacks are dispatched on this thread
345 Thread* owner_;
346 // object lock
347 CriticalSection crit_;
348 RTC_DISALLOW_COPY_AND_ASSIGN(FifoBuffer);
349};
350
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200351} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000352
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200353#endif // RTC_BASE_STREAM_H_