VLCEventManager.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. /*****************************************************************************
  2. * VLCEventManager.m: VLCKit.framework VLCEventManager implementation
  3. *****************************************************************************
  4. * Copyright (C) 2007 Pierre d'Herbemont
  5. * Copyright (C) 2007 VLC authors and VideoLAN
  6. * $Id$
  7. *
  8. * Authors: Pierre d'Herbemont <pdherbemont # videolan.org>
  9. *
  10. * This program is free software; you can redistribute it and/or modify it
  11. * under the terms of the GNU Lesser General Public License as published by
  12. * the Free Software Foundation; either version 2.1 of the License, or
  13. * (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Lesser General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Lesser General Public License
  21. * along with this program; if not, write to the Free Software Foundation,
  22. * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
  23. *****************************************************************************/
  24. #import "VLCEventManager.h"
  25. #import <pthread.h>
  26. /**
  27. * Defines the type of interthread message on the queue.
  28. */
  29. typedef enum
  30. {
  31. VLCNotification, //< Standard NSNotification.
  32. VLCObjectMethodWithObjectArg, //< Method with an object argument.
  33. VLCObjectMethodWithArrayArg //< Method with an array argument.
  34. } message_type_t;
  35. /**
  36. * Data structured used to enqueue messages onto the queue.
  37. */
  38. @interface message_t : NSObject
  39. @property (nonatomic, strong) id target; //< Target object that should receive the message (retained until method is called).
  40. @property (nonatomic) SEL sel; //< A selector that identifies the message to be sent to the target.
  41. @property (nonatomic, copy) NSString * name; //< Name to be used for NSNotification
  42. @property (nonatomic, strong) id object; //< Object argument to pass to the target via the selector.
  43. @property (nonatomic) message_type_t type; //< Type of queued message.
  44. @end
  45. @implementation message_t
  46. - (BOOL)isEqual:(id)object
  47. {
  48. if (![object isKindOfClass:[message_t class]]) return NO;
  49. message_t *otherObject = object;
  50. BOOL notificationMatches =
  51. (otherObject.type == VLCNotification && [otherObject.name isEqualToString:self.name]) ||
  52. (otherObject.type == VLCObjectMethodWithArrayArg && [otherObject.object isEqual:self.object]) ||
  53. (otherObject.type == VLCObjectMethodWithObjectArg && [otherObject.object isEqual:self.object]);
  54. return [otherObject.target isEqual:_target] &&
  55. otherObject.sel == self.sel &&
  56. otherObject.type == self.type &&
  57. notificationMatches;
  58. }
  59. @end
  60. @interface VLCEventManager ()
  61. {
  62. NSMutableArray *_messageQueue; //< Holds a queue of messages.
  63. NSMutableArray *_pendingMessagesOnMainThread; //< Holds the message that are being posted on main thread.
  64. NSLock *_pendingMessagesLock;
  65. pthread_t _dispatcherThread; //< Thread responsible for dispatching messages.
  66. pthread_mutex_t _queueLock; //< Queue lock.
  67. pthread_cond_t _signalData; //< Data lock.
  68. }
  69. - (void)startEventLoop;
  70. - (void)callDelegateOfObjectAndSendNotificationWithArgs:(message_t *)message;
  71. - (void)callObjectMethodWithArgs:(message_t *)message;
  72. - (pthread_cond_t *)signalData;
  73. - (pthread_mutex_t *)queueLock;
  74. - (void)addMessageToHandleOnMainThread:(message_t *)message;
  75. @end
  76. /**
  77. * Provides a function for the main entry point for the dispatch thread. It dispatches any messages that is queued.
  78. * \param user_data Pointer to the VLCEventManager instance that instiated this thread.
  79. */
  80. static void * EventDispatcherMainLoop(void * user_data)
  81. {
  82. VLCEventManager * self = (__bridge VLCEventManager *)(user_data);
  83. [self startEventLoop];
  84. return NULL;
  85. }
  86. @implementation VLCEventManager
  87. + (id)sharedManager
  88. {
  89. static dispatch_once_t onceToken;
  90. static VLCEventManager *defaultManager = nil;
  91. dispatch_once(&onceToken, ^{
  92. defaultManager = [[VLCEventManager alloc] init];
  93. });
  94. return defaultManager;
  95. }
  96. - (void)dummy
  97. {
  98. /* Put Cocoa in multithreaded mode by calling a dummy function */
  99. }
  100. - (id)init
  101. {
  102. if (self = [super init]) {
  103. if (![NSThread isMultiThreaded]) {
  104. [NSThread detachNewThreadSelector:@selector(dummy) toTarget:self withObject:nil];
  105. NSAssert([NSThread isMultiThreaded], @"Can't put Cocoa in multithreaded mode");
  106. }
  107. _messageQueue = [NSMutableArray new];
  108. _pendingMessagesOnMainThread = [NSMutableArray new];
  109. _pendingMessagesLock = [[NSLock alloc] init];
  110. pthread_mutex_init(&_queueLock, NULL);
  111. pthread_cond_init(&_signalData, NULL);
  112. pthread_create(&_dispatcherThread, NULL, EventDispatcherMainLoop, (__bridge void *)(self));
  113. }
  114. return self;
  115. }
  116. - (void)dealloc
  117. {
  118. pthread_kill(_dispatcherThread, SIGKILL);
  119. pthread_join(_dispatcherThread, NULL);
  120. }
  121. #pragma mark -
  122. - (void)startEventLoop {
  123. for (;;) {
  124. @autoreleasepool {
  125. message_t * message, * message_newer = NULL;
  126. /* Wait for some data */
  127. /* Wait until we have something on the queue */
  128. pthread_mutex_lock([self queueLock]);
  129. while (_messageQueue.count <= 0)
  130. pthread_cond_wait([self signalData], [self queueLock]);
  131. /* Get the first object off the queue. */
  132. message = [_messageQueue lastObject]; // Released in 'call'
  133. [_messageQueue removeLastObject];
  134. /* Remove duplicate notifications (keep the newest one). */
  135. if (message.type == VLCNotification) {
  136. NSInteger last_match_msg = -1;
  137. for (NSInteger i = _messageQueue.count - 1; i >= 0; i--) {
  138. message_newer = _messageQueue[i];
  139. if (message_newer.type == VLCNotification &&
  140. message_newer.target == message.target &&
  141. [message_newer.name isEqualToString:message.name]) {
  142. if (last_match_msg >= 0) {
  143. [_messageQueue removeObjectAtIndex:(NSUInteger) last_match_msg];
  144. }
  145. last_match_msg = i;
  146. }
  147. }
  148. if (last_match_msg >= 0) {
  149. // newer notification detected, ignore current one
  150. pthread_mutex_unlock([self queueLock]);
  151. continue;
  152. }
  153. } else if (message.type == VLCObjectMethodWithArrayArg) {
  154. NSMutableArray * newArg = nil;
  155. /* Collapse messages that takes array arg by sending one bigger array */
  156. for (NSInteger i = [_messageQueue count] - 1; i >= 0; i--) {
  157. message_newer = _messageQueue[i];
  158. if (message_newer.type == VLCObjectMethodWithArrayArg &&
  159. message_newer.target == message.target &&
  160. message_newer.sel == message.sel) {
  161. if (!newArg) {
  162. newArg = [NSMutableArray arrayWithArray:message.object];
  163. }
  164. [newArg addObjectsFromArray:message_newer.object];
  165. [_messageQueue removeObjectAtIndex:(NSUInteger) i];
  166. }
  167. /* It shouldn be a good idea not to collapse event with other kind of event in-between.
  168. * This could be particulary problematic when the same object receive two related events
  169. * (for instance Added and Removed).
  170. * Ignore for now only if target is the same */
  171. else if (message_newer.target == message.target)
  172. break;
  173. }
  174. if (newArg)
  175. message.object = newArg;
  176. }
  177. [self addMessageToHandleOnMainThread:message];
  178. pthread_mutex_unlock([self queueLock]);
  179. if (message.type == VLCNotification)
  180. [self performSelectorOnMainThread:@selector(callDelegateOfObjectAndSendNotificationWithArgs:)
  181. withObject:message
  182. waitUntilDone: NO];
  183. else
  184. [self performSelectorOnMainThread:@selector(callObjectMethodWithArgs:)
  185. withObject:message
  186. waitUntilDone: YES];
  187. }
  188. /* Sleep a bit not to flood the interface */
  189. usleep(300);
  190. }
  191. }
  192. - (void)callOnMainThreadDelegateOfObject:(id)aTarget withDelegateMethod:(SEL)aSelector withNotificationName:(NSString *)aNotificationName
  193. {
  194. /* Don't send on main thread before this gets sorted out */
  195. @autoreleasepool {
  196. message_t *message = [message_t new];
  197. message.sel = aSelector;
  198. message.target = aTarget;
  199. message.name = aNotificationName;
  200. message.type = VLCNotification;
  201. pthread_mutex_lock([self queueLock]);
  202. [_messageQueue insertObject:message atIndex:0];
  203. pthread_cond_signal([self signalData]);
  204. pthread_mutex_unlock([self queueLock]);
  205. }
  206. }
  207. - (void)callOnMainThreadObject:(id)aTarget withMethod:(SEL)aSelector withArgumentAsObject:(id)arg
  208. {
  209. @autoreleasepool {
  210. message_t *message = [message_t new];
  211. message.sel = aSelector;
  212. message.target = aTarget;
  213. message.object = arg;
  214. message.type = [arg isKindOfClass:[NSArray class]] ? VLCObjectMethodWithArrayArg : VLCObjectMethodWithObjectArg;
  215. pthread_mutex_lock([self queueLock]);
  216. [_messageQueue insertObject:message atIndex:0];
  217. pthread_cond_signal([self signalData]);
  218. pthread_mutex_unlock([self queueLock]);
  219. }
  220. }
  221. - (void)cancelCallToObject:(id)target
  222. {
  223. // Remove all queued message
  224. pthread_mutex_lock([self queueLock]);
  225. [_pendingMessagesLock lock];
  226. // Keep a hold on the secondary objects and release them only AFTER we have released our locks to prevents deadlocks.
  227. // i.e. dealloc'ing a VLCMediaPlayer that has pending messages with its VLCMedia as message object,
  228. // and these references are the last ones to the VLCMedia, so releasing message->u.object would dealloc the VLCMedia which in
  229. // turn would call -cancelCallToObject, effectively causing a deadlock.
  230. NSMutableArray *secondaryObjects = [[NSMutableArray alloc] init];
  231. for (NSInteger i = _messageQueue.count - 1; i >= 0; i--) {
  232. message_t *message = _messageQueue[i];
  233. if (message.target == target) {
  234. if (message.object != nil)
  235. [secondaryObjects addObject:message.object];
  236. [_messageQueue removeObjectAtIndex:(NSUInteger) i];
  237. }
  238. }
  239. // Remove all pending messages
  240. NSMutableArray *messages = _pendingMessagesOnMainThread;
  241. // need to interate in reverse since we are removing objects
  242. for (NSInteger i = [messages count] - 1; i >= 0; i--) {
  243. message_t *message = messages[i];
  244. if (message.target == target) {
  245. if (message.object != nil)
  246. [secondaryObjects addObject:message.object];
  247. [messages removeObjectAtIndex:(NSUInteger) i];
  248. }
  249. }
  250. [_pendingMessagesLock unlock];
  251. pthread_mutex_unlock([self queueLock]);
  252. // secondaryObjects will be disposed of now, but just to make sure that ARC doesn't
  253. // dispose it earlier, play a little trick to keep it alive up to this point by calling a selector
  254. // keeping the objects alive until the mutex has been unlocked is crucial to preventing recursion+deadlock
  255. [secondaryObjects removeAllObjects];
  256. }
  257. - (void)addMessageToHandleOnMainThread:(message_t *)message
  258. {
  259. [_pendingMessagesLock lock];
  260. [_pendingMessagesOnMainThread addObject:message];
  261. [_pendingMessagesLock unlock];
  262. }
  263. - (BOOL)markMessageHandledOnMainThreadIfExists:(message_t *)message
  264. {
  265. [_pendingMessagesLock lock];
  266. BOOL cancelled = ![_pendingMessagesOnMainThread containsObject:message];
  267. if (!cancelled) {
  268. [_pendingMessagesOnMainThread removeObject:message];
  269. }
  270. [_pendingMessagesLock unlock];
  271. return !cancelled;
  272. }
  273. - (void)callDelegateOfObjectAndSendNotificationWithArgs:(message_t *)message
  274. {
  275. // Check that we were not cancelled, ie, target was released
  276. if ([self markMessageHandledOnMainThreadIfExists:message]) {
  277. id target = message.target;
  278. [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:message.object object:target]];
  279. id delegate = [target delegate];
  280. if ([delegate respondsToSelector:message.sel]) {
  281. void (*method)(id, SEL, id) = (void (*)(id, SEL, id)) [delegate methodForSelector:message.sel];
  282. method(delegate, message.sel, [NSNotification notificationWithName:message.object object:target]);
  283. }
  284. }
  285. }
  286. - (void)callObjectMethodWithArgs:(message_t *)message
  287. {
  288. // Check that we were not cancelled
  289. if ([self markMessageHandledOnMainThreadIfExists:message]) {
  290. void (*method)(id, SEL, id) = (void (*)(id, SEL, id))[message.target methodForSelector: message.sel];
  291. method(message.target, message.sel, message.object);
  292. }
  293. }
  294. - (pthread_cond_t *)signalData
  295. {
  296. return &_signalData;
  297. }
  298. - (pthread_mutex_t *)queueLock
  299. {
  300. return &_queueLock;
  301. }
  302. @end