blob: a7991a8923ad407c216c63542445077df50d2896 [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_MESSAGEQUEUE_H_
12#define WEBRTC_BASE_MESSAGEQUEUE_H_
13
14#include <string.h>
15
16#include <algorithm>
17#include <list>
18#include <queue>
19#include <vector>
20
21#include "webrtc/base/basictypes.h"
22#include "webrtc/base/constructormagic.h"
23#include "webrtc/base/criticalsection.h"
24#include "webrtc/base/messagehandler.h"
25#include "webrtc/base/scoped_ptr.h"
26#include "webrtc/base/scoped_ref_ptr.h"
27#include "webrtc/base/sigslot.h"
28#include "webrtc/base/socketserver.h"
29#include "webrtc/base/timeutils.h"
30
31namespace rtc {
32
33struct Message;
34class MessageQueue;
35
36// MessageQueueManager does cleanup of of message queues
37
38class MessageQueueManager {
39 public:
40 static void Add(MessageQueue *message_queue);
41 static void Remove(MessageQueue *message_queue);
42 static void Clear(MessageHandler *handler);
43
44 // For testing purposes, we expose whether or not the MessageQueueManager
45 // instance has been initialized. It has no other use relative to the rest of
46 // the functions of this class, which auto-initialize the underlying
47 // MessageQueueManager instance when necessary.
48 static bool IsInitialized();
49
50 private:
51 static MessageQueueManager* Instance();
52
53 MessageQueueManager();
54 ~MessageQueueManager();
55
56 void AddInternal(MessageQueue *message_queue);
57 void RemoveInternal(MessageQueue *message_queue);
58 void ClearInternal(MessageHandler *handler);
59
60 static MessageQueueManager* instance_;
henrike@webrtc.org99b41622014-05-21 20:42:17 +000061 // This list contains all live MessageQueues.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000062 std::vector<MessageQueue *> message_queues_;
63 CriticalSection crit_;
64};
65
66// Derive from this for specialized data
67// App manages lifetime, except when messages are purged
68
69class MessageData {
70 public:
71 MessageData() {}
72 virtual ~MessageData() {}
73};
74
75template <class T>
76class TypedMessageData : public MessageData {
77 public:
78 explicit TypedMessageData(const T& data) : data_(data) { }
79 const T& data() const { return data_; }
80 T& data() { return data_; }
81 private:
82 T data_;
83};
84
85// Like TypedMessageData, but for pointers that require a delete.
86template <class T>
87class ScopedMessageData : public MessageData {
88 public:
89 explicit ScopedMessageData(T* data) : data_(data) { }
90 const scoped_ptr<T>& data() const { return data_; }
91 scoped_ptr<T>& data() { return data_; }
92 private:
93 scoped_ptr<T> data_;
94};
95
96// Like ScopedMessageData, but for reference counted pointers.
97template <class T>
98class ScopedRefMessageData : public MessageData {
99 public:
100 explicit ScopedRefMessageData(T* data) : data_(data) { }
101 const scoped_refptr<T>& data() const { return data_; }
102 scoped_refptr<T>& data() { return data_; }
103 private:
104 scoped_refptr<T> data_;
105};
106
107template<class T>
108inline MessageData* WrapMessageData(const T& data) {
109 return new TypedMessageData<T>(data);
110}
111
112template<class T>
113inline const T& UseMessageData(MessageData* data) {
114 return static_cast< TypedMessageData<T>* >(data)->data();
115}
116
117template<class T>
118class DisposeData : public MessageData {
119 public:
120 explicit DisposeData(T* data) : data_(data) { }
121 virtual ~DisposeData() { delete data_; }
122 private:
123 T* data_;
124};
125
Peter Boström0c4e06b2015-10-07 12:23:21 +0200126const uint32_t MQID_ANY = static_cast<uint32_t>(-1);
127const uint32_t MQID_DISPOSE = static_cast<uint32_t>(-2);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000128
129// No destructor
130
131struct Message {
132 Message() {
133 memset(this, 0, sizeof(*this));
134 }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200135 inline bool Match(MessageHandler* handler, uint32_t id) const {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000136 return (handler == NULL || handler == phandler)
137 && (id == MQID_ANY || id == message_id);
138 }
139 MessageHandler *phandler;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200140 uint32_t message_id;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000141 MessageData *pdata;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200142 uint32_t ts_sensitive;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000143};
144
145typedef std::list<Message> MessageList;
146
147// DelayedMessage goes into a priority queue, sorted by trigger time. Messages
148// with the same trigger time are processed in num_ (FIFO) order.
149
150class DelayedMessage {
151 public:
Peter Boström0c4e06b2015-10-07 12:23:21 +0200152 DelayedMessage(int delay, uint32_t trigger, uint32_t num, const Message& msg)
153 : cmsDelay_(delay), msTrigger_(trigger), num_(num), msg_(msg) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000154
155 bool operator< (const DelayedMessage& dmsg) const {
156 return (dmsg.msTrigger_ < msTrigger_)
157 || ((dmsg.msTrigger_ == msTrigger_) && (dmsg.num_ < num_));
158 }
159
160 int cmsDelay_; // for debugging
Peter Boström0c4e06b2015-10-07 12:23:21 +0200161 uint32_t msTrigger_;
162 uint32_t num_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000163 Message msg_;
164};
165
166class MessageQueue {
167 public:
andresp@webrtc.org53d90122015-02-09 14:19:09 +0000168 static const int kForever = -1;
169
jbauch25d1f282016-02-05 00:25:02 -0800170 // Create a new MessageQueue and optionally assign it to the passed
171 // SocketServer. Subclasses that override Clear should pass false for
172 // init_queue and call DoInit() from their constructor to prevent races
173 // with the MessageQueueManager using the object while the vtable is still
174 // being created.
175 explicit MessageQueue(SocketServer* ss = NULL,
176 bool init_queue = true);
177
178 // NOTE: SUBCLASSES OF MessageQueue THAT OVERRIDE Clear MUST CALL
179 // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race
180 // between the destructor modifying the vtable, and the MessageQueueManager
181 // calling Clear on the object from a different thread.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000182 virtual ~MessageQueue();
183
jbauch9674d7c2016-02-19 07:16:16 -0800184 SocketServer* socketserver() { return ss_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000185 void set_socketserver(SocketServer* ss);
186
187 // Note: The behavior of MessageQueue has changed. When a MQ is stopped,
188 // futher Posts and Sends will fail. However, any pending Sends and *ready*
189 // Posts (as opposed to unexpired delayed Posts) will be delivered before
190 // Get (or Peek) returns false. By guaranteeing delivery of those messages,
191 // we eliminate the race condition when an MessageHandler and MessageQueue
192 // may be destroyed independently of each other.
193 virtual void Quit();
194 virtual bool IsQuitting();
195 virtual void Restart();
196
197 // Get() will process I/O until:
198 // 1) A message is available (returns true)
199 // 2) cmsWait seconds have elapsed (returns false)
200 // 3) Stop() is called (returns false)
201 virtual bool Get(Message *pmsg, int cmsWait = kForever,
202 bool process_io = true);
203 virtual bool Peek(Message *pmsg, int cmsWait = 0);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200204 virtual void Post(MessageHandler* phandler,
205 uint32_t id = 0,
206 MessageData* pdata = NULL,
207 bool time_sensitive = false);
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000208 virtual void PostDelayed(int cmsDelay,
209 MessageHandler* phandler,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200210 uint32_t id = 0,
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000211 MessageData* pdata = NULL);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200212 virtual void PostAt(uint32_t tstamp,
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000213 MessageHandler* phandler,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200214 uint32_t id = 0,
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000215 MessageData* pdata = NULL);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200216 virtual void Clear(MessageHandler* phandler,
217 uint32_t id = MQID_ANY,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000218 MessageList* removed = NULL);
219 virtual void Dispatch(Message *pmsg);
220 virtual void ReceiveSends();
221
222 // Amount of time until the next message can be retrieved
223 virtual int GetDelay();
224
225 bool empty() const { return size() == 0u; }
226 size_t size() const {
227 CritScope cs(&crit_); // msgq_.size() is not thread safe.
228 return msgq_.size() + dmsgq_.size() + (fPeekKeep_ ? 1u : 0u);
229 }
230
231 // Internally posts a message which causes the doomed object to be deleted
232 template<class T> void Dispose(T* doomed) {
233 if (doomed) {
234 Post(NULL, MQID_DISPOSE, new DisposeData<T>(doomed));
235 }
236 }
237
238 // When this signal is sent out, any references to this queue should
239 // no longer be used.
240 sigslot::signal0<> SignalQueueDestroyed;
241
242 protected:
243 class PriorityQueue : public std::priority_queue<DelayedMessage> {
244 public:
245 container_type& container() { return c; }
246 void reheap() { make_heap(c.begin(), c.end(), comp); }
247 };
248
Peter Boström0c4e06b2015-10-07 12:23:21 +0200249 void DoDelayPost(int cmsDelay,
250 uint32_t tstamp,
251 MessageHandler* phandler,
252 uint32_t id,
253 MessageData* pdata);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000254
jbauch25d1f282016-02-05 00:25:02 -0800255 // Perform initialization, subclasses must call this from their constructor
256 // if false was passed as init_queue to the MessageQueue constructor.
257 void DoInit();
258
259 // Perform cleanup, subclasses that override Clear must call this from the
260 // destructor.
261 void DoDestroy();
262
jbauch9674d7c2016-02-19 07:16:16 -0800263 // The SocketServer is not owned by MessageQueue.
264 SocketServer* ss_;
265 // If a server isn't supplied in the constructor, use this one.
266 scoped_ptr<SocketServer> default_ss_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000267 bool fStop_;
268 bool fPeekKeep_;
269 Message msgPeek_;
jbauch9674d7c2016-02-19 07:16:16 -0800270 MessageList msgq_;
271 PriorityQueue dmsgq_;
272 uint32_t dmsgq_next_num_;
pbos5ad935c2016-01-25 03:52:44 -0800273 CriticalSection crit_;
jbauch25d1f282016-02-05 00:25:02 -0800274 bool fInitialized_;
275 bool fDestroyed_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000276
277 private:
henrikg3c089d72015-09-16 05:37:44 -0700278 RTC_DISALLOW_COPY_AND_ASSIGN(MessageQueue);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000279};
280
281} // namespace rtc
282
283#endif // WEBRTC_BASE_MESSAGEQUEUE_H_