SixelEncoder.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. // This code is based on existing implementations of sixel algorithm in MIT licensed open source libraries
  2. // node-sixel (Typescript) - https://github.com/jerch/node-sixel/tree/master/src
  3. // Copyright (c) 2019, Joerg Breitbart @license MIT
  4. // libsixel (C/C++) - https://github.com/saitoha/libsixel
  5. // Copyright (c) 2014-2016 Hayaki Saito @license MIT
  6. using Terminal.Gui;
  7. namespace Terminal.Gui;
  8. /// <summary>
  9. /// Encodes a images into the sixel console image output format.
  10. /// </summary>
  11. public class SixelEncoder
  12. {
  13. /*
  14. A sixel is a column of 6 pixels - with a width of 1 pixel
  15. Column controlled by one sixel character:
  16. [ ] - Bit 0 (top-most pixel)
  17. [ ] - Bit 1
  18. [ ] - Bit 2
  19. [ ] - Bit 3
  20. [ ] - Bit 4
  21. [ ] - Bit 5 (bottom-most pixel)
  22. Special Characters
  23. The '-' acts like '\n'. It moves the drawing cursor
  24. to beginning of next line
  25. The '$' acts like the <Home> key. It moves drawing
  26. cursor back to beginning of the current line
  27. e.g. to draw more color layers.
  28. */
  29. /// <summary>
  30. /// Gets or sets the quantizer responsible for building a representative
  31. /// limited color palette for images and for mapping novel colors in
  32. /// images to their closest palette color
  33. /// </summary>
  34. public ColorQuantizer Quantizer { get; set; } = new ();
  35. /// <summary>
  36. /// Encode the given bitmap into sixel encoding
  37. /// </summary>
  38. /// <param name="pixels"></param>
  39. /// <returns></returns>
  40. public string EncodeSixel (Color [,] pixels)
  41. {
  42. const string start = "\u001bP"; // Start sixel sequence
  43. string defaultRatios = this.AnyHasAlphaOfZero(pixels) ? "0;1;0": "0;0;0"; // Defaults for aspect ratio and grid size
  44. const string completeStartSequence = "q"; // Signals beginning of sixel image data
  45. const string noScaling = "\"1;1;"; // no scaling factors (1x1);
  46. string fillArea = GetFillArea (pixels);
  47. string pallette = GetColorPalette (pixels );
  48. string pixelData = WriteSixel (pixels);
  49. const string terminator = "\u001b\\"; // End sixel sequence
  50. return start + defaultRatios + completeStartSequence + noScaling + fillArea + pallette + pixelData + terminator;
  51. }
  52. private string WriteSixel (Color [,] pixels)
  53. {
  54. StringBuilder sb = new StringBuilder ();
  55. int height = pixels.GetLength (1);
  56. int width = pixels.GetLength (0);
  57. // Iterate over each 'row' of the image. Because each sixel write operation
  58. // outputs a screen area 6 pixels high (and 1+ across) we must process the image
  59. // 6 'y' units at once (1 band)
  60. for (int y = 0; y < height; y += 6)
  61. {
  62. sb.Append (ProcessBand (pixels, y, Math.Min (6, height - y), width));
  63. // Line separator between bands
  64. if (y + 6 < height) // Only add separator if not the last band
  65. {
  66. // This completes the drawing of the current line of sixel and
  67. // returns the 'cursor' to beginning next line, newly drawn sixel
  68. // after this will draw in the next 6 pixel high band (i.e. below).
  69. sb.Append ("-");
  70. }
  71. }
  72. return sb.ToString ();
  73. }
  74. private string ProcessBand (Color [,] pixels, int startY, int bandHeight, int width)
  75. {
  76. var last = new sbyte [Quantizer.Palette.Count + 1];
  77. var code = new byte [Quantizer.Palette.Count + 1];
  78. var accu = new ushort [Quantizer.Palette.Count + 1];
  79. var slots = new short [Quantizer.Palette.Count + 1];
  80. Array.Fill (last, (sbyte)-1);
  81. Array.Fill (accu, (ushort)1);
  82. Array.Fill (slots, (short)-1);
  83. var usedColorIdx = new List<int> ();
  84. var targets = new List<List<string>> ();
  85. // Process columns within the band
  86. for (int x = 0; x < width; ++x)
  87. {
  88. Array.Clear (code, 0, usedColorIdx.Count);
  89. bool anyNonTransparentPixel = false; // Track if any non-transparent pixels are found in this column
  90. // Process each row in the 6-pixel high band
  91. for (int row = 0; row < bandHeight; ++row)
  92. {
  93. var color = pixels [x, startY + row];
  94. int colorIndex = Quantizer.GetNearestColor (color);
  95. if (color.A == 0) // Skip fully transparent pixels
  96. {
  97. continue;
  98. }
  99. else
  100. {
  101. anyNonTransparentPixel = true;
  102. }
  103. if (slots [colorIndex] == -1)
  104. {
  105. targets.Add (new List<string> ());
  106. if (x > 0)
  107. {
  108. last [usedColorIdx.Count] = 0;
  109. accu [usedColorIdx.Count] = (ushort)x;
  110. }
  111. slots [colorIndex] = (short)usedColorIdx.Count;
  112. usedColorIdx.Add (colorIndex);
  113. }
  114. code [slots [colorIndex]] |= (byte)(1 << row); // Accumulate SIXEL data
  115. }
  116. /*
  117. // If no non-transparent pixels are found in the entire column, it's fully transparent
  118. if (!anyNonTransparentPixel)
  119. {
  120. // Emit fully transparent pixel data: #0!<width>?$
  121. result.Append ($"#0!{width}?");
  122. // Add the line terminator: use "$-" if it's not the last line, "$" if it's the last line
  123. if (x < width - 1)
  124. {
  125. result.Append ("$-");
  126. }
  127. else
  128. {
  129. result.Append ("$");
  130. }
  131. // Skip to the next column as we have already handled transparency
  132. continue;
  133. }*/
  134. // Handle transitions between columns
  135. for (int j = 0; j < usedColorIdx.Count; ++j)
  136. {
  137. if (code [j] == last [j])
  138. {
  139. accu [j]++;
  140. }
  141. else
  142. {
  143. if (last [j] != -1)
  144. {
  145. targets [j].Add (CodeToSixel (last [j], accu [j]));
  146. }
  147. last [j] = (sbyte)code [j];
  148. accu [j] = 1;
  149. }
  150. }
  151. }
  152. // Process remaining data for this band
  153. for (int j = 0; j < usedColorIdx.Count; ++j)
  154. {
  155. if (last [j] != 0)
  156. {
  157. targets [j].Add (CodeToSixel (last [j], accu [j]));
  158. }
  159. }
  160. // Build the final output for this band
  161. var result = new StringBuilder ();
  162. for (int j = 0; j < usedColorIdx.Count; ++j)
  163. {
  164. result.Append ($"#{usedColorIdx [j]}{string.Join ("", targets [j])}$");
  165. }
  166. return result.ToString ();
  167. }
  168. private static string CodeToSixel (int code, int repeat)
  169. {
  170. char c = (char)(code + 63);
  171. if (repeat > 3) return "!" + repeat + c;
  172. if (repeat == 3) return c.ToString () + c + c;
  173. if (repeat == 2) return c.ToString () + c;
  174. return c.ToString ();
  175. }
  176. private string GetColorPalette (Color [,] pixels)
  177. {
  178. Quantizer.BuildPalette (pixels);
  179. StringBuilder paletteSb = new StringBuilder ();
  180. for (int i = 0; i < Quantizer.Palette.Count; i++)
  181. {
  182. var color = Quantizer.Palette.ElementAt (i);
  183. paletteSb.AppendFormat ("#{0};2;{1};{2};{3}",
  184. i,
  185. color.R * 100 / 255,
  186. color.G * 100 / 255,
  187. color.B * 100 / 255);
  188. }
  189. return paletteSb.ToString ();
  190. }
  191. private string GetFillArea (Color [,] pixels)
  192. {
  193. int widthInChars = pixels.GetLength (0);
  194. int heightInChars = pixels.GetLength (1);
  195. return $"{widthInChars};{heightInChars}";
  196. }
  197. private bool AnyHasAlphaOfZero (Color [,] pixels)
  198. {
  199. int width = pixels.GetLength (0);
  200. int height = pixels.GetLength (1);
  201. // Loop through each pixel in the 2D array
  202. for (int x = 0; x < width; x++)
  203. {
  204. for (int y = 0; y < height; y++)
  205. {
  206. // Check if the alpha component (A) is 0
  207. if (pixels [x, y].A == 0)
  208. {
  209. return true; // Found a pixel with A of 0
  210. }
  211. }
  212. }
  213. return false; // No pixel with A of 0 was found
  214. }
  215. }