Mac OS X ambilight
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AppDelegate.m 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. //
  2. // AppDelegate.m
  3. // DisplayBacklight
  4. //
  5. // Created by Thomas Buck on 21.12.15.
  6. // Copyright © 2015 xythobuz. All rights reserved.
  7. //
  8. #import "AppDelegate.h"
  9. #import "Serial.h"
  10. #import "Screenshot.h"
  11. // ----------------------- Config starts here -----------------------
  12. // The idea behind this algorithm is very simple. It assumes that each LED strand
  13. // follows one edge of one of your displays. So one of the two coordinates should
  14. // always be zero or the width / height of your display.
  15. // Define the amount of LEDs in your strip here
  16. #define LED_COUNT 156
  17. // This defines how large the averaging-boxes should be in the dimension perpendicular
  18. // to the strand. So eg. for a bottom strand, how high the box should be in px.
  19. #define COLOR_AVERAGE_OTHER_DIMENSION_SIZE 100
  20. // Identify your displays here. Currently they're only distinguished by their resolution.
  21. // The ID will be the index in the list, so the first entry is display 0 and so on.
  22. struct DisplayAssignment displays[] = {
  23. { 1920, 1080 },
  24. { 900, 1600 }
  25. };
  26. // This defines the orientation and placement of your strands and is the most important part.
  27. // It begins with the LED IDs this strand includes, starting with ID 0 up to LED_COUNT - 1.
  28. // The second item is the length of this strip, as in the count of LEDs in it.
  29. // The third item is the display ID, defined by the previous struct.
  30. // The fourth and fifth items are the starting X and Y coordinates of the strand.
  31. // As described above, one should always be zero or the display width / height.
  32. // The sixth element is the direction the strand goes (no diagonals supported yet).
  33. // The last element is the size of the averaging-box for each LED, moving with the strand.
  34. // So, if your strand contains 33 LEDs and spans 1920 pixels, this should be (1920 / 33).
  35. // By default you can always use (length in pixel / LED count) for the last item, except
  36. // if your strand does not span the whole length of this screen edge.
  37. struct LEDStrand strands[] = {
  38. { 0, 33, 0, 1920, 1080, DIR_LEFT, 1920 / 33 },
  39. { 33, 19, 0, 0, 1080, DIR_UP, 1080 / 19 },
  40. { 52, 33, 0, 0, 0, DIR_RIGHT, 1920 / 33 },
  41. { 85, 5, 1, 0, 250, DIR_UP, 250 / 5 },
  42. { 90, 17, 1, 0, 0, DIR_RIGHT, 900 / 17 },
  43. { 107, 28, 1, 900, 0, DIR_DOWN, 1600 / 28 },
  44. { 135, 17, 1, 900, 1600, DIR_LEFT, 900 / 17 },
  45. { 152, 4, 1, 0, 1600, DIR_UP, 180 / 4 }
  46. };
  47. // This defines the update-speed of the Ambilight, in seconds.
  48. // With a baudrate of 115200 and 156 LEDs and 14-bytes Magic-Word,
  49. // theoretically you could transmit:
  50. // 115200 / (14 + (156 * 3)) * 8 =~ 30 Frames per Second
  51. // Inserting (1.0 / 30.0) here would try to reach these 30FPS,
  52. // but will probably cause high CPU-Usage.
  53. // (Run-Time of the algorithm is ignored here, so real speed will be
  54. // slightly lower.)
  55. #define DISPLAY_DELAY (1.0 / 30.0)
  56. // How many pixels to skip when calculating the average color.
  57. // Slightly increases performance and doesn't really alter the result.
  58. #define AVERAGE_PIXEL_SKIP 2
  59. // Magic identifying string used to differntiate start of packets.
  60. // Has to be the same here and in the Arduino Sketch.
  61. #define MAGIC_WORD @"xythobuzRGBled"
  62. // These are the values stored persistently in the preferences
  63. #define PREF_SERIAL_PORT @"SerialPort"
  64. #define PREF_BRIGHTNESS @"Brightness"
  65. #define PREF_TURNED_ON @"IsEnabled"
  66. // If this is defined it will print the FPS every DEBUG_PRINT_FPS seconds
  67. //#define DEBUG_PRINT_FPS 10
  68. // ------------------------ Config ends here ------------------------
  69. @interface AppDelegate ()
  70. @property (weak) IBOutlet NSMenu *statusMenu;
  71. @property (weak) IBOutlet NSMenu *menuPorts;
  72. @property (weak) IBOutlet NSMenuItem *buttonAmbilight;
  73. @property (weak) IBOutlet NSMenuItem *brightnessItem;
  74. @property (weak) IBOutlet NSSlider *brightnessSlider;
  75. @property (weak) IBOutlet NSMenuItem *brightnessLabel;
  76. @property (strong) NSStatusItem *statusItem;
  77. @property (strong) NSImage *statusImage;
  78. @property (strong) NSTimer *timer;
  79. @property (strong) Serial *serial;
  80. @property (strong) NSArray *lastDisplayIDs;
  81. @property (assign) BOOL restartAmbilight;
  82. @end
  83. @implementation AppDelegate
  84. @synthesize statusMenu, application;
  85. @synthesize menuPorts, buttonAmbilight;
  86. @synthesize brightnessItem, brightnessSlider, brightnessLabel;
  87. @synthesize statusItem, statusImage, lastDisplayIDs;
  88. @synthesize timer, serial, restartAmbilight;
  89. - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
  90. serial = [[Serial alloc] init];
  91. timer = nil;
  92. restartAmbilight = NO;
  93. // Set default configuration values
  94. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  95. NSMutableDictionary *appDefaults = [NSMutableDictionary dictionaryWithObject:@"" forKey:PREF_SERIAL_PORT];
  96. [appDefaults setObject:[NSNumber numberWithFloat:50.0] forKey:PREF_BRIGHTNESS];
  97. [appDefaults setObject:[NSNumber numberWithBool:NO] forKey:PREF_TURNED_ON];
  98. [store registerDefaults:appDefaults];
  99. [store synchronize];
  100. // Load existing configuration values
  101. NSString *savedPort = [store stringForKey:PREF_SERIAL_PORT];
  102. float brightness = [store floatForKey:PREF_BRIGHTNESS];
  103. BOOL ambilightIsOn = [store boolForKey:PREF_TURNED_ON];
  104. // Prepare status bar menu
  105. statusImage = [NSImage imageNamed:@"MenuIcon"];
  106. statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
  107. [statusImage setTemplate:YES];
  108. [statusItem setImage:statusImage];
  109. [statusItem setMenu:statusMenu];
  110. // Prepare brightness menu
  111. brightnessItem.view = brightnessSlider;
  112. [brightnessSlider setFloatValue:brightness];
  113. [brightnessLabel setTitle:[NSString stringWithFormat:@"Value: %.0f%%", brightness]];
  114. // Prepare serial port menu
  115. BOOL foundPort = NO;
  116. NSArray *ports = [Serial listSerialPorts];
  117. if ([ports count] > 0) {
  118. [menuPorts removeAllItems];
  119. for (int i = 0; i < [ports count]; i++) {
  120. // Add Menu Item for this port
  121. NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:[ports objectAtIndex:i] action:@selector(selectedSerialPort:) keyEquivalent:@""];
  122. [menuPorts addItem:item];
  123. // Set Enabled if it was used the last time
  124. if ((savedPort != nil) && [[ports objectAtIndex:i] isEqualToString:savedPort]) {
  125. // Try to open serial port
  126. [serial setPortName:savedPort];
  127. if (![serial openPort]) {
  128. foundPort = YES;
  129. [[menuPorts itemAtIndex:i] setState:NSOnState];
  130. }
  131. }
  132. }
  133. if (!foundPort) {
  134. // I'm using a cheap chinese Arduino Nano clone with a CH340 chipset.
  135. // This driver creates device-files in /dev/cu.* that don't correspond
  136. // to the chip-id and change every time the adapter is re-enumerated.
  137. // That means we may have to try and find the device again after the
  138. // stored name does no longer exist. In this case, we simply try the first
  139. // device that starts with /dev/cu.wchusbserial*...
  140. for (int i = 0; i < [ports count]; i++) {
  141. if ([[ports objectAtIndex:i] hasPrefix:@"/dev/cu.wchusbserial"]) {
  142. // Try to open serial port
  143. [serial setPortName:savedPort];
  144. if (![serial openPort]) {
  145. [[menuPorts itemAtIndex:i] setState:NSOnState];
  146. // Reattempt next matching device when opening this one fails.
  147. break;
  148. }
  149. }
  150. }
  151. }
  152. }
  153. [Screenshot init:self];
  154. lastDisplayIDs = [Screenshot listDisplays];
  155. if (ambilightIsOn) {
  156. timer = [NSTimer scheduledTimerWithTimeInterval:DISPLAY_DELAY target:self selector:@selector(visualizeDisplay:) userInfo:nil repeats:NO];
  157. [buttonAmbilight setState:NSOnState];
  158. }
  159. }
  160. - (void)applicationWillTerminate:(NSNotification *)aNotification {
  161. // Stop previous timer setting
  162. if (timer != nil) {
  163. [timer invalidate];
  164. timer = nil;
  165. }
  166. // Remove display callback
  167. [Screenshot close:self];
  168. // Turn off all lights if possible
  169. if ([serial isOpen]) {
  170. [self sendNullFrame];
  171. [serial closePort];
  172. }
  173. }
  174. - (IBAction)relistSerialPorts:(id)sender {
  175. // Refill port list
  176. NSArray *ports = [Serial listSerialPorts];
  177. [menuPorts removeAllItems];
  178. for (int i = 0; i < [ports count]; i++) {
  179. // Add Menu Item for this port
  180. NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:[ports objectAtIndex:i] action:@selector(selectedSerialPort:) keyEquivalent:@""];
  181. [menuPorts addItem:item];
  182. // Mark it if it is currently open
  183. if ([serial isOpen]) {
  184. if ([[ports objectAtIndex:i] isEqualToString:[serial portName]]) {
  185. [[menuPorts itemAtIndex:i] setState:NSOnState];
  186. }
  187. }
  188. }
  189. }
  190. - (void)selectedSerialPort:(NSMenuItem *)source {
  191. // Store selection for next start-up
  192. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  193. [store setObject:[source title] forKey:PREF_SERIAL_PORT];
  194. [store synchronize];
  195. // De-select all other ports
  196. for (int i = 0; i < [menuPorts numberOfItems]; i++) {
  197. [[menuPorts itemAtIndex:i] setState:NSOffState];
  198. }
  199. // Select only the current port
  200. [source setState:NSOnState];
  201. // Close previously opened port, if any
  202. if ([serial isOpen]) {
  203. [serial closePort];
  204. }
  205. // Stop previous timer setting
  206. if (timer != nil) {
  207. [timer invalidate];
  208. timer = nil;
  209. }
  210. // Turn off ambilight button
  211. [buttonAmbilight setState:NSOffState];
  212. // Try to open selected port
  213. [serial setPortName:[source title]];
  214. if ([serial openPort] != 0) {
  215. [source setState:NSOffState];
  216. }
  217. }
  218. - (IBAction)toggleAmbilight:(NSMenuItem *)sender {
  219. if ([sender state] == NSOnState) {
  220. [sender setState:NSOffState];
  221. // Stop previous timer setting
  222. if (timer != nil) {
  223. [timer invalidate];
  224. timer = nil;
  225. }
  226. [self sendNullFrame];
  227. // Store state
  228. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  229. [store setObject:[NSNumber numberWithBool:NO] forKey:PREF_TURNED_ON];
  230. [store synchronize];
  231. } else {
  232. [sender setState:NSOnState];
  233. timer = [NSTimer scheduledTimerWithTimeInterval:DISPLAY_DELAY target:self selector:@selector(visualizeDisplay:) userInfo:nil repeats:NO];
  234. // Store state
  235. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  236. [store setObject:[NSNumber numberWithBool:YES] forKey:PREF_TURNED_ON];
  237. [store synchronize];
  238. }
  239. }
  240. - (void)stopAmbilight {
  241. restartAmbilight = NO;
  242. if (timer != nil) {
  243. restartAmbilight = YES;
  244. [timer invalidate];
  245. timer = nil;
  246. [buttonAmbilight setState:NSOffState];
  247. }
  248. }
  249. - (void)newDisplayList:(NSArray *)displayIDs {
  250. lastDisplayIDs = displayIDs;
  251. if (restartAmbilight) {
  252. restartAmbilight = NO;
  253. [buttonAmbilight setState:NSOnState];
  254. timer = [NSTimer scheduledTimerWithTimeInterval:DISPLAY_DELAY target:self selector:@selector(visualizeDisplay:) userInfo:nil repeats:NO];
  255. }
  256. }
  257. - (IBAction)brightnessMoved:(NSSlider *)sender {
  258. [brightnessLabel setTitle:[NSString stringWithFormat:@"Value: %.0f%%", [sender floatValue]]];
  259. // Store changed value in preferences
  260. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  261. [store setObject:[NSNumber numberWithFloat:[sender floatValue]] forKey:PREF_BRIGHTNESS];
  262. [store synchronize];
  263. }
  264. - (IBAction)showAbout:(id)sender {
  265. [NSApp activateIgnoringOtherApps:YES];
  266. [application orderFrontStandardAboutPanel:self];
  267. }
  268. - (void)sendLEDFrame {
  269. if ([serial isOpen]) {
  270. [serial sendString:MAGIC_WORD];
  271. [serial sendData:(char *)ledColorData withLength:(sizeof(ledColorData) / sizeof(ledColorData[0]))];
  272. }
  273. }
  274. - (void)sendNullFrame {
  275. for (int i = 0; i < (sizeof(ledColorData) / sizeof(ledColorData[0])); i++) {
  276. ledColorData[i] = 0;
  277. }
  278. [self sendLEDFrame];
  279. }
  280. // ----------------------------------------------------
  281. // ------------ 'Ambilight' Visualizations ------------
  282. // ----------------------------------------------------
  283. UInt8 ledColorData[LED_COUNT * 3];
  284. - (UInt32)calculateAverage:(unsigned char *)data Width:(NSInteger)width Height:(NSInteger)height SPP:(NSInteger)spp Alpha:(BOOL)alpha StartX:(NSInteger)startX StartY:(NSInteger)startY EndX:(NSInteger)endX EndY:(NSInteger)endY {
  285. int redC = 0, greenC = 1, blueC = 2;
  286. if (alpha) {
  287. redC = 1; greenC = 2; blueC = 3;
  288. }
  289. NSInteger xa, xb, ya, yb;
  290. if (startX < endX) {
  291. xa = startX;
  292. xb = endX;
  293. } else {
  294. xa = endX;
  295. xb = startX;
  296. }
  297. if (startY < endY) {
  298. ya = startY;
  299. yb = endY;
  300. } else {
  301. ya = endY;
  302. yb = startY;
  303. }
  304. unsigned long red = 0, green = 0, blue = 0, count = 0;
  305. for (NSInteger i = xa; i < xb; i += AVERAGE_PIXEL_SKIP) {
  306. for (NSInteger j = ya; j < yb; j++) {
  307. count++;
  308. unsigned long index = i + (j * width);
  309. red += data[(index * spp) + redC];
  310. green += data[(index * spp) + greenC];
  311. blue += data[(index * spp) + blueC];
  312. }
  313. }
  314. red /= count;
  315. green /= count;
  316. blue /= count;
  317. red *= [brightnessSlider floatValue] / 100.0f;
  318. green *= [brightnessSlider floatValue] / 100.0f;
  319. blue *= [brightnessSlider floatValue] / 100.0f;
  320. return ((UInt32)red << 16) | ((UInt32)green << 8) | ((UInt32)blue);
  321. }
  322. - (void)visualizeSingleDisplay:(NSInteger)disp Data:(unsigned char *)data Width:(unsigned long)width Height:(unsigned long)height SPP:(NSInteger)spp Alpha:(BOOL)alpha {
  323. for (int i = 0; i < (sizeof(strands) / sizeof(strands[0])); i++) {
  324. if (strands[i].display == disp) {
  325. // Walk the strand, calculating value for each LED
  326. unsigned long x = strands[i].startX;
  327. unsigned long y = strands[i].startY;
  328. unsigned long blockWidth = COLOR_AVERAGE_OTHER_DIMENSION_SIZE;
  329. unsigned long blockHeight = COLOR_AVERAGE_OTHER_DIMENSION_SIZE;
  330. if ((strands[i].direction == DIR_LEFT) || (strands[i].direction == DIR_RIGHT)) {
  331. blockWidth = strands[i].size;
  332. } else {
  333. blockHeight = strands[i].size;
  334. }
  335. for (int led = strands[i].idMin; led < (strands[i].idMin + strands[i].count); led++) {
  336. // First move appropriately in the direction of the strand
  337. unsigned long endX = x, endY = y;
  338. if (strands[i].direction == DIR_LEFT) {
  339. endX -= blockWidth;
  340. } else if (strands[i].direction == DIR_RIGHT) {
  341. endX += blockWidth;
  342. } else if (strands[i].direction == DIR_UP) {
  343. endY -= blockHeight;
  344. } else if (strands[i].direction == DIR_DOWN) {
  345. endY += blockHeight;
  346. }
  347. // But also span the averaging-square in the other dimension, depending on which
  348. // side of the monitor we're at.
  349. if ((strands[i].direction == DIR_LEFT) || (strands[i].direction == DIR_RIGHT)) {
  350. if (y == 0) {
  351. endY = blockHeight;
  352. } else if (y == displays[disp].height) {
  353. endY -= blockHeight;
  354. }
  355. } else {
  356. if (x == 0) {
  357. endX = blockWidth;
  358. } else if (x == displays[disp].width) {
  359. endX -= blockWidth;
  360. }
  361. }
  362. // Calculate average color for this led
  363. UInt32 color = [self calculateAverage:data Width:width Height:height SPP:spp Alpha:alpha StartX:x StartY:y EndX:endX EndY:endY];
  364. ledColorData[led * 3] = (color & 0xFF0000) >> 16;
  365. ledColorData[(led * 3) + 1] = (color & 0x00FF00) >> 8;
  366. ledColorData[(led * 3) + 2] = color & 0x0000FF;
  367. // Move to next LED
  368. if ((strands[i].direction == DIR_LEFT) || (strands[i].direction == DIR_RIGHT)) {
  369. x = endX;
  370. } else {
  371. y = endY;
  372. }
  373. }
  374. }
  375. }
  376. }
  377. - (void)visualizeDisplay:(NSTimer *)time {
  378. #ifdef DEBUG_PRINT_FPS
  379. static NSInteger frameCount = 0;
  380. static NSDate *lastPrintTime = nil;
  381. if (lastPrintTime == nil) {
  382. lastPrintTime = [NSDate date];
  383. }
  384. #endif
  385. //NSLog(@"Running Ambilight-Algorithm (%lu)...", (unsigned long)[lastDisplayIDs count]);
  386. // Create a Screenshot for all connected displays
  387. for (NSInteger i = 0; i < [lastDisplayIDs count]; i++) {
  388. NSBitmapImageRep *screen = [Screenshot screenshot:[lastDisplayIDs objectAtIndex:i]];
  389. unsigned long width = [screen pixelsWide];
  390. unsigned long height = [screen pixelsHigh];
  391. // Ensure we can handle the format of this display
  392. NSInteger spp = [screen samplesPerPixel];
  393. if (((spp != 3) && (spp != 4)) || ([screen isPlanar] == YES) || ([screen numberOfPlanes] != 1)) {
  394. NSLog(@"Unknown image format for %ld (%ld, %c, %ld)!\n", (long)i, (long)spp, ([screen isPlanar] == YES) ? 'p' : 'n', (long)[screen numberOfPlanes]);
  395. continue;
  396. }
  397. // Find out how the color components are ordered
  398. BOOL alpha = NO;
  399. if ([screen bitmapFormat] & NSAlphaFirstBitmapFormat) {
  400. alpha = YES;
  401. }
  402. // Try to find the matching display id for the strand associations
  403. for (int n = 0; n < (sizeof(displays) / sizeof(displays[0])); n++) {
  404. if ((width == displays[n].width) && (height == displays[n].height)) {
  405. unsigned char *data = [screen bitmapData];
  406. [self visualizeSingleDisplay:n Data:data Width:width Height:height SPP:spp Alpha:alpha];
  407. break;
  408. }
  409. }
  410. }
  411. [self sendLEDFrame];
  412. #ifdef DEBUG_PRINT_FPS
  413. frameCount++;
  414. NSDate *now = [NSDate date];
  415. NSTimeInterval interval = [now timeIntervalSinceDate:lastPrintTime];
  416. if (interval >= DEBUG_PRINT_FPS) {
  417. NSLog(@"FPS: %.2f", frameCount / interval);
  418. frameCount = 0;
  419. lastPrintTime = now;
  420. }
  421. #endif
  422. timer = [NSTimer scheduledTimerWithTimeInterval:DISPLAY_DELAY target:self selector:@selector(visualizeDisplay:) userInfo:nil repeats:NO];
  423. }
  424. @end