VLCEventManager.m 13 KB

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