blob: 2e72ce3a186c5f47890b461e03bb1e07f5e1074b [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"
19#include "rtc_base/constructormagic.h"
20#include "rtc_base/criticalsection.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "rtc_base/messagehandler.h"
22#include "rtc_base/messagequeue.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
119 // Get the byte length of the entire stream. Returns false if the length
120 // is not known.
121 virtual bool GetSize(size_t* size) const;
122
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200123 // Return true if flush is successful.
124 virtual bool Flush();
125
126 // Communicates the amount of data which will be written to the stream. The
127 // stream may choose to preallocate memory to accomodate this data. The
128 // stream may return false to indicate that there is not enough room (ie,
129 // Write will return SR_EOS/SR_ERROR at some point). Note that calling this
130 // function should not affect the existing state of data in the stream.
131 virtual bool ReserveSize(size_t size);
132
133 //
134 // CONVENIENCE METHODS
135 //
136 // These methods are implemented in terms of other methods, for convenience.
137 //
138
139 // Seek to the start of the stream.
140 inline bool Rewind() { return SetPosition(0); }
141
142 // WriteAll is a helper function which repeatedly calls Write until all the
143 // data is written, or something other than SR_SUCCESS is returned. Note that
144 // unlike Write, the argument 'written' is always set, and may be non-zero
145 // on results other than SR_SUCCESS. The remaining arguments have the
146 // same semantics as Write.
Yves Gerey665174f2018-06-19 15:03:05 +0200147 StreamResult WriteAll(const void* data,
148 size_t data_len,
149 size_t* written,
150 int* error);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200151
152 // Similar to ReadAll. Calls Read until buffer_len bytes have been read, or
153 // until a non-SR_SUCCESS result is returned. 'read' is always set.
Yves Gerey665174f2018-06-19 15:03:05 +0200154 StreamResult ReadAll(void* buffer,
155 size_t buffer_len,
156 size_t* read,
157 int* error);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200158
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200159 protected:
160 StreamInterface();
161
162 // MessageHandler Interface
163 void OnMessage(Message* msg) override;
164
165 private:
166 RTC_DISALLOW_COPY_AND_ASSIGN(StreamInterface);
167};
168
169///////////////////////////////////////////////////////////////////////////////
170// StreamAdapterInterface is a convenient base-class for adapting a stream.
171// By default, all operations are pass-through. Override the methods that you
172// require adaptation. Streams should really be upgraded to reference-counted.
173// In the meantime, use the owned flag to indicate whether the adapter should
174// own the adapted stream.
175///////////////////////////////////////////////////////////////////////////////
176
177class StreamAdapterInterface : public StreamInterface,
178 public sigslot::has_slots<> {
179 public:
180 explicit StreamAdapterInterface(StreamInterface* stream, bool owned = true);
181
182 // Core Stream Interface
183 StreamState GetState() const override;
184 StreamResult Read(void* buffer,
185 size_t buffer_len,
186 size_t* read,
187 int* error) override;
188 StreamResult Write(const void* data,
189 size_t data_len,
190 size_t* written,
191 int* error) override;
192 void Close() override;
193
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200194 bool SetPosition(size_t position) override;
195 bool GetPosition(size_t* position) const override;
196 bool GetSize(size_t* size) const override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200197 bool ReserveSize(size_t size) override;
198 bool Flush() override;
199
200 void Attach(StreamInterface* stream, bool owned = true);
201 StreamInterface* Detach();
202
203 protected:
204 ~StreamAdapterInterface() override;
205
206 // Note that the adapter presents itself as the origin of the stream events,
207 // since users of the adapter may not recognize the adapted object.
208 virtual void OnEvent(StreamInterface* stream, int events, int err);
209 StreamInterface* stream() { return stream_; }
210
211 private:
212 StreamInterface* stream_;
213 bool owned_;
214 RTC_DISALLOW_COPY_AND_ASSIGN(StreamAdapterInterface);
215};
216
217///////////////////////////////////////////////////////////////////////////////
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200218// FileStream is a simple implementation of a StreamInterface, which does not
219// support asynchronous notification.
220///////////////////////////////////////////////////////////////////////////////
221
222class FileStream : public StreamInterface {
223 public:
224 FileStream();
225 ~FileStream() override;
226
227 // The semantics of filename and mode are the same as stdio's fopen
228 virtual bool Open(const std::string& filename, const char* mode, int* error);
Yves Gerey665174f2018-06-19 15:03:05 +0200229 virtual bool OpenShare(const std::string& filename,
230 const char* mode,
231 int shflag,
232 int* error);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200233
234 // By default, reads and writes are buffered for efficiency. Disabling
235 // buffering causes writes to block until the bytes on disk are updated.
236 virtual bool DisableBuffering();
237
238 StreamState GetState() const override;
239 StreamResult Read(void* buffer,
240 size_t buffer_len,
241 size_t* read,
242 int* error) override;
243 StreamResult Write(const void* data,
244 size_t data_len,
245 size_t* written,
246 int* error) override;
247 void Close() override;
248 bool SetPosition(size_t position) override;
249 bool GetPosition(size_t* position) const override;
250 bool GetSize(size_t* size) const override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200251 bool ReserveSize(size_t size) override;
252
253 bool Flush() override;
254
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200255 protected:
256 virtual void DoClose();
257
258 FILE* file_;
259
260 private:
261 RTC_DISALLOW_COPY_AND_ASSIGN(FileStream);
262};
263
264///////////////////////////////////////////////////////////////////////////////
265// MemoryStream is a simple implementation of a StreamInterface over in-memory
266// data. Data is read and written at the current seek position. Reads return
267// end-of-stream when they reach the end of data. Writes actually extend the
268// end of data mark.
269///////////////////////////////////////////////////////////////////////////////
270
271class MemoryStreamBase : public StreamInterface {
272 public:
273 StreamState GetState() const override;
274 StreamResult Read(void* buffer,
275 size_t bytes,
276 size_t* bytes_read,
277 int* error) override;
278 StreamResult Write(const void* buffer,
279 size_t bytes,
280 size_t* bytes_written,
281 int* error) override;
282 void Close() override;
283 bool SetPosition(size_t position) override;
284 bool GetPosition(size_t* position) const override;
285 bool GetSize(size_t* size) const override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200286 bool ReserveSize(size_t size) override;
287
288 char* GetBuffer() { return buffer_; }
289 const char* GetBuffer() const { return buffer_; }
290
291 protected:
292 MemoryStreamBase();
293
294 virtual StreamResult DoReserve(size_t size, int* error);
295
296 // Invariant: 0 <= seek_position <= data_length_ <= buffer_length_
297 char* buffer_;
298 size_t buffer_length_;
299 size_t data_length_;
300 size_t seek_position_;
301
302 private:
303 RTC_DISALLOW_COPY_AND_ASSIGN(MemoryStreamBase);
304};
305
306// MemoryStream dynamically resizes to accomodate written data.
307
308class MemoryStream : public MemoryStreamBase {
309 public:
310 MemoryStream();
311 explicit MemoryStream(const char* data); // Calls SetData(data, strlen(data))
312 MemoryStream(const void* data, size_t length); // Calls SetData(data, length)
313 ~MemoryStream() override;
314
315 void SetData(const void* data, size_t length);
316
317 protected:
318 StreamResult DoReserve(size_t size, int* error) override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200319};
320
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200321// FifoBuffer allows for efficient, thread-safe buffering of data between
322// writer and reader. As the data can wrap around the end of the buffer,
323// MemoryStreamBase can't help us here.
324
Niels Möllera8fa2d02018-10-31 10:19:50 +0100325class FifoBuffer final : public StreamInterface {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200326 public:
327 // Creates a FIFO buffer with the specified capacity.
328 explicit FifoBuffer(size_t length);
329 // Creates a FIFO buffer with the specified capacity and owner
330 FifoBuffer(size_t length, Thread* owner);
331 ~FifoBuffer() override;
332 // Gets the amount of data currently readable from the buffer.
333 bool GetBuffered(size_t* data_len) const;
334 // Resizes the buffer to the specified capacity. Fails if data_length_ > size
335 bool SetCapacity(size_t length);
336
337 // Read into |buffer| with an offset from the current read position, offset
338 // is specified in number of bytes.
339 // This method doesn't adjust read position nor the number of available
340 // bytes, user has to call ConsumeReadData() to do this.
Yves Gerey665174f2018-06-19 15:03:05 +0200341 StreamResult ReadOffset(void* buffer,
342 size_t bytes,
343 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200344 size_t* bytes_read);
345
346 // Write |buffer| with an offset from the current write position, offset is
347 // specified in number of bytes.
348 // This method doesn't adjust the number of buffered bytes, user has to call
349 // ConsumeWriteBuffer() to do this.
Yves Gerey665174f2018-06-19 15:03:05 +0200350 StreamResult WriteOffset(const void* buffer,
351 size_t bytes,
352 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200353 size_t* bytes_written);
354
355 // StreamInterface methods
356 StreamState GetState() const override;
357 StreamResult Read(void* buffer,
358 size_t bytes,
359 size_t* bytes_read,
360 int* error) override;
361 StreamResult Write(const void* buffer,
362 size_t bytes,
363 size_t* bytes_written,
364 int* error) override;
365 void Close() override;
Niels Möllera8fa2d02018-10-31 10:19:50 +0100366 // GetReadData returns a pointer to a buffer which is owned by the stream.
367 // The buffer contains data_len bytes. null is returned if no data is
368 // available, or if the method fails. If the caller processes the data, it
369 // must call ConsumeReadData with the number of processed bytes. GetReadData
370 // does not require a matching call to ConsumeReadData if the data is not
371 // processed. Read and ConsumeReadData invalidate the buffer returned by
372 // GetReadData.
373 const void* GetReadData(size_t* data_len);
374 void ConsumeReadData(size_t used);
375 // GetWriteBuffer returns a pointer to a buffer which is owned by the stream.
376 // The buffer has a capacity of buf_len bytes. null is returned if there is
377 // no buffer available, or if the method fails. The call may write data to
378 // the buffer, and then call ConsumeWriteBuffer with the number of bytes
379 // written. GetWriteBuffer does not require a matching call to
380 // ConsumeWriteData if no data is written. Write and
381 // ConsumeWriteData invalidate the buffer returned by GetWriteBuffer.
382 void* GetWriteBuffer(size_t* buf_len);
383 void ConsumeWriteBuffer(size_t used);
384
385 // Return the number of Write()-able bytes remaining before end-of-stream.
386 // Returns false if not known.
387 bool GetWriteRemaining(size_t* size) const;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200388
389 private:
390 // Helper method that implements ReadOffset. Caller must acquire a lock
391 // when calling this method.
danilchap3c6abd22017-09-06 05:46:29 -0700392 StreamResult ReadOffsetLocked(void* buffer,
393 size_t bytes,
394 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200395 size_t* bytes_read)
danilchap3c6abd22017-09-06 05:46:29 -0700396 RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200397
398 // Helper method that implements WriteOffset. Caller must acquire a lock
399 // when calling this method.
danilchap3c6abd22017-09-06 05:46:29 -0700400 StreamResult WriteOffsetLocked(const void* buffer,
401 size_t bytes,
402 size_t offset,
403 size_t* bytes_written)
404 RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200405
406 // keeps the opened/closed state of the stream
danilchap3c6abd22017-09-06 05:46:29 -0700407 StreamState state_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200408 // the allocated buffer
danilchap3c6abd22017-09-06 05:46:29 -0700409 std::unique_ptr<char[]> buffer_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200410 // size of the allocated buffer
danilchap3c6abd22017-09-06 05:46:29 -0700411 size_t buffer_length_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200412 // amount of readable data in the buffer
danilchap3c6abd22017-09-06 05:46:29 -0700413 size_t data_length_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200414 // offset to the readable data
danilchap3c6abd22017-09-06 05:46:29 -0700415 size_t read_position_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200416 // stream callbacks are dispatched on this thread
417 Thread* owner_;
418 // object lock
419 CriticalSection crit_;
420 RTC_DISALLOW_COPY_AND_ASSIGN(FifoBuffer);
421};
422
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200423} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000424
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200425#endif // RTC_BASE_STREAM_H_