VLCEventManager.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. - (void)addMessageToHandleOnMainThread:(message_t *)message;
  73. @end
  74. /**
  75. * Provides a function for the main entry point for the dispatch thread. It dispatches any messages that is queued.
  76. * \param user_data Pointer to the VLCEventManager instance that instiated this thread.
  77. */
  78. static void * EventDispatcherMainLoop(void * user_data)
  79. {
  80. VLCEventManager * self = (__bridge VLCEventManager *)(user_data);
  81. [self startEventLoop];
  82. return NULL;
  83. }
  84. @implementation VLCEventManager
  85. + (id)sharedManager
  86. {
  87. static dispatch_once_t onceToken;
  88. static VLCEventManager *defaultManager = nil;
  89. dispatch_once(&onceToken, ^{
  90. defaultManager = [[VLCEventManager alloc] init];
  91. });
  92. return defaultManager;
  93. }
  94. - (void)dummy
  95. {
  96. /* Put Cocoa in multithreaded mode by calling a dummy function */
  97. }
  98. - (id)init
  99. {
  100. if (self = [super init]) {
  101. if (![NSThread isMultiThreaded]) {
  102. [NSThread detachNewThreadSelector:@selector(dummy) toTarget:self withObject:nil];
  103. NSAssert([NSThread isMultiThreaded], @"Can't put Cocoa in multithreaded mode");
  104. }
  105. _messageQueue = [NSMutableArray new];
  106. _pendingMessagesOnMainThread = [NSMutableArray new];
  107. _pendingMessagesLock = [[NSLock alloc] init];
  108. pthread_mutex_init(&_queueLock, NULL);
  109. pthread_cond_init(&_signalData, NULL);
  110. pthread_create(&_dispatcherThread, NULL, EventDispatcherMainLoop, (__bridge void *)(self));
  111. }
  112. return self;
  113. }
  114. - (void)dealloc
  115. {
  116. pthread_kill(_dispatcherThread, SIGKILL);
  117. pthread_join(_dispatcherThread, NULL);
  118. }
  119. #pragma mark -
  120. - (void)startEventLoop {
  121. for (;;) {
  122. @autoreleasepool {
  123. message_t * message, * message_newer = NULL;
  124. /* Wait for some data */
  125. /* Wait until we have something on the queue */
  126. pthread_mutex_lock(&_queueLock);
  127. while (_messageQueue.count <= 0)
  128. pthread_cond_wait(&_signalData, &_queueLock);
  129. /* Get the first object off the queue. */
  130. message = [_messageQueue lastObject]; // Released in 'call'
  131. [_messageQueue removeLastObject];
  132. /* Remove duplicate notifications (keep the newest one). */
  133. if (message.type == VLCNotification) {
  134. NSInteger last_match_msg = -1;
  135. for (NSInteger i = _messageQueue.count - 1; i >= 0; i--) {
  136. message_newer = _messageQueue[i];
  137. if (message_newer.type == VLCNotification &&
  138. message_newer.target == message.target &&
  139. [message_newer.name isEqualToString:message.name]) {
  140. if (last_match_msg >= 0) {
  141. [_messageQueue removeObjectAtIndex:(NSUInteger) last_match_msg];
  142. }
  143. last_match_msg = i;
  144. }
  145. }
  146. if (last_match_msg >= 0) {
  147. // newer notification detected, ignore current one
  148. pthread_mutex_unlock(&_queueLock);
  149. continue;
  150. }
  151. } else if (message.type == VLCObjectMethodWithArrayArg) {
  152. NSMutableArray * newArg = nil;
  153. /* Collapse messages that takes array arg by sending one bigger array */
  154. for (NSInteger i = [_messageQueue count] - 1; i >= 0; i--) {
  155. message_newer = _messageQueue[i];
  156. if (message_newer.type == VLCObjectMethodWithArrayArg &&
  157. message_newer.target == message.target &&
  158. message_newer.sel == message.sel) {
  159. if (!newArg) {
  160. newArg = [NSMutableArray arrayWithArray:message.object];
  161. }
  162. [newArg addObjectsFromArray:message_newer.object];
  163. [_messageQueue removeObjectAtIndex:(NSUInteger) i];
  164. }
  165. /* It shouldn be a good idea not to collapse event with other kind of event in-between.
  166. * This could be particulary problematic when the same object receive two related events
  167. * (for instance Added and Removed).
  168. * Ignore for now only if target is the same */
  169. else if (message_newer.target == message.target)
  170. break;
  171. }
  172. if (newArg)
  173. message.object = newArg;
  174. }
  175. [self addMessageToHandleOnMainThread:message];
  176. pthread_mutex_unlock(&_queueLock);
  177. if (message.type == VLCNotification)
  178. [self performSelectorOnMainThread:@selector(callDelegateOfObjectAndSendNotificationWithArgs:)
  179. withObject:message
  180. waitUntilDone: NO];
  181. else
  182. [self performSelectorOnMainThread:@selector(callObjectMethodWithArgs:)
  183. withObject:message
  184. waitUntilDone: YES];
  185. }
  186. /* Sleep a bit not to flood the interface */
  187. usleep(300);
  188. }
  189. }
  190. - (void)callOnMainThreadDelegateOfObject:(id)aTarget withDelegateMethod:(SEL)aSelector withNotificationName:(NSString *)aNotificationName
  191. {
  192. /* Don't send on main thread before this gets sorted out */
  193. @autoreleasepool {
  194. message_t *message = [message_t new];
  195. message.sel = aSelector;
  196. message.target = aTarget;
  197. message.name = aNotificationName;
  198. message.type = VLCNotification;
  199. pthread_mutex_lock(&_queueLock);
  200. [_messageQueue insertObject:message atIndex:0];
  201. pthread_cond_signal(&_signalData);
  202. pthread_mutex_unlock(&_queueLock);
  203. }
  204. }
  205. - (void)callOnMainThreadObject:(id)aTarget withMethod:(SEL)aSelector withArgumentAsObject:(id)arg
  206. {
  207. @autoreleasepool {
  208. message_t *message = [message_t new];
  209. message.sel = aSelector;
  210. message.target = aTarget;
  211. message.object = arg;
  212. message.type = [arg isKindOfClass:[NSArray class]] ? VLCObjectMethodWithArrayArg : VLCObjectMethodWithObjectArg;
  213. pthread_mutex_lock(&_queueLock);
  214. [_messageQueue insertObject:message atIndex:0];
  215. pthread_cond_signal(&_signalData);
  216. pthread_mutex_unlock(&_queueLock);
  217. }
  218. }
  219. - (void)cancelCallToObject:(id)target
  220. {
  221. // Remove all queued message
  222. pthread_mutex_lock(&_queueLock);
  223. [_pendingMessagesLock lock];
  224. // Keep a hold on the secondary objects and release them only AFTER we have released our locks to prevents deadlocks.
  225. // i.e. dealloc'ing a VLCMediaPlayer that has pending messages with its VLCMedia as message object,
  226. // and these references are the last ones to the VLCMedia, so releasing message->u.object would dealloc the VLCMedia which in
  227. // turn would call -cancelCallToObject, effectively causing a deadlock.
  228. NSMutableArray *secondaryObjects = [[NSMutableArray alloc] init];
  229. for (NSInteger i = _messageQueue.count - 1; i >= 0; i--) {
  230. message_t *message = _messageQueue[i];
  231. if (message.target == target) {
  232. if (message.object != nil)
  233. [secondaryObjects addObject:message.object];
  234. [_messageQueue removeObjectAtIndex:(NSUInteger) i];
  235. }
  236. }
  237. // Remove all pending messages
  238. NSMutableArray *messages = _pendingMessagesOnMainThread;
  239. // need to interate in reverse since we are removing objects
  240. for (NSInteger i = [messages count] - 1; i >= 0; i--) {
  241. message_t *message = messages[i];
  242. if (message.target == target) {
  243. if (message.object != nil)
  244. [secondaryObjects addObject:message.object];
  245. [messages removeObjectAtIndex:(NSUInteger) i];
  246. }
  247. }
  248. [_pendingMessagesLock unlock];
  249. pthread_mutex_unlock(&_queueLock);
  250. // secondaryObjects will be disposed of now, but just to make sure that ARC doesn't
  251. // dispose it earlier, play a little trick to keep it alive up to this point by calling a selector
  252. // keeping the objects alive until the mutex has been unlocked is crucial to preventing recursion+deadlock
  253. [secondaryObjects removeAllObjects];
  254. }
  255. - (void)addMessageToHandleOnMainThread:(message_t *)message
  256. {
  257. [_pendingMessagesLock lock];
  258. [_pendingMessagesOnMainThread addObject:message];
  259. [_pendingMessagesLock unlock];
  260. }
  261. - (BOOL)markMessageHandledOnMainThreadIfExists:(message_t *)message
  262. {
  263. [_pendingMessagesLock lock];
  264. BOOL cancelled = ![_pendingMessagesOnMainThread containsObject:message];
  265. if (!cancelled) {
  266. [_pendingMessagesOnMainThread removeObject:message];
  267. }
  268. [_pendingMessagesLock unlock];
  269. return !cancelled;
  270. }
  271. - (void)callDelegateOfObjectAndSendNotificationWithArgs:(message_t *)message
  272. {
  273. // Check that we were not cancelled, ie, target was released
  274. if ([self markMessageHandledOnMainThreadIfExists:message]) {
  275. id target = message.target;
  276. [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:message.object object:target]];
  277. id delegate = [target delegate];
  278. if ([delegate respondsToSelector:message.sel]) {
  279. void (*method)(id, SEL, id) = (void (*)(id, SEL, id)) [delegate methodForSelector:message.sel];
  280. method(delegate, message.sel, [NSNotification notificationWithName:message.object object:target]);
  281. }
  282. }
  283. }
  284. - (void)callObjectMethodWithArgs:(message_t *)message
  285. {
  286. // Check that we were not cancelled
  287. if ([self markMessageHandledOnMainThreadIfExists:message]) {
  288. void (*method)(id, SEL, id) = (void (*)(id, SEL, id))[message.target methodForSelector: message.sel];
  289. method(message.target, message.sel, message.object);
  290. }
  291. }
  292. @end