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 20KB

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