blob: 6ab6683c480b573dd3cb73a4dad68a7cf468dfa7 [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
11#ifndef WEBRTC_BASE_STREAM_H_
12#define WEBRTC_BASE_STREAM_H_
13
14#include <stdio.h>
15
16#include "webrtc/base/basictypes.h"
17#include "webrtc/base/buffer.h"
18#include "webrtc/base/criticalsection.h"
19#include "webrtc/base/logging.h"
20#include "webrtc/base/messagehandler.h"
21#include "webrtc/base/messagequeue.h"
22#include "webrtc/base/scoped_ptr.h"
23#include "webrtc/base/sigslot.h"
24
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;
57 StreamEventData(int ev, int er) : events(ev), error(er) { }
58};
59
60class StreamInterface : public MessageHandler {
61 public:
62 enum {
63 MSG_POST_EVENT = 0xF1F1, MSG_MAX = MSG_POST_EVENT
64 };
65
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +000066 ~StreamInterface() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000067
68 virtual StreamState GetState() const = 0;
69
70 // Read attempts to fill buffer of size buffer_len. Write attempts to send
71 // data_len bytes stored in data. The variables read and write are set only
72 // on SR_SUCCESS (see below). Likewise, error is only set on SR_ERROR.
73 // Read and Write return a value indicating:
74 // SR_ERROR: an error occurred, which is returned in a non-null error
75 // argument. Interpretation of the error requires knowledge of the
76 // stream's concrete type, which limits its usefulness.
77 // SR_SUCCESS: some number of bytes were successfully written, which is
78 // returned in a non-null read/write argument.
79 // SR_BLOCK: the stream is in non-blocking mode, and the operation would
80 // block, or the stream is in SS_OPENING state.
81 // SR_EOS: the end-of-stream has been reached, or the stream is in the
82 // SS_CLOSED state.
83 virtual StreamResult Read(void* buffer, size_t buffer_len,
84 size_t* read, int* error) = 0;
85 virtual StreamResult Write(const void* data, size_t data_len,
86 size_t* written, int* error) = 0;
87 // Attempt to transition to the SS_CLOSED state. SE_CLOSE will not be
88 // signalled as a result of this call.
89 virtual void Close() = 0;
90
91 // Streams may signal one or more StreamEvents to indicate state changes.
92 // The first argument identifies the stream on which the state change occured.
93 // The second argument is a bit-wise combination of StreamEvents.
94 // If SE_CLOSE is signalled, then the third argument is the associated error
95 // code. Otherwise, the value is undefined.
96 // Note: Not all streams will support asynchronous event signalling. However,
97 // SS_OPENING and SR_BLOCK returned from stream member functions imply that
98 // certain events will be raised in the future.
99 sigslot::signal3<StreamInterface*, int, int> SignalEvent;
100
101 // Like calling SignalEvent, but posts a message to the specified thread,
102 // which will call SignalEvent. This helps unroll the stack and prevent
103 // re-entrancy.
104 void PostEvent(Thread* t, int events, int err);
105 // Like the aforementioned method, but posts to the current thread.
106 void PostEvent(int events, int err);
107
108 //
109 // OPTIONAL OPERATIONS
110 //
111 // Not all implementations will support the following operations. In general,
112 // a stream will only support an operation if it reasonably efficient to do
113 // so. For example, while a socket could buffer incoming data to support
114 // seeking, it will not do so. Instead, a buffering stream adapter should
115 // be used.
116 //
117 // Even though several of these operations are related, you should
118 // always use whichever operation is most relevant. For example, you may
119 // be tempted to use GetSize() and GetPosition() to deduce the result of
120 // GetAvailable(). However, a stream which is read-once may support the
121 // latter operation but not the former.
122 //
123
124 // The following four methods are used to avoid copying data multiple times.
125
126 // GetReadData returns a pointer to a buffer which is owned by the stream.
127 // The buffer contains data_len bytes. NULL is returned if no data is
128 // available, or if the method fails. If the caller processes the data, it
129 // must call ConsumeReadData with the number of processed bytes. GetReadData
130 // does not require a matching call to ConsumeReadData if the data is not
131 // processed. Read and ConsumeReadData invalidate the buffer returned by
132 // GetReadData.
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000133 virtual const void* GetReadData(size_t* data_len);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000134 virtual void ConsumeReadData(size_t used) {}
135
136 // GetWriteBuffer returns a pointer to a buffer which is owned by the stream.
137 // The buffer has a capacity of buf_len bytes. NULL is returned if there is
138 // no buffer available, or if the method fails. The call may write data to
139 // the buffer, and then call ConsumeWriteBuffer with the number of bytes
140 // written. GetWriteBuffer does not require a matching call to
141 // ConsumeWriteData if no data is written. Write, ForceWrite, and
142 // ConsumeWriteData invalidate the buffer returned by GetWriteBuffer.
143 // TODO: Allow the caller to specify a minimum buffer size. If the specified
144 // amount of buffer is not yet available, return NULL and Signal SE_WRITE
145 // when it is available. If the requested amount is too large, return an
146 // error.
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000147 virtual void* GetWriteBuffer(size_t* buf_len);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000148 virtual void ConsumeWriteBuffer(size_t used) {}
149
150 // Write data_len bytes found in data, circumventing any throttling which
151 // would could cause SR_BLOCK to be returned. Returns true if all the data
152 // was written. Otherwise, the method is unsupported, or an unrecoverable
153 // error occurred, and the error value is set. This method should be used
154 // sparingly to write critical data which should not be throttled. A stream
155 // which cannot circumvent its blocking constraints should not implement this
156 // method.
157 // NOTE: This interface is being considered experimentally at the moment. It
158 // would be used by JUDP and BandwidthStream as a way to circumvent certain
159 // soft limits in writing.
160 //virtual bool ForceWrite(const void* data, size_t data_len, int* error) {
161 // if (error) *error = -1;
162 // return false;
163 //}
164
165 // Seek to a byte offset from the beginning of the stream. Returns false if
166 // the stream does not support seeking, or cannot seek to the specified
167 // position.
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000168 virtual bool SetPosition(size_t position);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000169
170 // Get the byte offset of the current position from the start of the stream.
171 // Returns false if the position is not known.
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000172 virtual bool GetPosition(size_t* position) const;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000173
174 // Get the byte length of the entire stream. Returns false if the length
175 // is not known.
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000176 virtual bool GetSize(size_t* size) const;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000177
178 // Return the number of Read()-able bytes remaining before end-of-stream.
179 // Returns false if not known.
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000180 virtual bool GetAvailable(size_t* size) const;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000181
182 // Return the number of Write()-able bytes remaining before end-of-stream.
183 // Returns false if not known.
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000184 virtual bool GetWriteRemaining(size_t* size) const;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000185
186 // Return true if flush is successful.
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000187 virtual bool Flush();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000188
189 // Communicates the amount of data which will be written to the stream. The
190 // stream may choose to preallocate memory to accomodate this data. The
191 // stream may return false to indicate that there is not enough room (ie,
192 // Write will return SR_EOS/SR_ERROR at some point). Note that calling this
193 // function should not affect the existing state of data in the stream.
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000194 virtual bool ReserveSize(size_t size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000195
196 //
197 // CONVENIENCE METHODS
198 //
199 // These methods are implemented in terms of other methods, for convenience.
200 //
201
202 // Seek to the start of the stream.
203 inline bool Rewind() { return SetPosition(0); }
204
205 // WriteAll is a helper function which repeatedly calls Write until all the
206 // data is written, or something other than SR_SUCCESS is returned. Note that
207 // unlike Write, the argument 'written' is always set, and may be non-zero
208 // on results other than SR_SUCCESS. The remaining arguments have the
209 // same semantics as Write.
210 StreamResult WriteAll(const void* data, size_t data_len,
211 size_t* written, int* error);
212
213 // Similar to ReadAll. Calls Read until buffer_len bytes have been read, or
214 // until a non-SR_SUCCESS result is returned. 'read' is always set.
215 StreamResult ReadAll(void* buffer, size_t buffer_len,
216 size_t* read, int* error);
217
218 // ReadLine is a helper function which repeatedly calls Read until it hits
219 // the end-of-line character, or something other than SR_SUCCESS.
220 // TODO: this is too inefficient to keep here. Break this out into a buffered
221 // readline object or adapter
222 StreamResult ReadLine(std::string* line);
223
224 protected:
225 StreamInterface();
226
227 // MessageHandler Interface
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000228 void OnMessage(Message* msg) override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000229
230 private:
Thiago Farinaae0f0ee2015-04-04 23:56:53 +0000231 DISALLOW_COPY_AND_ASSIGN(StreamInterface);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000232};
233
234///////////////////////////////////////////////////////////////////////////////
235// StreamAdapterInterface is a convenient base-class for adapting a stream.
236// By default, all operations are pass-through. Override the methods that you
237// require adaptation. Streams should really be upgraded to reference-counted.
238// In the meantime, use the owned flag to indicate whether the adapter should
239// own the adapted stream.
240///////////////////////////////////////////////////////////////////////////////
241
242class StreamAdapterInterface : public StreamInterface,
243 public sigslot::has_slots<> {
244 public:
245 explicit StreamAdapterInterface(StreamInterface* stream, bool owned = true);
246
247 // Core Stream Interface
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000248 StreamState GetState() const override;
249 StreamResult Read(void* buffer,
250 size_t buffer_len,
251 size_t* read,
252 int* error) override;
253 StreamResult Write(const void* data,
254 size_t data_len,
255 size_t* written,
256 int* error) override;
257 void Close() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000258
259 // Optional Stream Interface
260 /* Note: Many stream adapters were implemented prior to this Read/Write
261 interface. Therefore, a simple pass through of data in those cases may
262 be broken. At a later time, we should do a once-over pass of all
263 adapters, and make them compliant with these interfaces, after which this
264 code can be uncommented.
265 virtual const void* GetReadData(size_t* data_len) {
266 return stream_->GetReadData(data_len);
267 }
268 virtual void ConsumeReadData(size_t used) {
269 stream_->ConsumeReadData(used);
270 }
271
272 virtual void* GetWriteBuffer(size_t* buf_len) {
273 return stream_->GetWriteBuffer(buf_len);
274 }
275 virtual void ConsumeWriteBuffer(size_t used) {
276 stream_->ConsumeWriteBuffer(used);
277 }
278 */
279
280 /* Note: This interface is currently undergoing evaluation.
281 virtual bool ForceWrite(const void* data, size_t data_len, int* error) {
282 return stream_->ForceWrite(data, data_len, error);
283 }
284 */
285
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000286 bool SetPosition(size_t position) override;
287 bool GetPosition(size_t* position) const override;
288 bool GetSize(size_t* size) const override;
289 bool GetAvailable(size_t* size) const override;
290 bool GetWriteRemaining(size_t* size) const override;
291 bool ReserveSize(size_t size) override;
292 bool Flush() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000293
294 void Attach(StreamInterface* stream, bool owned = true);
295 StreamInterface* Detach();
296
297 protected:
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000298 ~StreamAdapterInterface() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000299
300 // Note that the adapter presents itself as the origin of the stream events,
301 // since users of the adapter may not recognize the adapted object.
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000302 virtual void OnEvent(StreamInterface* stream, int events, int err);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000303 StreamInterface* stream() { return stream_; }
304
305 private:
306 StreamInterface* stream_;
307 bool owned_;
Thiago Farinaae0f0ee2015-04-04 23:56:53 +0000308 DISALLOW_COPY_AND_ASSIGN(StreamAdapterInterface);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000309};
310
311///////////////////////////////////////////////////////////////////////////////
312// StreamTap is a non-modifying, pass-through adapter, which copies all data
313// in either direction to the tap. Note that errors or blocking on writing to
314// the tap will prevent further tap writes from occurring.
315///////////////////////////////////////////////////////////////////////////////
316
317class StreamTap : public StreamAdapterInterface {
318 public:
319 explicit StreamTap(StreamInterface* stream, StreamInterface* tap);
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000320 ~StreamTap() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000321
322 void AttachTap(StreamInterface* tap);
323 StreamInterface* DetachTap();
324 StreamResult GetTapResult(int* error);
325
326 // StreamAdapterInterface Interface
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000327 StreamResult Read(void* buffer,
328 size_t buffer_len,
329 size_t* read,
330 int* error) override;
331 StreamResult Write(const void* data,
332 size_t data_len,
333 size_t* written,
334 int* error) override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000335
336 private:
337 scoped_ptr<StreamInterface> tap_;
338 StreamResult tap_result_;
339 int tap_error_;
Thiago Farinaae0f0ee2015-04-04 23:56:53 +0000340 DISALLOW_COPY_AND_ASSIGN(StreamTap);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000341};
342
343///////////////////////////////////////////////////////////////////////////////
344// StreamSegment adapts a read stream, to expose a subset of the adapted
345// stream's data. This is useful for cases where a stream contains multiple
346// documents concatenated together. StreamSegment can expose a subset of
347// the data as an independent stream, including support for rewinding and
348// seeking.
349///////////////////////////////////////////////////////////////////////////////
350
351class StreamSegment : public StreamAdapterInterface {
352 public:
353 // The current position of the adapted stream becomes the beginning of the
354 // segment. If a length is specified, it bounds the length of the segment.
355 explicit StreamSegment(StreamInterface* stream);
356 explicit StreamSegment(StreamInterface* stream, size_t length);
357
358 // StreamAdapterInterface Interface
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000359 StreamResult Read(void* buffer,
360 size_t buffer_len,
361 size_t* read,
362 int* error) override;
363 bool SetPosition(size_t position) override;
364 bool GetPosition(size_t* position) const override;
365 bool GetSize(size_t* size) const override;
366 bool GetAvailable(size_t* size) const override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000367
368 private:
369 size_t start_, pos_, length_;
Thiago Farinaae0f0ee2015-04-04 23:56:53 +0000370 DISALLOW_COPY_AND_ASSIGN(StreamSegment);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000371};
372
373///////////////////////////////////////////////////////////////////////////////
374// NullStream gives errors on read, and silently discards all written data.
375///////////////////////////////////////////////////////////////////////////////
376
377class NullStream : public StreamInterface {
378 public:
379 NullStream();
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000380 ~NullStream() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000381
382 // StreamInterface Interface
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000383 StreamState GetState() const override;
384 StreamResult Read(void* buffer,
385 size_t buffer_len,
386 size_t* read,
387 int* error) override;
388 StreamResult Write(const void* data,
389 size_t data_len,
390 size_t* written,
391 int* error) override;
392 void Close() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000393};
394
395///////////////////////////////////////////////////////////////////////////////
396// FileStream is a simple implementation of a StreamInterface, which does not
397// support asynchronous notification.
398///////////////////////////////////////////////////////////////////////////////
399
400class FileStream : public StreamInterface {
401 public:
402 FileStream();
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000403 ~FileStream() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000404
405 // The semantics of filename and mode are the same as stdio's fopen
406 virtual bool Open(const std::string& filename, const char* mode, int* error);
407 virtual bool OpenShare(const std::string& filename, const char* mode,
408 int shflag, int* error);
409
410 // By default, reads and writes are buffered for efficiency. Disabling
411 // buffering causes writes to block until the bytes on disk are updated.
412 virtual bool DisableBuffering();
413
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000414 StreamState GetState() const override;
415 StreamResult Read(void* buffer,
416 size_t buffer_len,
417 size_t* read,
418 int* error) override;
419 StreamResult Write(const void* data,
420 size_t data_len,
421 size_t* written,
422 int* error) override;
423 void Close() override;
424 bool SetPosition(size_t position) override;
425 bool GetPosition(size_t* position) const override;
426 bool GetSize(size_t* size) const override;
427 bool GetAvailable(size_t* size) const override;
428 bool ReserveSize(size_t size) override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000429
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000430 bool Flush() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000431
432#if defined(WEBRTC_POSIX) && !defined(__native_client__)
433 // Tries to aquire an exclusive lock on the file.
434 // Use OpenShare(...) on win32 to get similar functionality.
435 bool TryLock();
436 bool Unlock();
437#endif
438
439 // Note: Deprecated in favor of Filesystem::GetFileSize().
440 static bool GetSize(const std::string& filename, size_t* size);
441
442 protected:
443 virtual void DoClose();
444
445 FILE* file_;
446
447 private:
Thiago Farinaae0f0ee2015-04-04 23:56:53 +0000448 DISALLOW_COPY_AND_ASSIGN(FileStream);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000449};
450
451// A stream that caps the output at a certain size, dropping content from the
452// middle of the logical stream and maintaining equal parts of the start/end of
453// the logical stream.
454class CircularFileStream : public FileStream {
455 public:
456 explicit CircularFileStream(size_t max_size);
457
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000458 bool Open(const std::string& filename, const char* mode, int* error) override;
459 StreamResult Read(void* buffer,
460 size_t buffer_len,
461 size_t* read,
462 int* error) override;
463 StreamResult Write(const void* data,
464 size_t data_len,
465 size_t* written,
466 int* error) override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000467
468 private:
469 enum ReadSegment {
470 READ_MARKED, // Read 0 .. marked_position_
471 READ_MIDDLE, // Read position_ .. file_size
472 READ_LATEST, // Read marked_position_ .. position_ if the buffer was
473 // overwritten or 0 .. position_ otherwise.
474 };
475
476 size_t max_write_size_;
477 size_t position_;
478 size_t marked_position_;
479 size_t last_write_position_;
480 ReadSegment read_segment_;
481 size_t read_segment_available_;
482};
483
484// A stream which pushes writes onto a separate thread and
485// returns from the write call immediately.
486class AsyncWriteStream : public StreamInterface {
487 public:
488 // Takes ownership of the stream, but not the thread.
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000489 AsyncWriteStream(StreamInterface* stream, rtc::Thread* write_thread);
490 ~AsyncWriteStream() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000491
492 // StreamInterface Interface
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000493 StreamState GetState() const override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000494 // This is needed by some stream writers, such as RtpDumpWriter.
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000495 bool GetPosition(size_t* position) const override;
496 StreamResult Read(void* buffer,
497 size_t buffer_len,
498 size_t* read,
499 int* error) override;
500 StreamResult Write(const void* data,
501 size_t data_len,
502 size_t* written,
503 int* error) override;
504 void Close() override;
505 bool Flush() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000506
507 protected:
508 // From MessageHandler
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000509 void OnMessage(rtc::Message* pmsg) override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000510 virtual void ClearBufferAndWrite();
511
512 private:
513 rtc::scoped_ptr<StreamInterface> stream_;
514 Thread* write_thread_;
515 StreamState state_;
516 Buffer buffer_;
517 mutable CriticalSection crit_stream_;
518 CriticalSection crit_buffer_;
519
Thiago Farinaae0f0ee2015-04-04 23:56:53 +0000520 DISALLOW_COPY_AND_ASSIGN(AsyncWriteStream);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000521};
522
523
524#if defined(WEBRTC_POSIX) && !defined(__native_client__)
525// A FileStream that is actually not a file, but the output or input of a
526// sub-command. See "man 3 popen" for documentation of the underlying OS popen()
527// function.
528class POpenStream : public FileStream {
529 public:
530 POpenStream() : wait_status_(-1) {}
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000531 ~POpenStream() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000532
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000533 bool Open(const std::string& subcommand,
534 const char* mode,
535 int* error) override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000536 // Same as Open(). shflag is ignored.
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000537 bool OpenShare(const std::string& subcommand,
538 const char* mode,
539 int shflag,
540 int* error) override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000541
542 // Returns the wait status from the last Close() of an Open()'ed stream, or
543 // -1 if no Open()+Close() has been done on this object. Meaning of the number
544 // is documented in "man 2 wait".
545 int GetWaitStatus() const { return wait_status_; }
546
547 protected:
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000548 void DoClose() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000549
550 private:
551 int wait_status_;
552};
553#endif // WEBRTC_POSIX
554
555///////////////////////////////////////////////////////////////////////////////
556// MemoryStream is a simple implementation of a StreamInterface over in-memory
557// data. Data is read and written at the current seek position. Reads return
558// end-of-stream when they reach the end of data. Writes actually extend the
559// end of data mark.
560///////////////////////////////////////////////////////////////////////////////
561
562class MemoryStreamBase : public StreamInterface {
563 public:
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000564 StreamState GetState() const override;
565 StreamResult Read(void* buffer,
566 size_t bytes,
567 size_t* bytes_read,
568 int* error) override;
569 StreamResult Write(const void* buffer,
570 size_t bytes,
571 size_t* bytes_written,
572 int* error) override;
573 void Close() override;
574 bool SetPosition(size_t position) override;
575 bool GetPosition(size_t* position) const override;
576 bool GetSize(size_t* size) const override;
577 bool GetAvailable(size_t* size) const override;
578 bool ReserveSize(size_t size) override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000579
580 char* GetBuffer() { return buffer_; }
581 const char* GetBuffer() const { return buffer_; }
582
583 protected:
584 MemoryStreamBase();
585
586 virtual StreamResult DoReserve(size_t size, int* error);
587
588 // Invariant: 0 <= seek_position <= data_length_ <= buffer_length_
589 char* buffer_;
590 size_t buffer_length_;
591 size_t data_length_;
592 size_t seek_position_;
593
594 private:
Thiago Farinaae0f0ee2015-04-04 23:56:53 +0000595 DISALLOW_COPY_AND_ASSIGN(MemoryStreamBase);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000596};
597
598// MemoryStream dynamically resizes to accomodate written data.
599
600class MemoryStream : public MemoryStreamBase {
601 public:
602 MemoryStream();
603 explicit MemoryStream(const char* data); // Calls SetData(data, strlen(data))
604 MemoryStream(const void* data, size_t length); // Calls SetData(data, length)
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000605 ~MemoryStream() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000606
607 void SetData(const void* data, size_t length);
608
609 protected:
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000610 StreamResult DoReserve(size_t size, int* error) override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000611 // Memory Streams are aligned for efficiency.
612 static const int kAlignment = 16;
613 char* buffer_alloc_;
614};
615
616// ExternalMemoryStream adapts an external memory buffer, so writes which would
617// extend past the end of the buffer will return end-of-stream.
618
619class ExternalMemoryStream : public MemoryStreamBase {
620 public:
621 ExternalMemoryStream();
622 ExternalMemoryStream(void* data, size_t length);
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000623 ~ExternalMemoryStream() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000624
625 void SetData(void* data, size_t length);
626};
627
628// FifoBuffer allows for efficient, thread-safe buffering of data between
629// writer and reader. As the data can wrap around the end of the buffer,
630// MemoryStreamBase can't help us here.
631
632class FifoBuffer : public StreamInterface {
633 public:
634 // Creates a FIFO buffer with the specified capacity.
635 explicit FifoBuffer(size_t length);
636 // Creates a FIFO buffer with the specified capacity and owner
637 FifoBuffer(size_t length, Thread* owner);
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000638 ~FifoBuffer() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000639 // Gets the amount of data currently readable from the buffer.
640 bool GetBuffered(size_t* data_len) const;
641 // Resizes the buffer to the specified capacity. Fails if data_length_ > size
642 bool SetCapacity(size_t length);
643
644 // Read into |buffer| with an offset from the current read position, offset
645 // is specified in number of bytes.
646 // This method doesn't adjust read position nor the number of available
647 // bytes, user has to call ConsumeReadData() to do this.
648 StreamResult ReadOffset(void* buffer, size_t bytes, size_t offset,
649 size_t* bytes_read);
650
651 // Write |buffer| with an offset from the current write position, offset is
652 // specified in number of bytes.
653 // This method doesn't adjust the number of buffered bytes, user has to call
654 // ConsumeWriteBuffer() to do this.
655 StreamResult WriteOffset(const void* buffer, size_t bytes, size_t offset,
656 size_t* bytes_written);
657
658 // StreamInterface methods
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000659 StreamState GetState() const override;
660 StreamResult Read(void* buffer,
661 size_t bytes,
662 size_t* bytes_read,
663 int* error) override;
664 StreamResult Write(const void* buffer,
665 size_t bytes,
666 size_t* bytes_written,
667 int* error) override;
668 void Close() override;
669 const void* GetReadData(size_t* data_len) override;
670 void ConsumeReadData(size_t used) override;
671 void* GetWriteBuffer(size_t* buf_len) override;
672 void ConsumeWriteBuffer(size_t used) override;
673 bool GetWriteRemaining(size_t* size) const override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000674
675 private:
676 // Helper method that implements ReadOffset. Caller must acquire a lock
677 // when calling this method.
678 StreamResult ReadOffsetLocked(void* buffer, size_t bytes, size_t offset,
679 size_t* bytes_read);
680
681 // Helper method that implements WriteOffset. Caller must acquire a lock
682 // when calling this method.
683 StreamResult WriteOffsetLocked(const void* buffer, size_t bytes,
684 size_t offset, size_t* bytes_written);
685
686 StreamState state_; // keeps the opened/closed state of the stream
687 scoped_ptr<char[]> buffer_; // the allocated buffer
688 size_t buffer_length_; // size of the allocated buffer
689 size_t data_length_; // amount of readable data in the buffer
690 size_t read_position_; // offset to the readable data
691 Thread* owner_; // stream callbacks are dispatched on this thread
692 mutable CriticalSection crit_; // object lock
Thiago Farinaae0f0ee2015-04-04 23:56:53 +0000693 DISALLOW_COPY_AND_ASSIGN(FifoBuffer);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000694};
695
696///////////////////////////////////////////////////////////////////////////////
697
698class LoggingAdapter : public StreamAdapterInterface {
699 public:
700 LoggingAdapter(StreamInterface* stream, LoggingSeverity level,
701 const std::string& label, bool hex_mode = false);
702
703 void set_label(const std::string& label);
704
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000705 StreamResult Read(void* buffer,
706 size_t buffer_len,
707 size_t* read,
708 int* error) override;
709 StreamResult Write(const void* data,
710 size_t data_len,
711 size_t* written,
712 int* error) override;
713 void Close() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000714
715 protected:
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000716 void OnEvent(StreamInterface* stream, int events, int err) override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000717
718 private:
719 LoggingSeverity level_;
720 std::string label_;
721 bool hex_mode_;
722 LogMultilineState lms_;
723
Thiago Farinaae0f0ee2015-04-04 23:56:53 +0000724 DISALLOW_COPY_AND_ASSIGN(LoggingAdapter);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000725};
726
727///////////////////////////////////////////////////////////////////////////////
728// StringStream - Reads/Writes to an external std::string
729///////////////////////////////////////////////////////////////////////////////
730
731class StringStream : public StreamInterface {
732 public:
733 explicit StringStream(std::string& str);
734 explicit StringStream(const std::string& str);
735
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000736 StreamState GetState() const override;
737 StreamResult Read(void* buffer,
738 size_t buffer_len,
739 size_t* read,
740 int* error) override;
741 StreamResult Write(const void* data,
742 size_t data_len,
743 size_t* written,
744 int* error) override;
745 void Close() override;
746 bool SetPosition(size_t position) override;
747 bool GetPosition(size_t* position) const override;
748 bool GetSize(size_t* size) const override;
749 bool GetAvailable(size_t* size) const override;
750 bool ReserveSize(size_t size) override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000751
752 private:
753 std::string& str_;
754 size_t read_pos_;
755 bool read_only_;
756};
757
758///////////////////////////////////////////////////////////////////////////////
759// StreamReference - A reference counting stream adapter
760///////////////////////////////////////////////////////////////////////////////
761
762// Keep in mind that the streams and adapters defined in this file are
763// not thread-safe, so this has limited uses.
764
765// A StreamRefCount holds the reference count and a pointer to the
766// wrapped stream. It deletes the wrapped stream when there are no
767// more references. We can then have multiple StreamReference
768// instances pointing to one StreamRefCount, all wrapping the same
769// stream.
770
771class StreamReference : public StreamAdapterInterface {
772 class StreamRefCount;
773 public:
774 // Constructor for the first reference to a stream
775 // Note: get more references through NewReference(). Use this
776 // constructor only once on a given stream.
777 explicit StreamReference(StreamInterface* stream);
778 StreamInterface* GetStream() { return stream(); }
779 StreamInterface* NewReference();
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000780 ~StreamReference() override;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000781
782 private:
783 class StreamRefCount {
784 public:
785 explicit StreamRefCount(StreamInterface* stream)
786 : stream_(stream), ref_count_(1) {
787 }
788 void AddReference() {
789 CritScope lock(&cs_);
790 ++ref_count_;
791 }
792 void Release() {
793 int ref_count;
794 { // Atomic ops would have been a better fit here.
795 CritScope lock(&cs_);
796 ref_count = --ref_count_;
797 }
798 if (ref_count == 0) {
799 delete stream_;
800 delete this;
801 }
802 }
803 private:
804 StreamInterface* stream_;
805 int ref_count_;
806 CriticalSection cs_;
Thiago Farinaae0f0ee2015-04-04 23:56:53 +0000807 DISALLOW_COPY_AND_ASSIGN(StreamRefCount);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000808 };
809
810 // Constructor for adding references
811 explicit StreamReference(StreamRefCount* stream_ref_count,
812 StreamInterface* stream);
813
814 StreamRefCount* stream_ref_count_;
Thiago Farinaae0f0ee2015-04-04 23:56:53 +0000815 DISALLOW_COPY_AND_ASSIGN(StreamReference);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000816};
817
818///////////////////////////////////////////////////////////////////////////////
819
820// Flow attempts to move bytes from source to sink via buffer of size
821// buffer_len. The function returns SR_SUCCESS when source reaches
822// end-of-stream (returns SR_EOS), and all the data has been written successful
823// to sink. Alternately, if source returns SR_BLOCK or SR_ERROR, or if sink
824// returns SR_BLOCK, SR_ERROR, or SR_EOS, then the function immediately returns
825// with the unexpected StreamResult value.
826// data_len is the length of the valid data in buffer. in case of error
827// this is the data that read from source but can't move to destination.
828// as a pass in parameter, it indicates data in buffer that should move to sink
829StreamResult Flow(StreamInterface* source,
830 char* buffer, size_t buffer_len,
831 StreamInterface* sink, size_t* data_len = NULL);
832
833///////////////////////////////////////////////////////////////////////////////
834
835} // namespace rtc
836
837#endif // WEBRTC_BASE_STREAM_H_