blob: a14d48e05d7dc4f6863b7ba8084573792e00bb28 [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"
21#include "rtc_base/logging.h"
22#include "rtc_base/messagehandler.h"
23#include "rtc_base/messagequeue.h"
Artem Titove41c4332018-07-25 15:04:28 +020024#include "rtc_base/third_party/sigslot/sigslot.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020025
26namespace rtc {
27
28///////////////////////////////////////////////////////////////////////////////
29// StreamInterface is a generic asynchronous stream interface, supporting read,
30// write, and close operations, and asynchronous signalling of state changes.
31// The interface is designed with file, memory, and socket implementations in
32// mind. Some implementations offer extended operations, such as seeking.
33///////////////////////////////////////////////////////////////////////////////
34
35// The following enumerations are declared outside of the StreamInterface
36// class for brevity in use.
37
38// The SS_OPENING state indicates that the stream will signal open or closed
39// in the future.
40enum StreamState { SS_CLOSED, SS_OPENING, SS_OPEN };
41
42// Stream read/write methods return this value to indicate various success
43// and failure conditions described below.
44enum StreamResult { SR_ERROR, SR_SUCCESS, SR_BLOCK, SR_EOS };
45
46// StreamEvents are used to asynchronously signal state transitionss. The flags
47// may be combined.
48// SE_OPEN: The stream has transitioned to the SS_OPEN state
49// SE_CLOSE: The stream has transitioned to the SS_CLOSED state
50// SE_READ: Data is available, so Read is likely to not return SR_BLOCK
51// SE_WRITE: Data can be written, so Write is likely to not return SR_BLOCK
52enum StreamEvent { SE_OPEN = 1, SE_READ = 2, SE_WRITE = 4, SE_CLOSE = 8 };
53
54class Thread;
55
56struct StreamEventData : public MessageData {
57 int events, error;
Yves Gerey665174f2018-06-19 15:03:05 +020058 StreamEventData(int ev, int er) : events(ev), error(er) {}
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020059};
60
61class StreamInterface : public MessageHandler {
62 public:
Yves Gerey665174f2018-06-19 15:03:05 +020063 enum { MSG_POST_EVENT = 0xF1F1, MSG_MAX = MSG_POST_EVENT };
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020064
65 ~StreamInterface() override;
66
67 virtual StreamState GetState() const = 0;
68
69 // Read attempts to fill buffer of size buffer_len. Write attempts to send
70 // data_len bytes stored in data. The variables read and write are set only
71 // on SR_SUCCESS (see below). Likewise, error is only set on SR_ERROR.
72 // Read and Write return a value indicating:
73 // SR_ERROR: an error occurred, which is returned in a non-null error
74 // argument. Interpretation of the error requires knowledge of the
75 // stream's concrete type, which limits its usefulness.
76 // SR_SUCCESS: some number of bytes were successfully written, which is
77 // returned in a non-null read/write argument.
78 // SR_BLOCK: the stream is in non-blocking mode, and the operation would
79 // block, or the stream is in SS_OPENING state.
80 // SR_EOS: the end-of-stream has been reached, or the stream is in the
81 // SS_CLOSED state.
Yves Gerey665174f2018-06-19 15:03:05 +020082 virtual StreamResult Read(void* buffer,
83 size_t buffer_len,
84 size_t* read,
85 int* error) = 0;
86 virtual StreamResult Write(const void* data,
87 size_t data_len,
88 size_t* written,
89 int* error) = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020090 // Attempt to transition to the SS_CLOSED state. SE_CLOSE will not be
91 // signalled as a result of this call.
92 virtual void Close() = 0;
93
94 // Streams may signal one or more StreamEvents to indicate state changes.
95 // The first argument identifies the stream on which the state change occured.
96 // The second argument is a bit-wise combination of StreamEvents.
97 // If SE_CLOSE is signalled, then the third argument is the associated error
98 // code. Otherwise, the value is undefined.
99 // Note: Not all streams will support asynchronous event signalling. However,
100 // SS_OPENING and SR_BLOCK returned from stream member functions imply that
101 // certain events will be raised in the future.
102 sigslot::signal3<StreamInterface*, int, int> SignalEvent;
103
104 // Like calling SignalEvent, but posts a message to the specified thread,
105 // which will call SignalEvent. This helps unroll the stack and prevent
106 // re-entrancy.
107 void PostEvent(Thread* t, int events, int err);
108 // Like the aforementioned method, but posts to the current thread.
109 void PostEvent(int events, int err);
110
111 //
112 // OPTIONAL OPERATIONS
113 //
114 // Not all implementations will support the following operations. In general,
115 // a stream will only support an operation if it reasonably efficient to do
116 // so. For example, while a socket could buffer incoming data to support
117 // seeking, it will not do so. Instead, a buffering stream adapter should
118 // be used.
119 //
120 // Even though several of these operations are related, you should
121 // always use whichever operation is most relevant. For example, you may
122 // be tempted to use GetSize() and GetPosition() to deduce the result of
123 // GetAvailable(). However, a stream which is read-once may support the
124 // latter operation but not the former.
125 //
126
127 // The following four methods are used to avoid copying data multiple times.
128
129 // GetReadData returns a pointer to a buffer which is owned by the stream.
130 // The buffer contains data_len bytes. null is returned if no data is
131 // available, or if the method fails. If the caller processes the data, it
132 // must call ConsumeReadData with the number of processed bytes. GetReadData
133 // does not require a matching call to ConsumeReadData if the data is not
134 // processed. Read and ConsumeReadData invalidate the buffer returned by
135 // GetReadData.
136 virtual const void* GetReadData(size_t* data_len);
137 virtual void ConsumeReadData(size_t used) {}
138
139 // GetWriteBuffer returns a pointer to a buffer which is owned by the stream.
140 // The buffer has a capacity of buf_len bytes. null is returned if there is
141 // no buffer available, or if the method fails. The call may write data to
142 // the buffer, and then call ConsumeWriteBuffer with the number of bytes
143 // written. GetWriteBuffer does not require a matching call to
144 // ConsumeWriteData if no data is written. Write, ForceWrite, and
145 // ConsumeWriteData invalidate the buffer returned by GetWriteBuffer.
146 // TODO: Allow the caller to specify a minimum buffer size. If the specified
147 // amount of buffer is not yet available, return null and Signal SE_WRITE
148 // when it is available. If the requested amount is too large, return an
149 // error.
150 virtual void* GetWriteBuffer(size_t* buf_len);
151 virtual void ConsumeWriteBuffer(size_t used) {}
152
153 // Write data_len bytes found in data, circumventing any throttling which
154 // would could cause SR_BLOCK to be returned. Returns true if all the data
155 // was written. Otherwise, the method is unsupported, or an unrecoverable
156 // error occurred, and the error value is set. This method should be used
157 // sparingly to write critical data which should not be throttled. A stream
158 // which cannot circumvent its blocking constraints should not implement this
159 // method.
160 // NOTE: This interface is being considered experimentally at the moment. It
161 // would be used by JUDP and BandwidthStream as a way to circumvent certain
162 // soft limits in writing.
Yves Gerey665174f2018-06-19 15:03:05 +0200163 // virtual bool ForceWrite(const void* data, size_t data_len, int* error) {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200164 // if (error) *error = -1;
165 // return false;
166 //}
167
168 // Seek to a byte offset from the beginning of the stream. Returns false if
169 // the stream does not support seeking, or cannot seek to the specified
170 // position.
171 virtual bool SetPosition(size_t position);
172
173 // Get the byte offset of the current position from the start of the stream.
174 // Returns false if the position is not known.
175 virtual bool GetPosition(size_t* position) const;
176
177 // Get the byte length of the entire stream. Returns false if the length
178 // is not known.
179 virtual bool GetSize(size_t* size) const;
180
181 // Return the number of Read()-able bytes remaining before end-of-stream.
182 // Returns false if not known.
183 virtual bool GetAvailable(size_t* size) const;
184
185 // Return the number of Write()-able bytes remaining before end-of-stream.
186 // Returns false if not known.
187 virtual bool GetWriteRemaining(size_t* size) const;
188
189 // Return true if flush is successful.
190 virtual bool Flush();
191
192 // Communicates the amount of data which will be written to the stream. The
193 // stream may choose to preallocate memory to accomodate this data. The
194 // stream may return false to indicate that there is not enough room (ie,
195 // Write will return SR_EOS/SR_ERROR at some point). Note that calling this
196 // function should not affect the existing state of data in the stream.
197 virtual bool ReserveSize(size_t size);
198
199 //
200 // CONVENIENCE METHODS
201 //
202 // These methods are implemented in terms of other methods, for convenience.
203 //
204
205 // Seek to the start of the stream.
206 inline bool Rewind() { return SetPosition(0); }
207
208 // WriteAll is a helper function which repeatedly calls Write until all the
209 // data is written, or something other than SR_SUCCESS is returned. Note that
210 // unlike Write, the argument 'written' is always set, and may be non-zero
211 // on results other than SR_SUCCESS. The remaining arguments have the
212 // same semantics as Write.
Yves Gerey665174f2018-06-19 15:03:05 +0200213 StreamResult WriteAll(const void* data,
214 size_t data_len,
215 size_t* written,
216 int* error);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200217
218 // Similar to ReadAll. Calls Read until buffer_len bytes have been read, or
219 // until a non-SR_SUCCESS result is returned. 'read' is always set.
Yves Gerey665174f2018-06-19 15:03:05 +0200220 StreamResult ReadAll(void* buffer,
221 size_t buffer_len,
222 size_t* read,
223 int* error);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200224
225 // ReadLine is a helper function which repeatedly calls Read until it hits
226 // the end-of-line character, or something other than SR_SUCCESS.
227 // TODO: this is too inefficient to keep here. Break this out into a buffered
228 // readline object or adapter
229 StreamResult ReadLine(std::string* line);
230
231 protected:
232 StreamInterface();
233
234 // MessageHandler Interface
235 void OnMessage(Message* msg) override;
236
237 private:
238 RTC_DISALLOW_COPY_AND_ASSIGN(StreamInterface);
239};
240
241///////////////////////////////////////////////////////////////////////////////
242// StreamAdapterInterface is a convenient base-class for adapting a stream.
243// By default, all operations are pass-through. Override the methods that you
244// require adaptation. Streams should really be upgraded to reference-counted.
245// In the meantime, use the owned flag to indicate whether the adapter should
246// own the adapted stream.
247///////////////////////////////////////////////////////////////////////////////
248
249class StreamAdapterInterface : public StreamInterface,
250 public sigslot::has_slots<> {
251 public:
252 explicit StreamAdapterInterface(StreamInterface* stream, bool owned = true);
253
254 // Core Stream Interface
255 StreamState GetState() const override;
256 StreamResult Read(void* buffer,
257 size_t buffer_len,
258 size_t* read,
259 int* error) override;
260 StreamResult Write(const void* data,
261 size_t data_len,
262 size_t* written,
263 int* error) override;
264 void Close() override;
265
266 // Optional Stream Interface
267 /* Note: Many stream adapters were implemented prior to this Read/Write
268 interface. Therefore, a simple pass through of data in those cases may
269 be broken. At a later time, we should do a once-over pass of all
270 adapters, and make them compliant with these interfaces, after which this
271 code can be uncommented.
272 virtual const void* GetReadData(size_t* data_len) {
273 return stream_->GetReadData(data_len);
274 }
275 virtual void ConsumeReadData(size_t used) {
276 stream_->ConsumeReadData(used);
277 }
278
279 virtual void* GetWriteBuffer(size_t* buf_len) {
280 return stream_->GetWriteBuffer(buf_len);
281 }
282 virtual void ConsumeWriteBuffer(size_t used) {
283 stream_->ConsumeWriteBuffer(used);
284 }
285 */
286
287 /* Note: This interface is currently undergoing evaluation.
288 virtual bool ForceWrite(const void* data, size_t data_len, int* error) {
289 return stream_->ForceWrite(data, data_len, error);
290 }
291 */
292
293 bool SetPosition(size_t position) override;
294 bool GetPosition(size_t* position) const override;
295 bool GetSize(size_t* size) const override;
296 bool GetAvailable(size_t* size) const override;
297 bool GetWriteRemaining(size_t* size) const override;
298 bool ReserveSize(size_t size) override;
299 bool Flush() override;
300
301 void Attach(StreamInterface* stream, bool owned = true);
302 StreamInterface* Detach();
303
304 protected:
305 ~StreamAdapterInterface() override;
306
307 // Note that the adapter presents itself as the origin of the stream events,
308 // since users of the adapter may not recognize the adapted object.
309 virtual void OnEvent(StreamInterface* stream, int events, int err);
310 StreamInterface* stream() { return stream_; }
311
312 private:
313 StreamInterface* stream_;
314 bool owned_;
315 RTC_DISALLOW_COPY_AND_ASSIGN(StreamAdapterInterface);
316};
317
318///////////////////////////////////////////////////////////////////////////////
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200319// FileStream is a simple implementation of a StreamInterface, which does not
320// support asynchronous notification.
321///////////////////////////////////////////////////////////////////////////////
322
323class FileStream : public StreamInterface {
324 public:
325 FileStream();
326 ~FileStream() override;
327
328 // The semantics of filename and mode are the same as stdio's fopen
329 virtual bool Open(const std::string& filename, const char* mode, int* error);
Yves Gerey665174f2018-06-19 15:03:05 +0200330 virtual bool OpenShare(const std::string& filename,
331 const char* mode,
332 int shflag,
333 int* error);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200334
335 // By default, reads and writes are buffered for efficiency. Disabling
336 // buffering causes writes to block until the bytes on disk are updated.
337 virtual bool DisableBuffering();
338
339 StreamState GetState() const override;
340 StreamResult Read(void* buffer,
341 size_t buffer_len,
342 size_t* read,
343 int* error) override;
344 StreamResult Write(const void* data,
345 size_t data_len,
346 size_t* written,
347 int* error) override;
348 void Close() override;
349 bool SetPosition(size_t position) override;
350 bool GetPosition(size_t* position) const override;
351 bool GetSize(size_t* size) const override;
352 bool GetAvailable(size_t* size) const override;
353 bool ReserveSize(size_t size) override;
354
355 bool Flush() override;
356
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200357 protected:
358 virtual void DoClose();
359
360 FILE* file_;
361
362 private:
363 RTC_DISALLOW_COPY_AND_ASSIGN(FileStream);
364};
365
366///////////////////////////////////////////////////////////////////////////////
367// MemoryStream is a simple implementation of a StreamInterface over in-memory
368// data. Data is read and written at the current seek position. Reads return
369// end-of-stream when they reach the end of data. Writes actually extend the
370// end of data mark.
371///////////////////////////////////////////////////////////////////////////////
372
373class MemoryStreamBase : public StreamInterface {
374 public:
375 StreamState GetState() const override;
376 StreamResult Read(void* buffer,
377 size_t bytes,
378 size_t* bytes_read,
379 int* error) override;
380 StreamResult Write(const void* buffer,
381 size_t bytes,
382 size_t* bytes_written,
383 int* error) override;
384 void Close() override;
385 bool SetPosition(size_t position) override;
386 bool GetPosition(size_t* position) const override;
387 bool GetSize(size_t* size) const override;
388 bool GetAvailable(size_t* size) const override;
389 bool ReserveSize(size_t size) override;
390
391 char* GetBuffer() { return buffer_; }
392 const char* GetBuffer() const { return buffer_; }
393
394 protected:
395 MemoryStreamBase();
396
397 virtual StreamResult DoReserve(size_t size, int* error);
398
399 // Invariant: 0 <= seek_position <= data_length_ <= buffer_length_
400 char* buffer_;
401 size_t buffer_length_;
402 size_t data_length_;
403 size_t seek_position_;
404
405 private:
406 RTC_DISALLOW_COPY_AND_ASSIGN(MemoryStreamBase);
407};
408
409// MemoryStream dynamically resizes to accomodate written data.
410
411class MemoryStream : public MemoryStreamBase {
412 public:
413 MemoryStream();
414 explicit MemoryStream(const char* data); // Calls SetData(data, strlen(data))
415 MemoryStream(const void* data, size_t length); // Calls SetData(data, length)
416 ~MemoryStream() override;
417
418 void SetData(const void* data, size_t length);
419
420 protected:
421 StreamResult DoReserve(size_t size, int* error) override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200422};
423
424// ExternalMemoryStream adapts an external memory buffer, so writes which would
425// extend past the end of the buffer will return end-of-stream.
426
427class ExternalMemoryStream : public MemoryStreamBase {
428 public:
429 ExternalMemoryStream();
430 ExternalMemoryStream(void* data, size_t length);
431 ~ExternalMemoryStream() override;
432
433 void SetData(void* data, size_t length);
434};
435
436// FifoBuffer allows for efficient, thread-safe buffering of data between
437// writer and reader. As the data can wrap around the end of the buffer,
438// MemoryStreamBase can't help us here.
439
440class FifoBuffer : public StreamInterface {
441 public:
442 // Creates a FIFO buffer with the specified capacity.
443 explicit FifoBuffer(size_t length);
444 // Creates a FIFO buffer with the specified capacity and owner
445 FifoBuffer(size_t length, Thread* owner);
446 ~FifoBuffer() override;
447 // Gets the amount of data currently readable from the buffer.
448 bool GetBuffered(size_t* data_len) const;
449 // Resizes the buffer to the specified capacity. Fails if data_length_ > size
450 bool SetCapacity(size_t length);
451
452 // Read into |buffer| with an offset from the current read position, offset
453 // is specified in number of bytes.
454 // This method doesn't adjust read position nor the number of available
455 // bytes, user has to call ConsumeReadData() to do this.
Yves Gerey665174f2018-06-19 15:03:05 +0200456 StreamResult ReadOffset(void* buffer,
457 size_t bytes,
458 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200459 size_t* bytes_read);
460
461 // Write |buffer| with an offset from the current write position, offset is
462 // specified in number of bytes.
463 // This method doesn't adjust the number of buffered bytes, user has to call
464 // ConsumeWriteBuffer() to do this.
Yves Gerey665174f2018-06-19 15:03:05 +0200465 StreamResult WriteOffset(const void* buffer,
466 size_t bytes,
467 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200468 size_t* bytes_written);
469
470 // StreamInterface methods
471 StreamState GetState() const override;
472 StreamResult Read(void* buffer,
473 size_t bytes,
474 size_t* bytes_read,
475 int* error) override;
476 StreamResult Write(const void* buffer,
477 size_t bytes,
478 size_t* bytes_written,
479 int* error) override;
480 void Close() override;
481 const void* GetReadData(size_t* data_len) override;
482 void ConsumeReadData(size_t used) override;
483 void* GetWriteBuffer(size_t* buf_len) override;
484 void ConsumeWriteBuffer(size_t used) override;
485 bool GetWriteRemaining(size_t* size) const override;
486
487 private:
488 // Helper method that implements ReadOffset. Caller must acquire a lock
489 // when calling this method.
danilchap3c6abd22017-09-06 05:46:29 -0700490 StreamResult ReadOffsetLocked(void* buffer,
491 size_t bytes,
492 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200493 size_t* bytes_read)
danilchap3c6abd22017-09-06 05:46:29 -0700494 RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200495
496 // Helper method that implements WriteOffset. Caller must acquire a lock
497 // when calling this method.
danilchap3c6abd22017-09-06 05:46:29 -0700498 StreamResult WriteOffsetLocked(const void* buffer,
499 size_t bytes,
500 size_t offset,
501 size_t* bytes_written)
502 RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200503
504 // keeps the opened/closed state of the stream
danilchap3c6abd22017-09-06 05:46:29 -0700505 StreamState state_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200506 // the allocated buffer
danilchap3c6abd22017-09-06 05:46:29 -0700507 std::unique_ptr<char[]> buffer_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200508 // size of the allocated buffer
danilchap3c6abd22017-09-06 05:46:29 -0700509 size_t buffer_length_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200510 // amount of readable data in the buffer
danilchap3c6abd22017-09-06 05:46:29 -0700511 size_t data_length_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200512 // offset to the readable data
danilchap3c6abd22017-09-06 05:46:29 -0700513 size_t read_position_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200514 // stream callbacks are dispatched on this thread
515 Thread* owner_;
516 // object lock
517 CriticalSection crit_;
518 RTC_DISALLOW_COPY_AND_ASSIGN(FifoBuffer);
519};
520
521///////////////////////////////////////////////////////////////////////////////
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200522
523// Flow attempts to move bytes from source to sink via buffer of size
524// buffer_len. The function returns SR_SUCCESS when source reaches
525// end-of-stream (returns SR_EOS), and all the data has been written successful
526// to sink. Alternately, if source returns SR_BLOCK or SR_ERROR, or if sink
527// returns SR_BLOCK, SR_ERROR, or SR_EOS, then the function immediately returns
528// with the unexpected StreamResult value.
529// data_len is the length of the valid data in buffer. in case of error
530// this is the data that read from source but can't move to destination.
531// as a pass in parameter, it indicates data in buffer that should move to sink
532StreamResult Flow(StreamInterface* source,
533 char* buffer,
534 size_t buffer_len,
535 StreamInterface* sink,
536 size_t* data_len = nullptr);
537
538///////////////////////////////////////////////////////////////////////////////
539
540} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000541
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200542#endif // RTC_BASE_STREAM_H_