blob: 4aa96eb531f7c50ab6458e7eba703d38638c4b62 [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>
jbauch555604a2016-04-26 03:13:22 -070018#include <memory>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000019#include <queue>
20#include <vector>
21
22#include "webrtc/base/basictypes.h"
23#include "webrtc/base/constructormagic.h"
24#include "webrtc/base/criticalsection.h"
25#include "webrtc/base/messagehandler.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000026#include "webrtc/base/scoped_ref_ptr.h"
jbauch9ccedc32016-02-25 01:14:56 -080027#include "webrtc/base/sharedexclusivelock.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000028#include "webrtc/base/sigslot.h"
29#include "webrtc/base/socketserver.h"
30#include "webrtc/base/timeutils.h"
jbauch9ccedc32016-02-25 01:14:56 -080031#include "webrtc/base/thread_annotations.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000032
33namespace rtc {
34
35struct Message;
36class MessageQueue;
37
38// MessageQueueManager does cleanup of of message queues
39
40class MessageQueueManager {
41 public:
42 static void Add(MessageQueue *message_queue);
43 static void Remove(MessageQueue *message_queue);
44 static void Clear(MessageHandler *handler);
45
46 // For testing purposes, we expose whether or not the MessageQueueManager
47 // instance has been initialized. It has no other use relative to the rest of
48 // the functions of this class, which auto-initialize the underlying
49 // MessageQueueManager instance when necessary.
50 static bool IsInitialized();
51
52 private:
53 static MessageQueueManager* Instance();
54
55 MessageQueueManager();
56 ~MessageQueueManager();
57
58 void AddInternal(MessageQueue *message_queue);
59 void RemoveInternal(MessageQueue *message_queue);
60 void ClearInternal(MessageHandler *handler);
61
62 static MessageQueueManager* instance_;
henrike@webrtc.org99b41622014-05-21 20:42:17 +000063 // This list contains all live MessageQueues.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000064 std::vector<MessageQueue *> message_queues_;
65 CriticalSection crit_;
66};
67
68// Derive from this for specialized data
69// App manages lifetime, except when messages are purged
70
71class MessageData {
72 public:
73 MessageData() {}
74 virtual ~MessageData() {}
75};
76
77template <class T>
78class TypedMessageData : public MessageData {
79 public:
80 explicit TypedMessageData(const T& data) : data_(data) { }
81 const T& data() const { return data_; }
82 T& data() { return data_; }
83 private:
84 T data_;
85};
86
87// Like TypedMessageData, but for pointers that require a delete.
88template <class T>
89class ScopedMessageData : public MessageData {
90 public:
91 explicit ScopedMessageData(T* data) : data_(data) { }
jbauch555604a2016-04-26 03:13:22 -070092 const std::unique_ptr<T>& data() const { return data_; }
93 std::unique_ptr<T>& data() { return data_; }
94
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000095 private:
jbauch555604a2016-04-26 03:13:22 -070096 std::unique_ptr<T> data_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000097};
98
99// Like ScopedMessageData, but for reference counted pointers.
100template <class T>
101class ScopedRefMessageData : public MessageData {
102 public:
103 explicit ScopedRefMessageData(T* data) : data_(data) { }
104 const scoped_refptr<T>& data() const { return data_; }
105 scoped_refptr<T>& data() { return data_; }
106 private:
107 scoped_refptr<T> data_;
108};
109
110template<class T>
111inline MessageData* WrapMessageData(const T& data) {
112 return new TypedMessageData<T>(data);
113}
114
115template<class T>
116inline const T& UseMessageData(MessageData* data) {
117 return static_cast< TypedMessageData<T>* >(data)->data();
118}
119
120template<class T>
121class DisposeData : public MessageData {
122 public:
123 explicit DisposeData(T* data) : data_(data) { }
124 virtual ~DisposeData() { delete data_; }
125 private:
126 T* data_;
127};
128
Peter Boström0c4e06b2015-10-07 12:23:21 +0200129const uint32_t MQID_ANY = static_cast<uint32_t>(-1);
130const uint32_t MQID_DISPOSE = static_cast<uint32_t>(-2);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000131
132// No destructor
133
134struct Message {
135 Message() {
136 memset(this, 0, sizeof(*this));
137 }
Peter Boström0c4e06b2015-10-07 12:23:21 +0200138 inline bool Match(MessageHandler* handler, uint32_t id) const {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000139 return (handler == NULL || handler == phandler)
140 && (id == MQID_ANY || id == message_id);
141 }
142 MessageHandler *phandler;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200143 uint32_t message_id;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000144 MessageData *pdata;
Honghai Zhang82d78622016-05-06 11:29:15 -0700145 int64_t ts_sensitive;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000146};
147
148typedef std::list<Message> MessageList;
149
150// DelayedMessage goes into a priority queue, sorted by trigger time. Messages
151// with the same trigger time are processed in num_ (FIFO) order.
152
153class DelayedMessage {
154 public:
Honghai Zhang82d78622016-05-06 11:29:15 -0700155 DelayedMessage(int delay, int64_t trigger, uint32_t num, const Message& msg)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200156 : cmsDelay_(delay), msTrigger_(trigger), num_(num), msg_(msg) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000157
158 bool operator< (const DelayedMessage& dmsg) const {
159 return (dmsg.msTrigger_ < msTrigger_)
160 || ((dmsg.msTrigger_ == msTrigger_) && (dmsg.num_ < num_));
161 }
162
163 int cmsDelay_; // for debugging
Honghai Zhang82d78622016-05-06 11:29:15 -0700164 int64_t msTrigger_;
Peter Boström0c4e06b2015-10-07 12:23:21 +0200165 uint32_t num_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000166 Message msg_;
167};
168
169class MessageQueue {
170 public:
andresp@webrtc.org53d90122015-02-09 14:19:09 +0000171 static const int kForever = -1;
172
jbauch25d1f282016-02-05 00:25:02 -0800173 // Create a new MessageQueue and optionally assign it to the passed
174 // SocketServer. Subclasses that override Clear should pass false for
175 // init_queue and call DoInit() from their constructor to prevent races
176 // with the MessageQueueManager using the object while the vtable is still
177 // being created.
danilchapbebf54c2016-04-28 01:32:48 -0700178 MessageQueue(SocketServer* ss, bool init_queue);
179 MessageQueue(std::unique_ptr<SocketServer> ss, bool init_queue);
jbauch25d1f282016-02-05 00:25:02 -0800180
181 // NOTE: SUBCLASSES OF MessageQueue THAT OVERRIDE Clear MUST CALL
182 // DoDestroy() IN THEIR DESTRUCTORS! This is required to avoid a data race
183 // between the destructor modifying the vtable, and the MessageQueueManager
184 // calling Clear on the object from a different thread.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000185 virtual ~MessageQueue();
186
jbauch9ccedc32016-02-25 01:14:56 -0800187 SocketServer* socketserver();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000188 void set_socketserver(SocketServer* ss);
189
190 // Note: The behavior of MessageQueue has changed. When a MQ is stopped,
191 // futher Posts and Sends will fail. However, any pending Sends and *ready*
192 // Posts (as opposed to unexpired delayed Posts) will be delivered before
193 // Get (or Peek) returns false. By guaranteeing delivery of those messages,
194 // we eliminate the race condition when an MessageHandler and MessageQueue
195 // may be destroyed independently of each other.
196 virtual void Quit();
197 virtual bool IsQuitting();
198 virtual void Restart();
199
200 // Get() will process I/O until:
201 // 1) A message is available (returns true)
202 // 2) cmsWait seconds have elapsed (returns false)
203 // 3) Stop() is called (returns false)
204 virtual bool Get(Message *pmsg, int cmsWait = kForever,
205 bool process_io = true);
206 virtual bool Peek(Message *pmsg, int cmsWait = 0);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200207 virtual void Post(MessageHandler* phandler,
208 uint32_t id = 0,
209 MessageData* pdata = NULL,
210 bool time_sensitive = false);
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000211 virtual void PostDelayed(int cmsDelay,
212 MessageHandler* phandler,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200213 uint32_t id = 0,
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000214 MessageData* pdata = NULL);
Honghai Zhang82d78622016-05-06 11:29:15 -0700215 virtual void PostAt(int64_t tstamp,
216 MessageHandler* phandler,
217 uint32_t id = 0,
218 MessageData* pdata = NULL);
219 // TODO(honghaiz): Remove this when all the dependencies are removed.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200220 virtual void PostAt(uint32_t tstamp,
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000221 MessageHandler* phandler,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200222 uint32_t id = 0,
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000223 MessageData* pdata = NULL);
Peter Boström0c4e06b2015-10-07 12:23:21 +0200224 virtual void Clear(MessageHandler* phandler,
225 uint32_t id = MQID_ANY,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000226 MessageList* removed = NULL);
227 virtual void Dispatch(Message *pmsg);
228 virtual void ReceiveSends();
229
230 // Amount of time until the next message can be retrieved
231 virtual int GetDelay();
232
233 bool empty() const { return size() == 0u; }
234 size_t size() const {
235 CritScope cs(&crit_); // msgq_.size() is not thread safe.
236 return msgq_.size() + dmsgq_.size() + (fPeekKeep_ ? 1u : 0u);
237 }
238
239 // Internally posts a message which causes the doomed object to be deleted
240 template<class T> void Dispose(T* doomed) {
241 if (doomed) {
242 Post(NULL, MQID_DISPOSE, new DisposeData<T>(doomed));
243 }
244 }
245
246 // When this signal is sent out, any references to this queue should
247 // no longer be used.
248 sigslot::signal0<> SignalQueueDestroyed;
249
250 protected:
251 class PriorityQueue : public std::priority_queue<DelayedMessage> {
252 public:
253 container_type& container() { return c; }
254 void reheap() { make_heap(c.begin(), c.end(), comp); }
255 };
256
Peter Boström0c4e06b2015-10-07 12:23:21 +0200257 void DoDelayPost(int cmsDelay,
Honghai Zhang82d78622016-05-06 11:29:15 -0700258 int64_t tstamp,
Peter Boström0c4e06b2015-10-07 12:23:21 +0200259 MessageHandler* phandler,
260 uint32_t id,
261 MessageData* pdata);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000262
jbauch25d1f282016-02-05 00:25:02 -0800263 // Perform initialization, subclasses must call this from their constructor
264 // if false was passed as init_queue to the MessageQueue constructor.
265 void DoInit();
266
267 // Perform cleanup, subclasses that override Clear must call this from the
268 // destructor.
269 void DoDestroy();
270
jbauch9ccedc32016-02-25 01:14:56 -0800271 void WakeUpSocketServer();
272
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000273 bool fStop_;
274 bool fPeekKeep_;
275 Message msgPeek_;
jbauch9ccedc32016-02-25 01:14:56 -0800276 MessageList msgq_ GUARDED_BY(crit_);
277 PriorityQueue dmsgq_ GUARDED_BY(crit_);
278 uint32_t dmsgq_next_num_ GUARDED_BY(crit_);
pbos5ad935c2016-01-25 03:52:44 -0800279 CriticalSection crit_;
jbauch25d1f282016-02-05 00:25:02 -0800280 bool fInitialized_;
281 bool fDestroyed_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000282
283 private:
danilchapbebf54c2016-04-28 01:32:48 -0700284 // The SocketServer might not be owned by MessageQueue.
jbauch9ccedc32016-02-25 01:14:56 -0800285 SocketServer* ss_ GUARDED_BY(ss_lock_);
danilchapbebf54c2016-04-28 01:32:48 -0700286 // Used if SocketServer ownership lies with |this|.
287 std::unique_ptr<SocketServer> own_ss_;
jbauch9ccedc32016-02-25 01:14:56 -0800288 SharedExclusiveLock ss_lock_;
289
danilchapbebf54c2016-04-28 01:32:48 -0700290 RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(MessageQueue);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000291};
292
293} // namespace rtc
294
295#endif // WEBRTC_BASE_MESSAGEQUEUE_H_