VLCEventManager.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. if (!message)
  130. break;
  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't 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. dispatch_async(dispatch_get_main_queue(), ^{
  179. [self callDelegateOfObjectAndSendNotificationWithArgs:message];
  180. });
  181. } else {
  182. dispatch_sync(dispatch_get_main_queue(), ^{
  183. [self callObjectMethodWithArgs:message];
  184. });
  185. }
  186. }
  187. /* Sleep a bit not to flood the interface */
  188. usleep(300);
  189. }
  190. }
  191. - (void)callOnMainThreadDelegateOfObject:(id)aTarget withDelegateMethod:(SEL)aSelector withNotificationName:(NSString *)aNotificationName
  192. {
  193. /* Don't send on main thread before this gets sorted out */
  194. @autoreleasepool {
  195. message_t *message = [message_t new];
  196. message.sel = aSelector;
  197. message.target = aTarget;
  198. message.name = aNotificationName;
  199. message.type = VLCNotification;
  200. pthread_mutex_lock(&_queueLock);
  201. [_messageQueue insertObject:message atIndex:0];
  202. pthread_cond_signal(&_signalData);
  203. pthread_mutex_unlock(&_queueLock);
  204. }
  205. }
  206. - (void)callOnMainThreadObject:(id)aTarget withMethod:(SEL)aSelector withArgumentAsObject:(id)arg
  207. {
  208. @autoreleasepool {
  209. message_t *message = [message_t new];
  210. message.sel = aSelector;
  211. message.target = aTarget;
  212. message.object = arg;
  213. message.name = @"";
  214. message.type = [arg isKindOfClass:[NSArray class]] ? VLCObjectMethodWithArrayArg : VLCObjectMethodWithObjectArg;
  215. pthread_mutex_lock(&_queueLock);
  216. [_messageQueue insertObject:message atIndex:0];
  217. pthread_cond_signal(&_signalData);
  218. pthread_mutex_unlock(&_queueLock);
  219. }
  220. }
  221. - (void)cancelCallToObject:(id)target
  222. {
  223. // Remove all queued message
  224. pthread_mutex_lock(&_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(&_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. NSString *notificationName = message.name;
  278. id target = message.target;
  279. SEL targetSelector = message.sel;
  280. [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:notificationName object:target]];
  281. id delegate = [message.target delegate];
  282. if (!delegate || ![delegate respondsToSelector:targetSelector])
  283. return;
  284. void (*method)(id, SEL, id) = (void (*)(id, SEL, id))[delegate methodForSelector:targetSelector];
  285. method(delegate, targetSelector, [NSNotification notificationWithName:notificationName object:target]);
  286. }
  287. }
  288. - (void)callObjectMethodWithArgs:(message_t *)message
  289. {
  290. // Check that we were not cancelled
  291. if ([self markMessageHandledOnMainThreadIfExists:message]) {
  292. void (*method)(id, SEL, id) = (void (*)(id, SEL, id))[message.target methodForSelector: message.sel];
  293. if (message.target && message.sel)
  294. method(message.target, message.sel, message.object);
  295. }
  296. }
  297. @end