SixelEncoder.cs 7.7 KB

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