blob: a7c626630452bbf589e7953df0beed66ee53feda [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
Niels Möller23213d92019-01-22 11:01:24 +0100195// TODO(bugs.webrtc.org/6463): Delete this class.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200196class FileStream : public StreamInterface {
197 public:
198 FileStream();
199 ~FileStream() override;
200
201 // The semantics of filename and mode are the same as stdio's fopen
202 virtual bool Open(const std::string& filename, const char* mode, int* error);
Yves Gerey665174f2018-06-19 15:03:05 +0200203 virtual bool OpenShare(const std::string& filename,
204 const char* mode,
205 int shflag,
206 int* error);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200207
208 // By default, reads and writes are buffered for efficiency. Disabling
209 // buffering causes writes to block until the bytes on disk are updated.
210 virtual bool DisableBuffering();
211
212 StreamState GetState() const override;
213 StreamResult Read(void* buffer,
214 size_t buffer_len,
215 size_t* read,
216 int* error) override;
217 StreamResult Write(const void* data,
218 size_t data_len,
219 size_t* written,
220 int* error) override;
221 void Close() override;
Niels Möller1a86b782019-01-14 12:48:53 +0100222 virtual bool SetPosition(size_t position);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200223
224 bool Flush() override;
225
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200226 protected:
227 virtual void DoClose();
228
229 FILE* file_;
230
231 private:
232 RTC_DISALLOW_COPY_AND_ASSIGN(FileStream);
233};
234
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200235// FifoBuffer allows for efficient, thread-safe buffering of data between
236// writer and reader. As the data can wrap around the end of the buffer,
237// MemoryStreamBase can't help us here.
238
Niels Möllera8fa2d02018-10-31 10:19:50 +0100239class FifoBuffer final : public StreamInterface {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200240 public:
241 // Creates a FIFO buffer with the specified capacity.
242 explicit FifoBuffer(size_t length);
243 // Creates a FIFO buffer with the specified capacity and owner
244 FifoBuffer(size_t length, Thread* owner);
245 ~FifoBuffer() override;
246 // Gets the amount of data currently readable from the buffer.
247 bool GetBuffered(size_t* data_len) const;
248 // Resizes the buffer to the specified capacity. Fails if data_length_ > size
249 bool SetCapacity(size_t length);
250
251 // Read into |buffer| with an offset from the current read position, offset
252 // is specified in number of bytes.
253 // This method doesn't adjust read position nor the number of available
254 // bytes, user has to call ConsumeReadData() to do this.
Yves Gerey665174f2018-06-19 15:03:05 +0200255 StreamResult ReadOffset(void* buffer,
256 size_t bytes,
257 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200258 size_t* bytes_read);
259
260 // Write |buffer| with an offset from the current write position, offset is
261 // specified in number of bytes.
262 // This method doesn't adjust the number of buffered bytes, user has to call
263 // ConsumeWriteBuffer() to do this.
Yves Gerey665174f2018-06-19 15:03:05 +0200264 StreamResult WriteOffset(const void* buffer,
265 size_t bytes,
266 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200267 size_t* bytes_written);
268
269 // StreamInterface methods
270 StreamState GetState() const override;
271 StreamResult Read(void* buffer,
272 size_t bytes,
273 size_t* bytes_read,
274 int* error) override;
275 StreamResult Write(const void* buffer,
276 size_t bytes,
277 size_t* bytes_written,
278 int* error) override;
279 void Close() override;
Niels Möller1a86b782019-01-14 12:48:53 +0100280
281 // Seek to a byte offset from the beginning of the stream. Returns false if
282 // the stream does not support seeking, or cannot seek to the specified
283 // position.
284 bool SetPosition(size_t position);
285
286 // Get the byte offset of the current position from the start of the stream.
287 // Returns false if the position is not known.
288 bool GetPosition(size_t* position) const;
289
290 // Seek to the start of the stream.
291 bool Rewind() { return SetPosition(0); }
292
Niels Möllera8fa2d02018-10-31 10:19:50 +0100293 // GetReadData returns a pointer to a buffer which is owned by the stream.
294 // The buffer contains data_len bytes. null is returned if no data is
295 // available, or if the method fails. If the caller processes the data, it
296 // must call ConsumeReadData with the number of processed bytes. GetReadData
297 // does not require a matching call to ConsumeReadData if the data is not
298 // processed. Read and ConsumeReadData invalidate the buffer returned by
299 // GetReadData.
300 const void* GetReadData(size_t* data_len);
301 void ConsumeReadData(size_t used);
302 // GetWriteBuffer returns a pointer to a buffer which is owned by the stream.
303 // The buffer has a capacity of buf_len bytes. null is returned if there is
304 // no buffer available, or if the method fails. The call may write data to
305 // the buffer, and then call ConsumeWriteBuffer with the number of bytes
306 // written. GetWriteBuffer does not require a matching call to
307 // ConsumeWriteData if no data is written. Write and
308 // ConsumeWriteData invalidate the buffer returned by GetWriteBuffer.
309 void* GetWriteBuffer(size_t* buf_len);
310 void ConsumeWriteBuffer(size_t used);
311
312 // Return the number of Write()-able bytes remaining before end-of-stream.
313 // Returns false if not known.
314 bool GetWriteRemaining(size_t* size) const;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200315
316 private:
317 // Helper method that implements ReadOffset. Caller must acquire a lock
318 // when calling this method.
danilchap3c6abd22017-09-06 05:46:29 -0700319 StreamResult ReadOffsetLocked(void* buffer,
320 size_t bytes,
321 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200322 size_t* bytes_read)
danilchap3c6abd22017-09-06 05:46:29 -0700323 RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200324
325 // Helper method that implements WriteOffset. Caller must acquire a lock
326 // when calling this method.
danilchap3c6abd22017-09-06 05:46:29 -0700327 StreamResult WriteOffsetLocked(const void* buffer,
328 size_t bytes,
329 size_t offset,
330 size_t* bytes_written)
331 RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200332
333 // keeps the opened/closed state of the stream
danilchap3c6abd22017-09-06 05:46:29 -0700334 StreamState state_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200335 // the allocated buffer
danilchap3c6abd22017-09-06 05:46:29 -0700336 std::unique_ptr<char[]> buffer_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200337 // size of the allocated buffer
danilchap3c6abd22017-09-06 05:46:29 -0700338 size_t buffer_length_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200339 // amount of readable data in the buffer
danilchap3c6abd22017-09-06 05:46:29 -0700340 size_t data_length_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200341 // offset to the readable data
danilchap3c6abd22017-09-06 05:46:29 -0700342 size_t read_position_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200343 // stream callbacks are dispatched on this thread
344 Thread* owner_;
345 // object lock
346 CriticalSection crit_;
347 RTC_DISALLOW_COPY_AND_ASSIGN(FifoBuffer);
348};
349
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200350} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000351
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200352#endif // RTC_BASE_STREAM_H_