blob: d3f2f740ee3bc8d0d9f89825b4dccc87c8156614 [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"
24#include "rtc_base/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///////////////////////////////////////////////////////////////////////////////
319// StreamTap is a non-modifying, pass-through adapter, which copies all data
320// in either direction to the tap. Note that errors or blocking on writing to
321// the tap will prevent further tap writes from occurring.
322///////////////////////////////////////////////////////////////////////////////
323
324class StreamTap : public StreamAdapterInterface {
325 public:
326 explicit StreamTap(StreamInterface* stream, StreamInterface* tap);
327 ~StreamTap() override;
328
329 void AttachTap(StreamInterface* tap);
330 StreamInterface* DetachTap();
331 StreamResult GetTapResult(int* error);
332
333 // StreamAdapterInterface Interface
334 StreamResult Read(void* buffer,
335 size_t buffer_len,
336 size_t* read,
337 int* error) override;
338 StreamResult Write(const void* data,
339 size_t data_len,
340 size_t* written,
341 int* error) override;
342
343 private:
344 std::unique_ptr<StreamInterface> tap_;
345 StreamResult tap_result_;
346 int tap_error_;
347 RTC_DISALLOW_COPY_AND_ASSIGN(StreamTap);
348};
349
350///////////////////////////////////////////////////////////////////////////////
351// NullStream gives errors on read, and silently discards all written data.
352///////////////////////////////////////////////////////////////////////////////
353
354class NullStream : public StreamInterface {
355 public:
356 NullStream();
357 ~NullStream() override;
358
359 // StreamInterface Interface
360 StreamState GetState() const override;
361 StreamResult Read(void* buffer,
362 size_t buffer_len,
363 size_t* read,
364 int* error) override;
365 StreamResult Write(const void* data,
366 size_t data_len,
367 size_t* written,
368 int* error) override;
369 void Close() override;
370};
371
372///////////////////////////////////////////////////////////////////////////////
373// FileStream is a simple implementation of a StreamInterface, which does not
374// support asynchronous notification.
375///////////////////////////////////////////////////////////////////////////////
376
377class FileStream : public StreamInterface {
378 public:
379 FileStream();
380 ~FileStream() override;
381
382 // The semantics of filename and mode are the same as stdio's fopen
383 virtual bool Open(const std::string& filename, const char* mode, int* error);
Yves Gerey665174f2018-06-19 15:03:05 +0200384 virtual bool OpenShare(const std::string& filename,
385 const char* mode,
386 int shflag,
387 int* error);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200388
389 // By default, reads and writes are buffered for efficiency. Disabling
390 // buffering causes writes to block until the bytes on disk are updated.
391 virtual bool DisableBuffering();
392
393 StreamState GetState() const override;
394 StreamResult Read(void* buffer,
395 size_t buffer_len,
396 size_t* read,
397 int* error) override;
398 StreamResult Write(const void* data,
399 size_t data_len,
400 size_t* written,
401 int* error) override;
402 void Close() override;
403 bool SetPosition(size_t position) override;
404 bool GetPosition(size_t* position) const override;
405 bool GetSize(size_t* size) const override;
406 bool GetAvailable(size_t* size) const override;
407 bool ReserveSize(size_t size) override;
408
409 bool Flush() override;
410
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200411 protected:
412 virtual void DoClose();
413
414 FILE* file_;
415
416 private:
417 RTC_DISALLOW_COPY_AND_ASSIGN(FileStream);
418};
419
420///////////////////////////////////////////////////////////////////////////////
421// MemoryStream is a simple implementation of a StreamInterface over in-memory
422// data. Data is read and written at the current seek position. Reads return
423// end-of-stream when they reach the end of data. Writes actually extend the
424// end of data mark.
425///////////////////////////////////////////////////////////////////////////////
426
427class MemoryStreamBase : public StreamInterface {
428 public:
429 StreamState GetState() const override;
430 StreamResult Read(void* buffer,
431 size_t bytes,
432 size_t* bytes_read,
433 int* error) override;
434 StreamResult Write(const void* buffer,
435 size_t bytes,
436 size_t* bytes_written,
437 int* error) override;
438 void Close() override;
439 bool SetPosition(size_t position) override;
440 bool GetPosition(size_t* position) const override;
441 bool GetSize(size_t* size) const override;
442 bool GetAvailable(size_t* size) const override;
443 bool ReserveSize(size_t size) override;
444
445 char* GetBuffer() { return buffer_; }
446 const char* GetBuffer() const { return buffer_; }
447
448 protected:
449 MemoryStreamBase();
450
451 virtual StreamResult DoReserve(size_t size, int* error);
452
453 // Invariant: 0 <= seek_position <= data_length_ <= buffer_length_
454 char* buffer_;
455 size_t buffer_length_;
456 size_t data_length_;
457 size_t seek_position_;
458
459 private:
460 RTC_DISALLOW_COPY_AND_ASSIGN(MemoryStreamBase);
461};
462
463// MemoryStream dynamically resizes to accomodate written data.
464
465class MemoryStream : public MemoryStreamBase {
466 public:
467 MemoryStream();
468 explicit MemoryStream(const char* data); // Calls SetData(data, strlen(data))
469 MemoryStream(const void* data, size_t length); // Calls SetData(data, length)
470 ~MemoryStream() override;
471
472 void SetData(const void* data, size_t length);
473
474 protected:
475 StreamResult DoReserve(size_t size, int* error) override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200476};
477
478// ExternalMemoryStream adapts an external memory buffer, so writes which would
479// extend past the end of the buffer will return end-of-stream.
480
481class ExternalMemoryStream : public MemoryStreamBase {
482 public:
483 ExternalMemoryStream();
484 ExternalMemoryStream(void* data, size_t length);
485 ~ExternalMemoryStream() override;
486
487 void SetData(void* data, size_t length);
488};
489
490// FifoBuffer allows for efficient, thread-safe buffering of data between
491// writer and reader. As the data can wrap around the end of the buffer,
492// MemoryStreamBase can't help us here.
493
494class FifoBuffer : public StreamInterface {
495 public:
496 // Creates a FIFO buffer with the specified capacity.
497 explicit FifoBuffer(size_t length);
498 // Creates a FIFO buffer with the specified capacity and owner
499 FifoBuffer(size_t length, Thread* owner);
500 ~FifoBuffer() override;
501 // Gets the amount of data currently readable from the buffer.
502 bool GetBuffered(size_t* data_len) const;
503 // Resizes the buffer to the specified capacity. Fails if data_length_ > size
504 bool SetCapacity(size_t length);
505
506 // Read into |buffer| with an offset from the current read position, offset
507 // is specified in number of bytes.
508 // This method doesn't adjust read position nor the number of available
509 // bytes, user has to call ConsumeReadData() to do this.
Yves Gerey665174f2018-06-19 15:03:05 +0200510 StreamResult ReadOffset(void* buffer,
511 size_t bytes,
512 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200513 size_t* bytes_read);
514
515 // Write |buffer| with an offset from the current write position, offset is
516 // specified in number of bytes.
517 // This method doesn't adjust the number of buffered bytes, user has to call
518 // ConsumeWriteBuffer() to do this.
Yves Gerey665174f2018-06-19 15:03:05 +0200519 StreamResult WriteOffset(const void* buffer,
520 size_t bytes,
521 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200522 size_t* bytes_written);
523
524 // StreamInterface methods
525 StreamState GetState() const override;
526 StreamResult Read(void* buffer,
527 size_t bytes,
528 size_t* bytes_read,
529 int* error) override;
530 StreamResult Write(const void* buffer,
531 size_t bytes,
532 size_t* bytes_written,
533 int* error) override;
534 void Close() override;
535 const void* GetReadData(size_t* data_len) override;
536 void ConsumeReadData(size_t used) override;
537 void* GetWriteBuffer(size_t* buf_len) override;
538 void ConsumeWriteBuffer(size_t used) override;
539 bool GetWriteRemaining(size_t* size) const override;
540
541 private:
542 // Helper method that implements ReadOffset. Caller must acquire a lock
543 // when calling this method.
danilchap3c6abd22017-09-06 05:46:29 -0700544 StreamResult ReadOffsetLocked(void* buffer,
545 size_t bytes,
546 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200547 size_t* bytes_read)
danilchap3c6abd22017-09-06 05:46:29 -0700548 RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200549
550 // Helper method that implements WriteOffset. Caller must acquire a lock
551 // when calling this method.
danilchap3c6abd22017-09-06 05:46:29 -0700552 StreamResult WriteOffsetLocked(const void* buffer,
553 size_t bytes,
554 size_t offset,
555 size_t* bytes_written)
556 RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200557
558 // keeps the opened/closed state of the stream
danilchap3c6abd22017-09-06 05:46:29 -0700559 StreamState state_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200560 // the allocated buffer
danilchap3c6abd22017-09-06 05:46:29 -0700561 std::unique_ptr<char[]> buffer_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200562 // size of the allocated buffer
danilchap3c6abd22017-09-06 05:46:29 -0700563 size_t buffer_length_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200564 // amount of readable data in the buffer
danilchap3c6abd22017-09-06 05:46:29 -0700565 size_t data_length_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200566 // offset to the readable data
danilchap3c6abd22017-09-06 05:46:29 -0700567 size_t read_position_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200568 // stream callbacks are dispatched on this thread
569 Thread* owner_;
570 // object lock
571 CriticalSection crit_;
572 RTC_DISALLOW_COPY_AND_ASSIGN(FifoBuffer);
573};
574
575///////////////////////////////////////////////////////////////////////////////
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200576// StringStream - Reads/Writes to an external std::string
577///////////////////////////////////////////////////////////////////////////////
578
579class StringStream : public StreamInterface {
580 public:
581 explicit StringStream(std::string* str);
582 explicit StringStream(const std::string& str);
583
584 StreamState GetState() const override;
585 StreamResult Read(void* buffer,
586 size_t buffer_len,
587 size_t* read,
588 int* error) override;
589 StreamResult Write(const void* data,
590 size_t data_len,
591 size_t* written,
592 int* error) override;
593 void Close() override;
594 bool SetPosition(size_t position) override;
595 bool GetPosition(size_t* position) const override;
596 bool GetSize(size_t* size) const override;
597 bool GetAvailable(size_t* size) const override;
598 bool ReserveSize(size_t size) override;
599
600 private:
601 std::string& str_;
602 size_t read_pos_;
603 bool read_only_;
604};
605
606///////////////////////////////////////////////////////////////////////////////
607// StreamReference - A reference counting stream adapter
608///////////////////////////////////////////////////////////////////////////////
609
610// Keep in mind that the streams and adapters defined in this file are
611// not thread-safe, so this has limited uses.
612
613// A StreamRefCount holds the reference count and a pointer to the
614// wrapped stream. It deletes the wrapped stream when there are no
615// more references. We can then have multiple StreamReference
616// instances pointing to one StreamRefCount, all wrapping the same
617// stream.
618
619class StreamReference : public StreamAdapterInterface {
620 class StreamRefCount;
Yves Gerey665174f2018-06-19 15:03:05 +0200621
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200622 public:
623 // Constructor for the first reference to a stream
624 // Note: get more references through NewReference(). Use this
625 // constructor only once on a given stream.
626 explicit StreamReference(StreamInterface* stream);
627 StreamInterface* GetStream() { return stream(); }
628 StreamInterface* NewReference();
629 ~StreamReference() override;
630
631 private:
632 class StreamRefCount {
633 public:
634 explicit StreamRefCount(StreamInterface* stream)
Yves Gerey665174f2018-06-19 15:03:05 +0200635 : stream_(stream), ref_count_(1) {}
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200636 void AddReference() {
637 CritScope lock(&cs_);
638 ++ref_count_;
639 }
640 void Release() {
641 int ref_count;
642 { // Atomic ops would have been a better fit here.
643 CritScope lock(&cs_);
644 ref_count = --ref_count_;
645 }
646 if (ref_count == 0) {
647 delete stream_;
648 delete this;
649 }
650 }
Yves Gerey665174f2018-06-19 15:03:05 +0200651
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200652 private:
653 StreamInterface* stream_;
654 int ref_count_;
655 CriticalSection cs_;
656 RTC_DISALLOW_COPY_AND_ASSIGN(StreamRefCount);
657 };
658
659 // Constructor for adding references
660 explicit StreamReference(StreamRefCount* stream_ref_count,
661 StreamInterface* stream);
662
663 StreamRefCount* stream_ref_count_;
664 RTC_DISALLOW_COPY_AND_ASSIGN(StreamReference);
665};
666
667///////////////////////////////////////////////////////////////////////////////
668
669// Flow attempts to move bytes from source to sink via buffer of size
670// buffer_len. The function returns SR_SUCCESS when source reaches
671// end-of-stream (returns SR_EOS), and all the data has been written successful
672// to sink. Alternately, if source returns SR_BLOCK or SR_ERROR, or if sink
673// returns SR_BLOCK, SR_ERROR, or SR_EOS, then the function immediately returns
674// with the unexpected StreamResult value.
675// data_len is the length of the valid data in buffer. in case of error
676// this is the data that read from source but can't move to destination.
677// as a pass in parameter, it indicates data in buffer that should move to sink
678StreamResult Flow(StreamInterface* source,
679 char* buffer,
680 size_t buffer_len,
681 StreamInterface* sink,
682 size_t* data_len = nullptr);
683
684///////////////////////////////////////////////////////////////////////////////
685
686} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000687
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200688#endif // RTC_BASE_STREAM_H_