blob: 81c5e41801a5baad651b42b5dadd8453b5123378 [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
Niels Möllere5aadba2018-09-20 15:39:18 +0200121 // always use whichever operation is most relevant.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200122 //
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200123 // The following four methods are used to avoid copying data multiple times.
124
125 // GetReadData returns a pointer to a buffer which is owned by the stream.
126 // The buffer contains data_len bytes. null is returned if no data is
127 // available, or if the method fails. If the caller processes the data, it
128 // must call ConsumeReadData with the number of processed bytes. GetReadData
129 // does not require a matching call to ConsumeReadData if the data is not
130 // processed. Read and ConsumeReadData invalidate the buffer returned by
131 // GetReadData.
132 virtual const void* GetReadData(size_t* data_len);
133 virtual void ConsumeReadData(size_t used) {}
134
135 // GetWriteBuffer returns a pointer to a buffer which is owned by the stream.
136 // The buffer has a capacity of buf_len bytes. null is returned if there is
137 // no buffer available, or if the method fails. The call may write data to
138 // the buffer, and then call ConsumeWriteBuffer with the number of bytes
139 // written. GetWriteBuffer does not require a matching call to
140 // ConsumeWriteData if no data is written. Write, ForceWrite, and
141 // ConsumeWriteData invalidate the buffer returned by GetWriteBuffer.
142 // TODO: Allow the caller to specify a minimum buffer size. If the specified
143 // amount of buffer is not yet available, return null and Signal SE_WRITE
144 // when it is available. If the requested amount is too large, return an
145 // error.
146 virtual void* GetWriteBuffer(size_t* buf_len);
147 virtual void ConsumeWriteBuffer(size_t used) {}
148
149 // Write data_len bytes found in data, circumventing any throttling which
150 // would could cause SR_BLOCK to be returned. Returns true if all the data
151 // was written. Otherwise, the method is unsupported, or an unrecoverable
152 // error occurred, and the error value is set. This method should be used
153 // sparingly to write critical data which should not be throttled. A stream
154 // which cannot circumvent its blocking constraints should not implement this
155 // method.
156 // NOTE: This interface is being considered experimentally at the moment. It
157 // would be used by JUDP and BandwidthStream as a way to circumvent certain
158 // soft limits in writing.
Yves Gerey665174f2018-06-19 15:03:05 +0200159 // virtual bool ForceWrite(const void* data, size_t data_len, int* error) {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200160 // if (error) *error = -1;
161 // return false;
162 //}
163
164 // Seek to a byte offset from the beginning of the stream. Returns false if
165 // the stream does not support seeking, or cannot seek to the specified
166 // position.
167 virtual bool SetPosition(size_t position);
168
169 // Get the byte offset of the current position from the start of the stream.
170 // Returns false if the position is not known.
171 virtual bool GetPosition(size_t* position) const;
172
173 // Get the byte length of the entire stream. Returns false if the length
174 // is not known.
175 virtual bool GetSize(size_t* size) const;
176
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200177 // Return the number of Write()-able bytes remaining before end-of-stream.
178 // Returns false if not known.
179 virtual bool GetWriteRemaining(size_t* size) const;
180
181 // Return true if flush is successful.
182 virtual bool Flush();
183
184 // Communicates the amount of data which will be written to the stream. The
185 // stream may choose to preallocate memory to accomodate this data. The
186 // stream may return false to indicate that there is not enough room (ie,
187 // Write will return SR_EOS/SR_ERROR at some point). Note that calling this
188 // function should not affect the existing state of data in the stream.
189 virtual bool ReserveSize(size_t size);
190
191 //
192 // CONVENIENCE METHODS
193 //
194 // These methods are implemented in terms of other methods, for convenience.
195 //
196
197 // Seek to the start of the stream.
198 inline bool Rewind() { return SetPosition(0); }
199
200 // WriteAll is a helper function which repeatedly calls Write until all the
201 // data is written, or something other than SR_SUCCESS is returned. Note that
202 // unlike Write, the argument 'written' is always set, and may be non-zero
203 // on results other than SR_SUCCESS. The remaining arguments have the
204 // same semantics as Write.
Yves Gerey665174f2018-06-19 15:03:05 +0200205 StreamResult WriteAll(const void* data,
206 size_t data_len,
207 size_t* written,
208 int* error);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200209
210 // Similar to ReadAll. Calls Read until buffer_len bytes have been read, or
211 // until a non-SR_SUCCESS result is returned. 'read' is always set.
Yves Gerey665174f2018-06-19 15:03:05 +0200212 StreamResult ReadAll(void* buffer,
213 size_t buffer_len,
214 size_t* read,
215 int* error);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200216
217 // ReadLine is a helper function which repeatedly calls Read until it hits
218 // the end-of-line character, or something other than SR_SUCCESS.
219 // TODO: this is too inefficient to keep here. Break this out into a buffered
220 // readline object or adapter
221 StreamResult ReadLine(std::string* line);
222
223 protected:
224 StreamInterface();
225
226 // MessageHandler Interface
227 void OnMessage(Message* msg) override;
228
229 private:
230 RTC_DISALLOW_COPY_AND_ASSIGN(StreamInterface);
231};
232
233///////////////////////////////////////////////////////////////////////////////
234// StreamAdapterInterface is a convenient base-class for adapting a stream.
235// By default, all operations are pass-through. Override the methods that you
236// require adaptation. Streams should really be upgraded to reference-counted.
237// In the meantime, use the owned flag to indicate whether the adapter should
238// own the adapted stream.
239///////////////////////////////////////////////////////////////////////////////
240
241class StreamAdapterInterface : public StreamInterface,
242 public sigslot::has_slots<> {
243 public:
244 explicit StreamAdapterInterface(StreamInterface* stream, bool owned = true);
245
246 // Core Stream Interface
247 StreamState GetState() const override;
248 StreamResult Read(void* buffer,
249 size_t buffer_len,
250 size_t* read,
251 int* error) override;
252 StreamResult Write(const void* data,
253 size_t data_len,
254 size_t* written,
255 int* error) override;
256 void Close() override;
257
258 // Optional Stream Interface
259 /* Note: Many stream adapters were implemented prior to this Read/Write
260 interface. Therefore, a simple pass through of data in those cases may
261 be broken. At a later time, we should do a once-over pass of all
262 adapters, and make them compliant with these interfaces, after which this
263 code can be uncommented.
264 virtual const void* GetReadData(size_t* data_len) {
265 return stream_->GetReadData(data_len);
266 }
267 virtual void ConsumeReadData(size_t used) {
268 stream_->ConsumeReadData(used);
269 }
270
271 virtual void* GetWriteBuffer(size_t* buf_len) {
272 return stream_->GetWriteBuffer(buf_len);
273 }
274 virtual void ConsumeWriteBuffer(size_t used) {
275 stream_->ConsumeWriteBuffer(used);
276 }
277 */
278
279 /* Note: This interface is currently undergoing evaluation.
280 virtual bool ForceWrite(const void* data, size_t data_len, int* error) {
281 return stream_->ForceWrite(data, data_len, error);
282 }
283 */
284
285 bool SetPosition(size_t position) override;
286 bool GetPosition(size_t* position) const override;
287 bool GetSize(size_t* size) const override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200288 bool GetWriteRemaining(size_t* size) const override;
289 bool ReserveSize(size_t size) override;
290 bool Flush() override;
291
292 void Attach(StreamInterface* stream, bool owned = true);
293 StreamInterface* Detach();
294
295 protected:
296 ~StreamAdapterInterface() override;
297
298 // Note that the adapter presents itself as the origin of the stream events,
299 // since users of the adapter may not recognize the adapted object.
300 virtual void OnEvent(StreamInterface* stream, int events, int err);
301 StreamInterface* stream() { return stream_; }
302
303 private:
304 StreamInterface* stream_;
305 bool owned_;
306 RTC_DISALLOW_COPY_AND_ASSIGN(StreamAdapterInterface);
307};
308
309///////////////////////////////////////////////////////////////////////////////
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200310// FileStream is a simple implementation of a StreamInterface, which does not
311// support asynchronous notification.
312///////////////////////////////////////////////////////////////////////////////
313
314class FileStream : public StreamInterface {
315 public:
316 FileStream();
317 ~FileStream() override;
318
319 // The semantics of filename and mode are the same as stdio's fopen
320 virtual bool Open(const std::string& filename, const char* mode, int* error);
Yves Gerey665174f2018-06-19 15:03:05 +0200321 virtual bool OpenShare(const std::string& filename,
322 const char* mode,
323 int shflag,
324 int* error);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200325
326 // By default, reads and writes are buffered for efficiency. Disabling
327 // buffering causes writes to block until the bytes on disk are updated.
328 virtual bool DisableBuffering();
329
330 StreamState GetState() const override;
331 StreamResult Read(void* buffer,
332 size_t buffer_len,
333 size_t* read,
334 int* error) override;
335 StreamResult Write(const void* data,
336 size_t data_len,
337 size_t* written,
338 int* error) override;
339 void Close() override;
340 bool SetPosition(size_t position) override;
341 bool GetPosition(size_t* position) const override;
342 bool GetSize(size_t* size) const override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200343 bool ReserveSize(size_t size) override;
344
345 bool Flush() override;
346
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200347 protected:
348 virtual void DoClose();
349
350 FILE* file_;
351
352 private:
353 RTC_DISALLOW_COPY_AND_ASSIGN(FileStream);
354};
355
356///////////////////////////////////////////////////////////////////////////////
357// MemoryStream is a simple implementation of a StreamInterface over in-memory
358// data. Data is read and written at the current seek position. Reads return
359// end-of-stream when they reach the end of data. Writes actually extend the
360// end of data mark.
361///////////////////////////////////////////////////////////////////////////////
362
363class MemoryStreamBase : public StreamInterface {
364 public:
365 StreamState GetState() const override;
366 StreamResult Read(void* buffer,
367 size_t bytes,
368 size_t* bytes_read,
369 int* error) override;
370 StreamResult Write(const void* buffer,
371 size_t bytes,
372 size_t* bytes_written,
373 int* error) override;
374 void Close() override;
375 bool SetPosition(size_t position) override;
376 bool GetPosition(size_t* position) const override;
377 bool GetSize(size_t* size) const override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200378 bool ReserveSize(size_t size) override;
379
380 char* GetBuffer() { return buffer_; }
381 const char* GetBuffer() const { return buffer_; }
382
383 protected:
384 MemoryStreamBase();
385
386 virtual StreamResult DoReserve(size_t size, int* error);
387
388 // Invariant: 0 <= seek_position <= data_length_ <= buffer_length_
389 char* buffer_;
390 size_t buffer_length_;
391 size_t data_length_;
392 size_t seek_position_;
393
394 private:
395 RTC_DISALLOW_COPY_AND_ASSIGN(MemoryStreamBase);
396};
397
398// MemoryStream dynamically resizes to accomodate written data.
399
400class MemoryStream : public MemoryStreamBase {
401 public:
402 MemoryStream();
403 explicit MemoryStream(const char* data); // Calls SetData(data, strlen(data))
404 MemoryStream(const void* data, size_t length); // Calls SetData(data, length)
405 ~MemoryStream() override;
406
407 void SetData(const void* data, size_t length);
408
409 protected:
410 StreamResult DoReserve(size_t size, int* error) override;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200411};
412
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200413// FifoBuffer allows for efficient, thread-safe buffering of data between
414// writer and reader. As the data can wrap around the end of the buffer,
415// MemoryStreamBase can't help us here.
416
417class FifoBuffer : public StreamInterface {
418 public:
419 // Creates a FIFO buffer with the specified capacity.
420 explicit FifoBuffer(size_t length);
421 // Creates a FIFO buffer with the specified capacity and owner
422 FifoBuffer(size_t length, Thread* owner);
423 ~FifoBuffer() override;
424 // Gets the amount of data currently readable from the buffer.
425 bool GetBuffered(size_t* data_len) const;
426 // Resizes the buffer to the specified capacity. Fails if data_length_ > size
427 bool SetCapacity(size_t length);
428
429 // Read into |buffer| with an offset from the current read position, offset
430 // is specified in number of bytes.
431 // This method doesn't adjust read position nor the number of available
432 // bytes, user has to call ConsumeReadData() to do this.
Yves Gerey665174f2018-06-19 15:03:05 +0200433 StreamResult ReadOffset(void* buffer,
434 size_t bytes,
435 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200436 size_t* bytes_read);
437
438 // Write |buffer| with an offset from the current write position, offset is
439 // specified in number of bytes.
440 // This method doesn't adjust the number of buffered bytes, user has to call
441 // ConsumeWriteBuffer() to do this.
Yves Gerey665174f2018-06-19 15:03:05 +0200442 StreamResult WriteOffset(const void* buffer,
443 size_t bytes,
444 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200445 size_t* bytes_written);
446
447 // StreamInterface methods
448 StreamState GetState() const override;
449 StreamResult Read(void* buffer,
450 size_t bytes,
451 size_t* bytes_read,
452 int* error) override;
453 StreamResult Write(const void* buffer,
454 size_t bytes,
455 size_t* bytes_written,
456 int* error) override;
457 void Close() override;
458 const void* GetReadData(size_t* data_len) override;
459 void ConsumeReadData(size_t used) override;
460 void* GetWriteBuffer(size_t* buf_len) override;
461 void ConsumeWriteBuffer(size_t used) override;
462 bool GetWriteRemaining(size_t* size) const override;
463
464 private:
465 // Helper method that implements ReadOffset. Caller must acquire a lock
466 // when calling this method.
danilchap3c6abd22017-09-06 05:46:29 -0700467 StreamResult ReadOffsetLocked(void* buffer,
468 size_t bytes,
469 size_t offset,
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200470 size_t* bytes_read)
danilchap3c6abd22017-09-06 05:46:29 -0700471 RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200472
473 // Helper method that implements WriteOffset. Caller must acquire a lock
474 // when calling this method.
danilchap3c6abd22017-09-06 05:46:29 -0700475 StreamResult WriteOffsetLocked(const void* buffer,
476 size_t bytes,
477 size_t offset,
478 size_t* bytes_written)
479 RTC_EXCLUSIVE_LOCKS_REQUIRED(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200480
481 // keeps the opened/closed state of the stream
danilchap3c6abd22017-09-06 05:46:29 -0700482 StreamState state_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200483 // the allocated buffer
danilchap3c6abd22017-09-06 05:46:29 -0700484 std::unique_ptr<char[]> buffer_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200485 // size of the allocated buffer
danilchap3c6abd22017-09-06 05:46:29 -0700486 size_t buffer_length_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200487 // amount of readable data in the buffer
danilchap3c6abd22017-09-06 05:46:29 -0700488 size_t data_length_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200489 // offset to the readable data
danilchap3c6abd22017-09-06 05:46:29 -0700490 size_t read_position_ RTC_GUARDED_BY(crit_);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200491 // stream callbacks are dispatched on this thread
492 Thread* owner_;
493 // object lock
494 CriticalSection crit_;
495 RTC_DISALLOW_COPY_AND_ASSIGN(FifoBuffer);
496};
497
498///////////////////////////////////////////////////////////////////////////////
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200499
500// Flow attempts to move bytes from source to sink via buffer of size
501// buffer_len. The function returns SR_SUCCESS when source reaches
502// end-of-stream (returns SR_EOS), and all the data has been written successful
503// to sink. Alternately, if source returns SR_BLOCK or SR_ERROR, or if sink
504// returns SR_BLOCK, SR_ERROR, or SR_EOS, then the function immediately returns
505// with the unexpected StreamResult value.
506// data_len is the length of the valid data in buffer. in case of error
507// this is the data that read from source but can't move to destination.
508// as a pass in parameter, it indicates data in buffer that should move to sink
509StreamResult Flow(StreamInterface* source,
510 char* buffer,
511 size_t buffer_len,
512 StreamInterface* sink,
513 size_t* data_len = nullptr);
514
515///////////////////////////////////////////////////////////////////////////////
516
517} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000518
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200519#endif // RTC_BASE_STREAM_H_