blob: da6873222db7978fa204ca32a595598d61542392 [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
110 //
111 // OPTIONAL OPERATIONS
112 //
113 // Not all implementations will support the following operations. In general,
114 // a stream will only support an operation if it reasonably efficient to do
115 // so. For example, while a socket could buffer incoming data to support
116 // seeking, it will not do so. Instead, a buffering stream adapter should
117 // be used.
118 //
119 // Even though several of these operations are related, you should
Niels Möllere5aadba2018-09-20 15:39:18 +0200120 // always use whichever operation is most relevant.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200121 //
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200122 // The following four methods are used to avoid copying data multiple times.
123
124 // GetReadData returns a pointer to a buffer which is owned by the stream.
125 // The buffer contains data_len bytes. null is returned if no data is
126 // available, or if the method fails. If the caller processes the data, it
127 // must call ConsumeReadData with the number of processed bytes. GetReadData
128 // does not require a matching call to ConsumeReadData if the data is not
129 // processed. Read and ConsumeReadData invalidate the buffer returned by
130 // GetReadData.
131 virtual const void* GetReadData(size_t* data_len);
132 virtual void ConsumeReadData(size_t used) {}
133
134 // GetWriteBuffer returns a pointer to a buffer which is owned by the stream.
135 // The buffer has a capacity of buf_len bytes. null is returned if there is
136 // no buffer available, or if the method fails. The call may write data to
137 // the buffer, and then call ConsumeWriteBuffer with the number of bytes
138 // written. GetWriteBuffer does not require a matching call to
139 // ConsumeWriteData if no data is written. Write, ForceWrite, and
140 // ConsumeWriteData invalidate the buffer returned by GetWriteBuffer.
141 // TODO: Allow the caller to specify a minimum buffer size. If the specified
142 // amount of buffer is not yet available, return null and Signal SE_WRITE
143 // when it is available. If the requested amount is too large, return an
144 // error.
145 virtual void* GetWriteBuffer(size_t* buf_len);
146 virtual void ConsumeWriteBuffer(size_t used) {}
147
148 // Write data_len bytes found in data, circumventing any throttling which
149 // would could cause SR_BLOCK to be returned. Returns true if all the data
150 // was written. Otherwise, the method is unsupported, or an unrecoverable
151 // error occurred, and the error value is set. This method should be used
152 // sparingly to write critical data which should not be throttled. A stream
153 // which cannot circumvent its blocking constraints should not implement this
154 // method.
155 // NOTE: This interface is being considered experimentally at the moment. It
156 // would be used by JUDP and BandwidthStream as a way to circumvent certain
157 // soft limits in writing.
Yves Gerey665174f2018-06-19 15:03:05 +0200158 // virtual bool ForceWrite(const void* data, size_t data_len, int* error) {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200159 // if (error) *error = -1;
160 // return false;
161 //}
162
163 // Seek to a byte offset from the beginning of the stream. Returns false if
164 // the stream does not support seeking, or cannot seek to the specified
165 // position.
166 virtual bool SetPosition(size_t position);
167
168 // Get the byte offset of the current position from the start of the stream.
169 // Returns false if the position is not known.
170 virtual bool GetPosition(size_t* position) const;
171
172 // Get the byte length of the entire stream. Returns false if the length
173 // is not known.
174 virtual bool GetSize(size_t* size) const;
175
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200176 // Return the number of Write()-able bytes remaining before end-of-stream.
177 // Returns false if not known.
178 virtual bool GetWriteRemaining(size_t* size) const;
179
180 // Return true if flush is successful.
181 virtual bool Flush();
182
183 // Communicates the amount of data which will be written to the stream. The
184 // stream may choose to preallocate memory to accomodate this data. The
185 // stream may return false to indicate that there is not enough room (ie,
186 // Write will return SR_EOS/SR_ERROR at some point). Note that calling this
187 // function should not affect the existing state of data in the stream.
188 virtual bool ReserveSize(size_t size);
189
190 //
191 // CONVENIENCE METHODS
192 //
193 // These methods are implemented in terms of other methods, for convenience.
194 //
195
196 // Seek to the start of the stream.
197 inline bool Rewind() { return SetPosition(0); }
198
199 // WriteAll is a helper function which repeatedly calls Write until all the
200 // data is written, or something other than SR_SUCCESS is returned. Note that
201 // unlike Write, the argument 'written' is always set, and may be non-zero
202 // on results other than SR_SUCCESS. The remaining arguments have the
203 // same semantics as Write.
Yves Gerey665174f2018-06-19 15:03:05 +0200204 StreamResult WriteAll(const void* data,
205 size_t data_len,
206 size_t* written,
207 int* error);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200208
209 // Similar to ReadAll. Calls Read until buffer_len bytes have been read, or
210 // until a non-SR_SUCCESS result is returned. 'read' is always set.
Yves Gerey665174f2018-06-19 15:03:05 +0200211 StreamResult ReadAll(void* buffer,
212 size_t buffer_len,
213 size_t* read,
214 int* error);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200215
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200216 protected:
217 StreamInterface();
218
219 // MessageHandler Interface
220 void OnMessage(Message* msg) override;
221
222 private:
223 RTC_DISALLOW_COPY_AND_ASSIGN(StreamInterface);
224};
225
226///////////////////////////////////////////////////////////////////////////////
227// StreamAdapterInterface is a convenient base-class for adapting a stream.
228// By default, all operations are pass-through. Override the methods that you
229// require adaptation. Streams should really be upgraded to reference-counted.
230// In the meantime, use the owned flag to indicate whether the adapter should
231// own the adapted stream.
232///////////////////////////////////////////////////////////////////////////////
233
234class StreamAdapterInterface : public StreamInterface,
235 public sigslot::has_slots<> {
236 public:
237 explicit StreamAdapterInterface(StreamInterface* stream, bool owned = true);
238
239 // Core Stream Interface
240 StreamState GetState() const override;
241 StreamResult Read(void* buffer,
242 size_t buffer_len,
243 size_t* read,
244 int* error) override;
245 StreamResult Write(const void* data,
246 size_t data_len,
247 size_t* written,
248 int* error) override;
249 void Close() override;
250
251 // Optional Stream Interface
252 /* Note: Many stream adapters were implemented prior to this Read/Write
253 interface. Therefore, a simple pass through of data in those cases may
254 be broken. At a later time, we should do a once-over pass of all
255 adapters, and make them compliant with these interfaces, after which this
256 code can be uncommented.
257 virtual const void* GetReadData(size_t* data_len) {
258 return stream_->GetReadData(data_len);
259 }
260 virtual void ConsumeReadData(size_t used) {
261 stream_->ConsumeReadData(used);
262 }
263
264 virtual void* GetWriteBuffer(size_t* buf_len) {
265 return stream_->GetWriteBuffer(buf_len);
266 }
267 virtual void ConsumeWriteBuffer(size_t used) {
268 stream_->ConsumeWriteBuffer(used);
269 }
270 */
271
272 /* Note: This interface is currently undergoing evaluation.
273 virtual bool ForceWrite(const void* data, size_t data_len, int* error) {
274 return stream_->ForceWrite(data, data_len, error);
275 }
276 */
277
278 bool SetPosition(size_t position) override;
279 bool GetPosition(size_t* position) const override;
280 bool GetSize(size_t* size) const override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200281 bool GetWriteRemaining(size_t* size) const override;
282 bool ReserveSize(size_t size) override;
283 bool Flush() override;
284
285 void Attach(StreamInterface* stream, bool owned = true);
286 StreamInterface* Detach();
287
288 protected:
289 ~StreamAdapterInterface() override;
290
291 // Note that the adapter presents itself as the origin of the stream events,
292 // since users of the adapter may not recognize the adapted object.
293 virtual void OnEvent(StreamInterface* stream, int events, int err);
294 StreamInterface* stream() { return stream_; }
295
296 private:
297 StreamInterface* stream_;
298 bool owned_;
299 RTC_DISALLOW_COPY_AND_ASSIGN(StreamAdapterInterface);
300};
301
302///////////////////////////////////////////////////////////////////////////////
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200303// FileStream is a simple implementation of a StreamInterface, which does not
304// support asynchronous notification.
305///////////////////////////////////////////////////////////////////////////////
306
307class FileStream : public StreamInterface {
308 public:
309 FileStream();
310 ~FileStream() override;
311
312 // The semantics of filename and mode are the same as stdio's fopen
313 virtual bool Open(const std::string& filename, const char* mode, int* error);
Yves Gerey665174f2018-06-19 15:03:05 +0200314 virtual bool OpenShare(const std::string& filename,
315 const char* mode,
316 int shflag,
317 int* error);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200318
319 // By default, reads and writes are buffered for efficiency. Disabling
320 // buffering causes writes to block until the bytes on disk are updated.
321 virtual bool DisableBuffering();
322
323 StreamState GetState() const override;
324 StreamResult Read(void* buffer,
325 size_t buffer_len,
326 size_t* read,
327 int* error) override;
328 StreamResult Write(const void* data,
329 size_t data_len,
330 size_t* written,
331 int* error) override;
332 void Close() override;
333 bool SetPosition(size_t position) override;
334 bool GetPosition(size_t* position) const override;
335 bool GetSize(size_t* size) const override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200336 bool ReserveSize(size_t size) override;
337
338 bool Flush() override;
339
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200340 protected:
341 virtual void DoClose();
342
343 FILE* file_;
344
345 private:
346 RTC_DISALLOW_COPY_AND_ASSIGN(FileStream);
347};
348
349///////////////////////////////////////////////////////////////////////////////
350// MemoryStream is a simple implementation of a StreamInterface over in-memory
351// data. Data is read and written at the current seek position. Reads return
352// end-of-stream when they reach the end of data. Writes actually extend the
353// end of data mark.
354///////////////////////////////////////////////////////////////////////////////
355
356class MemoryStreamBase : public StreamInterface {
357 public:
358 StreamState GetState() const override;
359 StreamResult Read(void* buffer,
360 size_t bytes,
361 size_t* bytes_read,
362 int* error) override;
363 StreamResult Write(const void* buffer,
364 size_t bytes,
365 size_t* bytes_written,
366 int* error) override;
367 void Close() override;
368 bool SetPosition(size_t position) override;
369 bool GetPosition(size_t* position) const override;
370 bool GetSize(size_t* size) const override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200371 bool ReserveSize(size_t size) override;
372
373 char* GetBuffer() { return buffer_; }
374 const char* GetBuffer() const { return buffer_; }
375
376 protected:
377 MemoryStreamBase();
378
379 virtual StreamResult DoReserve(size_t size, int* error);
380
381 // Invariant: 0 <= seek_position <= data_length_ <= buffer_length_
382 char* buffer_;
383 size_t buffer_length_;
384 size_t data_length_;
385 size_t seek_position_;
386
387 private:
388 RTC_DISALLOW_COPY_AND_ASSIGN(MemoryStreamBase);
389};
390
391// MemoryStream dynamically resizes to accomodate written data.
392
393class MemoryStream : public MemoryStreamBase {
394 public:
395 MemoryStream();
396 explicit MemoryStream(const char* data); // Calls SetData(data, strlen(data))
397 MemoryStream(const void* data, size_t length); // Calls SetData(data, length)
398 ~MemoryStream() override;
399
400 void SetData(const void* data, size_t length);
401
402 protected:
403 StreamResult DoReserve(size_t size, int* error) override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200404};
405
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200406// FifoBuffer allows for efficient, thread-safe buffering of data between
407// writer and reader. As the data can wrap around the end of the buffer,
408// MemoryStreamBase can't help us here.
409
410class FifoBuffer : public StreamInterface {
411 public:
412 // Creates a FIFO buffer with the specified capacity.
413 explicit FifoBuffer(size_t length);
414 // Creates a FIFO buffer with the specified capacity and owner
415 FifoBuffer(size_t length, Thread* owner);
416 ~FifoBuffer() override;
417 // Gets the amount of data currently readable from the buffer.
418 bool GetBuffered(size_t* data_len) const;
419 // Resizes the buffer to the specified capacity. Fails if data_length_ > size
420 bool SetCapacity(size_t length);
421
422 // Read into |buffer| with an offset from the current read position, offset
423 // is specified in number of bytes.
424 // This method doesn't adjust read position nor the number of available
425 // bytes, user has to call ConsumeReadData() to do this.
Yves Gerey665174f2018-06-19 15:03:05 +0200426 StreamResult ReadOffset(void* buffer,
427 size_t bytes,
428 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200429 size_t* bytes_read);
430
431 // Write |buffer| with an offset from the current write position, offset is
432 // specified in number of bytes.
433 // This method doesn't adjust the number of buffered bytes, user has to call
434 // ConsumeWriteBuffer() to do this.
Yves Gerey665174f2018-06-19 15:03:05 +0200435 StreamResult WriteOffset(const void* buffer,
436 size_t bytes,
437 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200438 size_t* bytes_written);
439
440 // StreamInterface methods
441 StreamState GetState() const override;
442 StreamResult Read(void* buffer,
443 size_t bytes,
444 size_t* bytes_read,
445 int* error) override;
446 StreamResult Write(const void* buffer,
447 size_t bytes,
448 size_t* bytes_written,
449 int* error) override;
450 void Close() override;
451 const void* GetReadData(size_t* data_len) override;
452 void ConsumeReadData(size_t used) override;
453 void* GetWriteBuffer(size_t* buf_len) override;
454 void ConsumeWriteBuffer(size_t used) override;
455 bool GetWriteRemaining(size_t* size) const override;
456
457 private:
458 // Helper method that implements ReadOffset. Caller must acquire a lock
459 // when calling this method.
danilchap3c6abd22017-09-06 05:46:29 -0700460 StreamResult ReadOffsetLocked(void* buffer,
461 size_t bytes,
462 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200463 size_t* bytes_read)
danilchap3c6abd22017-09-06 05:46:29 -0700464 RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200465
466 // Helper method that implements WriteOffset. Caller must acquire a lock
467 // when calling this method.
danilchap3c6abd22017-09-06 05:46:29 -0700468 StreamResult WriteOffsetLocked(const void* buffer,
469 size_t bytes,
470 size_t offset,
471 size_t* bytes_written)
472 RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200473
474 // keeps the opened/closed state of the stream
danilchap3c6abd22017-09-06 05:46:29 -0700475 StreamState state_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200476 // the allocated buffer
danilchap3c6abd22017-09-06 05:46:29 -0700477 std::unique_ptr<char[]> buffer_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200478 // size of the allocated buffer
danilchap3c6abd22017-09-06 05:46:29 -0700479 size_t buffer_length_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200480 // amount of readable data in the buffer
danilchap3c6abd22017-09-06 05:46:29 -0700481 size_t data_length_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200482 // offset to the readable data
danilchap3c6abd22017-09-06 05:46:29 -0700483 size_t read_position_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200484 // stream callbacks are dispatched on this thread
485 Thread* owner_;
486 // object lock
487 CriticalSection crit_;
488 RTC_DISALLOW_COPY_AND_ASSIGN(FifoBuffer);
489};
490
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200491} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000492
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200493#endif // RTC_BASE_STREAM_H_