JPEGCodec.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  1. //
  2. // System.Drawing.Imaging.JPEGCodec.cs
  3. //
  4. // Author:
  5. // Alexandre Pigolkine ([email protected])
  6. //
  7. // (C) 2002/2003 Ximian, Inc.
  8. #if DECLARE_CDECL_DELEGATES
  9. namespace cdeclCallback {
  10. using System;
  11. internal class cdeclRedirector {
  12. internal delegate void MethodVoidIntPtr(IntPtr param);
  13. internal delegate int MethodIntIntPtr(IntPtr param);
  14. internal delegate void MethodVoidIntPtrInt(IntPtr param, int param1);
  15. internal delegate int MethodIntIntPtrInt(IntPtr param,int param1);
  16. }
  17. }
  18. #endif
  19. namespace System.Drawing.Imaging
  20. {
  21. using System;
  22. using System.IO;
  23. using System.Drawing.Imaging;
  24. using System.Runtime.InteropServices;
  25. using cdeclCallback;
  26. /// <summary>
  27. /// Summary description for JPEGCodec.
  28. /// </summary>
  29. internal class JPEGCodec
  30. {
  31. enum J_COLOR_SPACE : int {
  32. JCS_UNKNOWN = 0, /* error/unspecified */
  33. JCS_GRAYSCALE = 1, /* monochrome */
  34. JCS_RGB = 2, /* red/green/blue */
  35. JCS_YCbCr = 3, /* Y/Cb/Cr (also known as YUV) */
  36. JCS_CMYK = 4, /* C/M/Y/K */
  37. JCS_YCCK = 5 /* Y/Cb/Cr/K */
  38. }
  39. [StructLayout(LayoutKind.Sequential)]
  40. internal struct jpeg_error_mgr_get {
  41. public IntPtr a1;
  42. public IntPtr a2;
  43. public IntPtr a3;
  44. public IntPtr a4;
  45. public IntPtr a5;
  46. public int msg_code;
  47. [MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst=20)]
  48. public int[] param_array;
  49. public int trace_level;
  50. public int num_warnings;
  51. public int jpeg_message_table;
  52. public int last_jpeg_message;
  53. public int addon_message_table;
  54. public int first_addon_message;
  55. public int last_addon_message;
  56. };
  57. [StructLayout(LayoutKind.Sequential)]
  58. internal struct jpeg_error_mgr {
  59. public cdeclRedirector.MethodVoidIntPtr error_exit;
  60. public IntPtr a2;
  61. public IntPtr a3;
  62. public IntPtr a4;
  63. public IntPtr a5;
  64. public int msg_code;
  65. [MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst=20)]
  66. public int[] param_array;
  67. public int trace_level;
  68. public int num_warnings;
  69. public int jpeg_message_table;
  70. public int last_jpeg_message;
  71. public int addon_message_table;
  72. public int first_addon_message;
  73. public int last_addon_message;
  74. };
  75. [StructLayout(LayoutKind.Sequential)]
  76. struct jpeg_source_mgr {
  77. public IntPtr next_input_byte; /* => next byte to read from buffer */
  78. public uint bytes_in_buffer; /* # of bytes remaining in buffer */
  79. //[MarshalAs(UnmanagedType.FunctionPtr)]
  80. public cdeclRedirector.MethodVoidIntPtr init_source;
  81. //[MarshalAs(UnmanagedType.FunctionPtr)]
  82. public cdeclRedirector.MethodIntIntPtr fill_input_buffer;
  83. //[MarshalAs(UnmanagedType.FunctionPtr)]
  84. public cdeclRedirector.MethodVoidIntPtrInt skip_input_data;
  85. //[MarshalAs(UnmanagedType.FunctionPtr)]
  86. public cdeclRedirector.MethodIntIntPtrInt resync_to_restart;
  87. //[MarshalAs(UnmanagedType.FunctionPtr)]
  88. public cdeclRedirector.MethodVoidIntPtr term_source;
  89. };
  90. [StructLayout(LayoutKind.Sequential)]
  91. struct jpeg_destination_mgr {
  92. public IntPtr next_output_byte; /* => next byte to write in buffer */
  93. public uint free_in_buffer; /* # of byte spaces remaining in buffer */
  94. //[MarshalAs(UnmanagedType.FunctionPtr)]
  95. public cdeclRedirector.MethodVoidIntPtr init_destination;
  96. //[MarshalAs(UnmanagedType.FunctionPtr)]
  97. public cdeclRedirector.MethodIntIntPtr empty_output_buffer;
  98. //[MarshalAs(UnmanagedType.FunctionPtr)]
  99. public cdeclRedirector.MethodVoidIntPtr term_destination;
  100. };
  101. class jpeg_compress_decompress_base {
  102. byte[] raw_struct_array;
  103. IntPtr raw_error_mgr = IntPtr.Zero;
  104. IntPtr raw_source_mgr = IntPtr.Zero;
  105. IntPtr raw_destination_mgr = IntPtr.Zero;
  106. internal struct structure_fields {
  107. internal int structure_size;
  108. internal int QUANTIZE_COLORS;
  109. internal int ACTUAL_NUMBER_OF_COLORS;
  110. internal int OUT_COLOR_SPACE;
  111. internal int OUTPUT_WIDTH;
  112. internal int OUTPUT_HEIGHT;
  113. internal int OUT_COLOR_COMPONENT;
  114. internal int OUTPUT_COMPONENTS;
  115. internal int OUTPUT_SCANLINE;
  116. internal int OUT_COLORMAP;
  117. internal int IMAGE_WIDTH;
  118. internal int IMAGE_HEIGHT;
  119. internal int INPUT_COMPONENTS;
  120. internal int IN_COLOR_SPACE;
  121. internal int NEXT_SCAN_LINE;
  122. };
  123. structure_fields[] known_libraries;
  124. int current_library_index;
  125. public jpeg_compress_decompress_base(structure_fields[] known_libraries, int start_index) {
  126. this.known_libraries = known_libraries;
  127. current_library_index = start_index;
  128. raw_struct_array = new byte[known_libraries[current_library_index].structure_size];
  129. }
  130. public void switch_to_struct_size(int size) {
  131. if (raw_struct_array.Length == size) return;
  132. bool structureFound = false;
  133. for( int i = 0; i < known_libraries.Length; i++) {
  134. if( known_libraries[i].structure_size == size) {
  135. current_library_index = i;
  136. raw_struct_array = new byte[known_libraries[current_library_index].structure_size];
  137. structureFound = true;
  138. break;
  139. }
  140. }
  141. if (!structureFound) throw new Exception("JPEG Codec cannot work with existing libjpeg");
  142. }
  143. public byte[] raw_struct {
  144. get {
  145. return raw_struct_array;
  146. }
  147. }
  148. unsafe protected void copyToStruct( int value, int offset) {
  149. fixed( byte* pd = raw_struct_array) {
  150. *((int*)(pd + offset)) = value;
  151. }
  152. }
  153. unsafe protected int copyFromStruct( int offset) {
  154. int result = 0;
  155. fixed( byte* pd = raw_struct_array) {
  156. result = *((int*)(pd + offset));
  157. }
  158. return result;
  159. }
  160. public jpeg_error_mgr jpeg_error_mgr {
  161. set {
  162. raw_error_mgr = Marshal.AllocHGlobal(Marshal.SizeOf(value));
  163. Marshal.StructureToPtr(value, raw_error_mgr, false);
  164. copyToStruct(raw_error_mgr.ToInt32(), 0);
  165. }
  166. }
  167. public jpeg_source_mgr jpeg_source_mgr {
  168. set {
  169. raw_source_mgr = Marshal.AllocHGlobal( Marshal.SizeOf(value));
  170. Marshal.StructureToPtr( value, raw_source_mgr, false);
  171. copyToStruct(raw_source_mgr.ToInt32(), 24);
  172. }
  173. }
  174. public jpeg_destination_mgr jpeg_destination_mgr {
  175. set {
  176. raw_destination_mgr = Marshal.AllocHGlobal( Marshal.SizeOf(value));
  177. Marshal.StructureToPtr( value, raw_destination_mgr, false);
  178. copyToStruct(raw_destination_mgr.ToInt32(), 24);
  179. }
  180. }
  181. public int Stride {
  182. get {
  183. return OutputWidth * OutputComponents;
  184. }
  185. }
  186. public Color[] ColorMap {
  187. get {
  188. int actual_number_of_colors = copyFromStruct(known_libraries[current_library_index].ACTUAL_NUMBER_OF_COLORS);
  189. IntPtr nativeMap = (IntPtr)copyFromStruct(known_libraries[current_library_index].OUT_COLORMAP);
  190. Color[] map = new Color[actual_number_of_colors];
  191. if (nativeMap != IntPtr.Zero) {
  192. byte[] byteMap = new byte[OutColorComponents * actual_number_of_colors];
  193. Marshal.Copy( (IntPtr)Marshal.ReadInt32(nativeMap), byteMap, 0, byteMap.Length);
  194. }
  195. return map;
  196. }
  197. }
  198. public J_COLOR_SPACE OutColorSpace {
  199. get {
  200. return (J_COLOR_SPACE)copyFromStruct(known_libraries[current_library_index].OUT_COLOR_SPACE);
  201. }
  202. set {
  203. copyToStruct((int)value,known_libraries[current_library_index].OUT_COLOR_SPACE);
  204. }
  205. }
  206. public bool QuantizeColors {
  207. get {
  208. return raw_struct[known_libraries[current_library_index].QUANTIZE_COLORS] != (byte)0 ? true : false;
  209. }
  210. set {
  211. raw_struct[known_libraries[current_library_index].QUANTIZE_COLORS] = value ? (byte)1 : (byte)0;
  212. }
  213. }
  214. public int OutputWidth {
  215. get {
  216. return copyFromStruct(known_libraries[current_library_index].OUTPUT_WIDTH);
  217. }
  218. }
  219. public int OutputHeight {
  220. get {
  221. return copyFromStruct(known_libraries[current_library_index].OUTPUT_HEIGHT);
  222. }
  223. }
  224. public int OutColorComponents {
  225. get {
  226. return copyFromStruct(known_libraries[current_library_index].OUT_COLOR_COMPONENT);
  227. }
  228. }
  229. public int OutputComponents {
  230. get {
  231. return copyFromStruct(known_libraries[current_library_index].OUTPUT_COMPONENTS);
  232. }
  233. }
  234. public int OutputScanLine {
  235. get {
  236. return copyFromStruct(known_libraries[current_library_index].OUTPUT_SCANLINE);
  237. }
  238. }
  239. public int ImageWidth {
  240. set {
  241. copyToStruct(value, known_libraries[current_library_index].IMAGE_WIDTH);
  242. }
  243. }
  244. public int ImageHeight {
  245. get {
  246. return copyFromStruct(known_libraries[current_library_index].IMAGE_HEIGHT);
  247. }
  248. set {
  249. copyToStruct(value, known_libraries[current_library_index].IMAGE_HEIGHT);
  250. }
  251. }
  252. public int InputComponents {
  253. set {
  254. copyToStruct(value, known_libraries[current_library_index].INPUT_COMPONENTS);
  255. }
  256. }
  257. public J_COLOR_SPACE InColorSpace {
  258. set {
  259. copyToStruct((int)value, known_libraries[current_library_index].IN_COLOR_SPACE);
  260. }
  261. }
  262. public int NextScanLine {
  263. get {
  264. return copyFromStruct(known_libraries[current_library_index].NEXT_SCAN_LINE);
  265. }
  266. }
  267. }
  268. class jpeg_decompress_struct : jpeg_compress_decompress_base {
  269. const int GNU_JPEG_DLL_WINDOWS = 0;
  270. const int LINUX_LIBJPEG = 1;
  271. const int KNOWN_JPEG_LINRARIES = 2;
  272. static bool offsets_initialized;
  273. static jpeg_compress_decompress_base.structure_fields[] known_jpeg_libraries;
  274. static int current_library_index = LINUX_LIBJPEG;
  275. static void initialize_jpeg_decompress_structs() {
  276. if (!offsets_initialized) {
  277. known_jpeg_libraries = new jpeg_compress_decompress_base.structure_fields[KNOWN_JPEG_LINRARIES];
  278. // GNU JPEG Windows version
  279. known_jpeg_libraries[GNU_JPEG_DLL_WINDOWS].structure_size = 432;
  280. known_jpeg_libraries[GNU_JPEG_DLL_WINDOWS].QUANTIZE_COLORS = 74;
  281. known_jpeg_libraries[GNU_JPEG_DLL_WINDOWS].ACTUAL_NUMBER_OF_COLORS = 112;
  282. known_jpeg_libraries[GNU_JPEG_DLL_WINDOWS].OUT_COLOR_SPACE = 44;
  283. known_jpeg_libraries[GNU_JPEG_DLL_WINDOWS].OUTPUT_WIDTH = 92;
  284. known_jpeg_libraries[GNU_JPEG_DLL_WINDOWS].OUTPUT_HEIGHT = 96;
  285. known_jpeg_libraries[GNU_JPEG_DLL_WINDOWS].OUT_COLOR_COMPONENT = 100;
  286. known_jpeg_libraries[GNU_JPEG_DLL_WINDOWS].OUTPUT_COMPONENTS = 104;
  287. known_jpeg_libraries[GNU_JPEG_DLL_WINDOWS].OUTPUT_SCANLINE = 120;
  288. known_jpeg_libraries[GNU_JPEG_DLL_WINDOWS].OUT_COLORMAP = 116;
  289. // libjpeg Linux version
  290. known_jpeg_libraries[LINUX_LIBJPEG].structure_size = 464;
  291. known_jpeg_libraries[LINUX_LIBJPEG].QUANTIZE_COLORS = 84;
  292. known_jpeg_libraries[LINUX_LIBJPEG].ACTUAL_NUMBER_OF_COLORS = 132;
  293. known_jpeg_libraries[LINUX_LIBJPEG].OUT_COLOR_SPACE = 44;
  294. known_jpeg_libraries[LINUX_LIBJPEG].OUTPUT_WIDTH = 112;
  295. known_jpeg_libraries[LINUX_LIBJPEG].OUTPUT_HEIGHT = 116;
  296. known_jpeg_libraries[LINUX_LIBJPEG].OUT_COLOR_COMPONENT = 120;
  297. known_jpeg_libraries[LINUX_LIBJPEG].OUTPUT_COMPONENTS = 124;
  298. known_jpeg_libraries[LINUX_LIBJPEG].OUTPUT_SCANLINE = 140;
  299. known_jpeg_libraries[LINUX_LIBJPEG].OUT_COLORMAP = 136;
  300. offsets_initialized = true;
  301. }
  302. }
  303. static jpeg_decompress_struct() {
  304. initialize_jpeg_decompress_structs();
  305. }
  306. public jpeg_decompress_struct() : base(known_jpeg_libraries, LINUX_LIBJPEG) {
  307. }
  308. }
  309. class jpeg_compress_struct : jpeg_compress_decompress_base {
  310. const int GNU_JPEG_DLL_WINDOWS = 0;
  311. const int LINUX_LIBJPEG = 1;
  312. const int KNOWN_JPEG_LINRARIES = 2;
  313. static bool offsets_initialized;
  314. static jpeg_compress_decompress_base.structure_fields[] known_jpeg_libraries;
  315. static int current_library_index = LINUX_LIBJPEG;
  316. static void initialize_jpeg_compress_structs() {
  317. if (!offsets_initialized) {
  318. known_jpeg_libraries = new jpeg_compress_decompress_base.structure_fields[KNOWN_JPEG_LINRARIES];
  319. // GNU JPEG Windows version
  320. known_jpeg_libraries[GNU_JPEG_DLL_WINDOWS].structure_size = 360;
  321. known_jpeg_libraries[GNU_JPEG_DLL_WINDOWS].IMAGE_WIDTH = 28;
  322. known_jpeg_libraries[GNU_JPEG_DLL_WINDOWS].IMAGE_HEIGHT = 32;
  323. known_jpeg_libraries[GNU_JPEG_DLL_WINDOWS].INPUT_COMPONENTS = 36;
  324. known_jpeg_libraries[GNU_JPEG_DLL_WINDOWS].IN_COLOR_SPACE = 40;
  325. known_jpeg_libraries[GNU_JPEG_DLL_WINDOWS].NEXT_SCAN_LINE = 208;
  326. // libjpeg Linux version
  327. known_jpeg_libraries[LINUX_LIBJPEG].structure_size = 372;
  328. known_jpeg_libraries[LINUX_LIBJPEG].IMAGE_WIDTH = 28;
  329. known_jpeg_libraries[LINUX_LIBJPEG].IMAGE_HEIGHT = 32;
  330. known_jpeg_libraries[LINUX_LIBJPEG].INPUT_COMPONENTS = 36;
  331. known_jpeg_libraries[LINUX_LIBJPEG].IN_COLOR_SPACE = 40;
  332. known_jpeg_libraries[LINUX_LIBJPEG].NEXT_SCAN_LINE = 220;
  333. offsets_initialized = true;
  334. }
  335. }
  336. static jpeg_compress_struct() {
  337. initialize_jpeg_compress_structs();
  338. }
  339. public jpeg_compress_struct() : base(known_jpeg_libraries, LINUX_LIBJPEG) {
  340. }
  341. }
  342. [StructLayout(LayoutKind.Sequential)]
  343. internal struct JSAMPARRAY {
  344. // FIXME: This code is not working on Mono(** ERROR **: Invalid IL code at...). Report a bug and change it later.
  345. //const int MAX_SCAN_LINES = 10;
  346. //[MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst=MAX_SCAN_LINES)]
  347. //internal IntPtr[] JSAMPLES;
  348. internal IntPtr JSAMPLE0;
  349. internal IntPtr JSAMPLE1;
  350. internal JSAMPARRAY(int len) {
  351. /*
  352. JSAMPLES = new IntPtr[MAX_SCAN_LINES];
  353. for (int i = 0; i < MAX_SCAN_LINES; i++) {
  354. JSAMPLES[i] = Marshal.AllocHGlobal(len);
  355. }
  356. */
  357. JSAMPLE0 = Marshal.AllocHGlobal(len);
  358. JSAMPLE1 = Marshal.AllocHGlobal(len);
  359. }
  360. internal void Dispose() {
  361. /*
  362. for (int i = 0; i < MAX_SCAN_LINES; i++) {
  363. Marshal.FreeHGlobal(JSAMPLES[i]);
  364. }
  365. */
  366. Marshal.FreeHGlobal(JSAMPLE0);
  367. Marshal.FreeHGlobal(JSAMPLE1);
  368. }
  369. }
  370. const string JPEGLibrary = "jpeg";
  371. [DllImport(JPEGLibrary, EntryPoint="jpeg_CreateCompress", CallingConvention=CallingConvention.Cdecl)]
  372. internal static extern void jpeg_create_compress(byte[] info, int version, int structure_size);
  373. [DllImport(JPEGLibrary, EntryPoint="jpeg_CreateDecompress", CallingConvention=CallingConvention.Cdecl)]
  374. internal static extern void jpeg_create_decompress(byte[] info, int version, int structure_size);
  375. [DllImport(JPEGLibrary, CallingConvention=CallingConvention.Cdecl)]
  376. internal static extern void jpeg_std_error(ref jpeg_error_mgr_get err_mgr);
  377. [DllImport(JPEGLibrary, CallingConvention=CallingConvention.Cdecl)]
  378. internal static extern void jpeg_set_defaults(byte[] cinfo);
  379. [DllImport(JPEGLibrary, CallingConvention=CallingConvention.Cdecl)]
  380. internal static extern void jpeg_set_quality(byte[] cinfo, int quality, int force_baseline);
  381. [DllImport(JPEGLibrary, CallingConvention=CallingConvention.Cdecl)]
  382. internal static extern int jpeg_read_header(byte[] cinfo, int condition);
  383. [DllImport(JPEGLibrary, CallingConvention=CallingConvention.Cdecl)]
  384. internal static extern void jpeg_calc_output_dimensions(byte[] cinfo);
  385. [DllImport(JPEGLibrary, CallingConvention=CallingConvention.Cdecl)]
  386. internal static extern int jpeg_start_compress(byte[] cinfo, int write_all_tables);
  387. [DllImport(JPEGLibrary, CallingConvention=CallingConvention.Cdecl)]
  388. internal static extern int jpeg_start_decompress(byte[] cinfo);
  389. [DllImport(JPEGLibrary, CallingConvention=CallingConvention.Cdecl)]
  390. internal static extern int jpeg_read_scanlines(byte[] cinfo, ref JSAMPARRAY buffer, int num);
  391. [DllImport(JPEGLibrary, CallingConvention=CallingConvention.Cdecl)]
  392. internal static extern int jpeg_write_scanlines(byte[] cinfo, ref JSAMPARRAY scanlines, int num_lines);
  393. [DllImport(JPEGLibrary, CallingConvention=CallingConvention.Cdecl)]
  394. internal static extern int jpeg_finish_compress(byte[] cinfo);
  395. [DllImport(JPEGLibrary, CallingConvention=CallingConvention.Cdecl)]
  396. internal static extern int jpeg_finish_decompress(byte[] cinfo);
  397. [DllImport(JPEGLibrary, CallingConvention=CallingConvention.Cdecl)]
  398. internal static extern void jpeg_destroy_compress(byte[] cinfo);
  399. [DllImport(JPEGLibrary, CallingConvention=CallingConvention.Cdecl)]
  400. internal static extern void jpeg_destroy_decompress(byte[] cinfo);
  401. Stream fs;
  402. IntPtr buffer;
  403. int readwriteSize = 4096;
  404. // Source manager callbacks
  405. void init_source( IntPtr cinfo) {
  406. buffer = Marshal.AllocHGlobal(readwriteSize);
  407. }
  408. int fill_input_buffer( IntPtr cinfo) {
  409. byte[] result = new byte[readwriteSize];
  410. int readed = fs.Read(result, 0, readwriteSize);
  411. Marshal.Copy(result, 0, buffer, readed);
  412. IntPtr srcAddr = (IntPtr)Marshal.ReadInt32(cinfo, 24);
  413. Marshal.WriteInt32(srcAddr, 0, buffer.ToInt32());
  414. Marshal.WriteInt32(srcAddr, 4, readed);
  415. return 1;
  416. }
  417. void skip_input_data( IntPtr cinfo, int num_bytes) {
  418. //byte[] result = new byte[num_bytes];
  419. //fs.Read(result, 0, num_bytes);
  420. fs.Seek(num_bytes, SeekOrigin.Current);
  421. }
  422. int resync_to_restart( IntPtr cinfo, int desired){
  423. return 0;
  424. }
  425. void term_source( IntPtr cinfo) {
  426. Marshal.FreeHGlobal(buffer);
  427. }
  428. // Destination manager callbacks
  429. void init_destination( IntPtr cinfo) {
  430. buffer = Marshal.AllocHGlobal(readwriteSize);
  431. IntPtr srcAddr = (IntPtr)Marshal.ReadInt32(cinfo, 24);
  432. Marshal.WriteInt32(srcAddr, 0, buffer.ToInt32());
  433. Marshal.WriteInt32(srcAddr, 4, readwriteSize);
  434. }
  435. int empty_output_buffer( IntPtr cinfo) {
  436. IntPtr srcAddr = (IntPtr)Marshal.ReadInt32(cinfo, 24);
  437. IntPtr bufferPtr = (IntPtr)Marshal.ReadInt32(srcAddr, 0);
  438. int bytes = readwriteSize - Marshal.ReadInt32(srcAddr, 4);
  439. byte[] result = new byte[readwriteSize];
  440. Marshal.Copy(buffer, result, 0, readwriteSize);
  441. fs.Write(result, 0, readwriteSize);
  442. Marshal.WriteInt32(srcAddr, 0, buffer.ToInt32());
  443. Marshal.WriteInt32(srcAddr, 4, readwriteSize);
  444. return 1;
  445. }
  446. void term_destination( IntPtr cinfo) {
  447. IntPtr srcAddr = (IntPtr)Marshal.ReadInt32(cinfo, 24);
  448. IntPtr bufferPtr = (IntPtr)Marshal.ReadInt32(srcAddr, 0);
  449. int bytes = readwriteSize - Marshal.ReadInt32(srcAddr, 4);
  450. byte[] result = new byte[bytes];
  451. Marshal.Copy(buffer, result, 0, bytes);
  452. fs.Write(result, 0, bytes);
  453. Marshal.FreeHGlobal(buffer);
  454. }
  455. class RetryInitializationException : Exception {
  456. int libraryStructureSize;
  457. public RetryInitializationException(int structureSize) {
  458. this.libraryStructureSize = structureSize;
  459. }
  460. public int LibraryStructureSize {
  461. get {
  462. return libraryStructureSize;
  463. }
  464. }
  465. }
  466. enum JPEGErrorCodes : int {
  467. JERR_BAD_STRUCT_SIZE = 21
  468. }
  469. void error_exit( IntPtr cinfo) {
  470. jpeg_error_mgr mgr = new jpeg_error_mgr();
  471. IntPtr err_raw = (IntPtr)Marshal.ReadInt32(cinfo, 0);
  472. mgr = (jpeg_error_mgr)Marshal.PtrToStructure(err_raw, mgr.GetType());
  473. if ( mgr.msg_code == (int)JPEGErrorCodes.JERR_BAD_STRUCT_SIZE) {
  474. throw new RetryInitializationException(mgr.param_array[0]);
  475. }
  476. throw new Exception();
  477. }
  478. internal JPEGCodec() {
  479. }
  480. internal static ImageCodecInfo CodecInfo {
  481. get {
  482. ImageCodecInfo info = new ImageCodecInfo();
  483. info.Flags = ImageCodecFlags.Encoder | ImageCodecFlags.Decoder | ImageCodecFlags.Builtin | ImageCodecFlags.SupportBitmap;
  484. info.FormatDescription = "JPEG file format";
  485. info.FormatID = System.Drawing.Imaging.ImageFormat.Jpeg.Guid;
  486. info.MimeType = "image/jpeg";
  487. info.Version = 1;
  488. byte[][] signaturePatterns = new byte[1][];
  489. signaturePatterns[0] = new byte[]{0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00};
  490. info.SignaturePatterns = signaturePatterns;
  491. byte[][] signatureMasks = new byte[1][];
  492. signatureMasks[0] = new byte[]{0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff};
  493. info.SignatureMasks = signatureMasks;
  494. info.decode += new ImageCodecInfo.DecodeFromStream(JPEGCodec.DecodeDelegate);
  495. info.encode += new ImageCodecInfo.EncodeToStream(JPEGCodec.EncodeDelegate);
  496. return info;
  497. }
  498. }
  499. internal static void DecodeDelegate (Stream stream, InternalImageInfo info) {
  500. JPEGCodec jpeg = new JPEGCodec();
  501. jpeg.Decode (stream, info);
  502. }
  503. internal static void EncodeDelegate (Stream stream, InternalImageInfo info) {
  504. JPEGCodec jpeg = new JPEGCodec();
  505. jpeg.Encode (stream, info);
  506. }
  507. internal unsafe void switch_color_bytes( byte[] image) {
  508. fixed(byte* start = image) {
  509. byte *pb = start;
  510. byte t1;
  511. for( int ic = 0; ic < image.Length; ic +=3) {
  512. t1 = *pb;
  513. *(pb) = *(pb+2);
  514. *(pb+2) = t1;
  515. pb += 3;
  516. }
  517. }
  518. }
  519. internal bool Decode( Stream stream, InternalImageInfo info) {
  520. fs = stream;
  521. jpeg_error_mgr_get mgr = new jpeg_error_mgr_get();
  522. mgr.param_array = new int[20];
  523. jpeg_std_error( ref mgr);
  524. jpeg_error_mgr mgr_real = new jpeg_error_mgr();
  525. mgr_real.param_array = new int[20];
  526. mgr_real.error_exit = new cdeclCallback.cdeclRedirector.MethodVoidIntPtr(this.error_exit);
  527. mgr_real.msg_code = mgr.msg_code;
  528. mgr_real.a2 = mgr.a2;
  529. mgr_real.a3 = mgr.a3;
  530. mgr_real.a4 = mgr.a4;
  531. mgr_real.a5 = mgr.a5;
  532. mgr_real.trace_level = mgr.trace_level;
  533. mgr_real.num_warnings = mgr.num_warnings;
  534. mgr_real.last_jpeg_message = mgr.last_jpeg_message;
  535. mgr_real.first_addon_message = mgr.first_addon_message;
  536. mgr_real.last_addon_message = mgr.last_addon_message;
  537. mgr_real.jpeg_message_table = mgr.jpeg_message_table;
  538. jpeg_decompress_struct cinfo = new jpeg_decompress_struct();
  539. cinfo.jpeg_error_mgr = mgr_real;
  540. bool initializedOk = false;
  541. do {
  542. try {
  543. jpeg_create_decompress(cinfo.raw_struct, 62, cinfo.raw_struct.Length);
  544. initializedOk = true;
  545. }
  546. catch( RetryInitializationException ex) {
  547. initializedOk = false;
  548. cinfo.switch_to_struct_size(ex.LibraryStructureSize);
  549. cinfo.jpeg_error_mgr = mgr_real;
  550. }
  551. }while( !initializedOk);
  552. jpeg_source_mgr smgr = new jpeg_source_mgr();
  553. smgr.next_input_byte = IntPtr.Zero;
  554. smgr.bytes_in_buffer = 0;
  555. smgr.init_source = new cdeclRedirector.MethodVoidIntPtr(this.init_source);
  556. smgr.fill_input_buffer = new cdeclRedirector.MethodIntIntPtr(this.fill_input_buffer);
  557. smgr.skip_input_data = new cdeclRedirector.MethodVoidIntPtrInt(this.skip_input_data);
  558. smgr.resync_to_restart = new cdeclRedirector.MethodIntIntPtrInt(this.resync_to_restart);
  559. smgr.term_source = new cdeclRedirector.MethodVoidIntPtr(this.term_source);
  560. cinfo.jpeg_source_mgr = smgr;
  561. jpeg_read_header( cinfo.raw_struct, 1);
  562. jpeg_calc_output_dimensions(cinfo.raw_struct);
  563. jpeg_start_decompress(cinfo.raw_struct);
  564. int row_width = cinfo.Stride;
  565. while ((row_width & 3) != 0) row_width++;
  566. int pad_bytes = (row_width - cinfo.Stride);
  567. if (cinfo.OutColorSpace == J_COLOR_SPACE.JCS_RGB) {
  568. if (cinfo.QuantizeColors) {
  569. info.Format = PixelFormat.Format8bppIndexed;
  570. }
  571. else {
  572. info.Format = PixelFormat.Format24bppRgb;
  573. }
  574. }
  575. else {
  576. info.Format = PixelFormat.Format8bppIndexed;
  577. }
  578. info.Size = new Size(cinfo.OutputWidth,cinfo.OutputHeight);
  579. info.Stride = cinfo.Stride + pad_bytes;
  580. info.Palette = new ColorPalette(1, cinfo.ColorMap);
  581. info.Format = PixelFormat.Format24bppRgb;
  582. info.RawImageBytes = new byte[(cinfo.OutputHeight) * (cinfo.Stride + pad_bytes)];
  583. JSAMPARRAY outbuf = new JSAMPARRAY(cinfo.Stride);
  584. int outputRow = 0;
  585. int outputIndex = info.RawImageBytes.Length - cinfo.Stride - pad_bytes;
  586. while (cinfo.OutputScanLine < cinfo.OutputHeight) {
  587. // FIXME: switch to the Length after fixing a run-time error
  588. int readed = jpeg_read_scanlines(cinfo.raw_struct, ref outbuf, 1 /*outbuf.JSAMPLES.Length*/);
  589. for (int i = 0; i < readed; i++) {
  590. // FIXME: switch to .JSAMPLES[i] after fix of run-time error
  591. //Marshal.Copy(outbuf.JSAMPLES[i], info.RawImageBytes, outputIndex, cinfo.Stride);
  592. Marshal.Copy(outbuf.JSAMPLE0, info.RawImageBytes, outputIndex, cinfo.Stride);
  593. outputIndex -= cinfo.Stride + pad_bytes;
  594. outputRow++;
  595. }
  596. }
  597. // FIXME: analise count of color components here
  598. switch_color_bytes(info.RawImageBytes);
  599. jpeg_finish_decompress(cinfo.raw_struct);
  600. jpeg_destroy_decompress(cinfo.raw_struct);
  601. return true;
  602. }
  603. internal bool Encode( Stream stream, InternalImageInfo info) {
  604. int bpp = Image.GetPixelFormatSize(info.Format) / 8;
  605. if( bpp != 3 ) {
  606. throw new ArgumentException(String.Format("Supplied pixel format is not yet supported: {0}, {1} bpp", info.Format, Image.GetPixelFormatSize(info.Format)));
  607. }
  608. fs = stream;
  609. jpeg_error_mgr_get mgr = new jpeg_error_mgr_get();
  610. mgr.param_array = new int[20];
  611. jpeg_std_error( ref mgr);
  612. jpeg_error_mgr mgr_real = new jpeg_error_mgr();
  613. mgr_real.param_array = new int[20];
  614. mgr_real.error_exit = new cdeclCallback.cdeclRedirector.MethodVoidIntPtr(this.error_exit);
  615. mgr_real.msg_code = mgr.msg_code;
  616. mgr_real.a2 = mgr.a2;
  617. mgr_real.a3 = mgr.a3;
  618. mgr_real.a4 = mgr.a4;
  619. mgr_real.a5 = mgr.a5;
  620. mgr_real.trace_level = mgr.trace_level;
  621. mgr_real.num_warnings = mgr.num_warnings;
  622. mgr_real.last_jpeg_message = mgr.last_jpeg_message;
  623. mgr_real.first_addon_message = mgr.first_addon_message;
  624. mgr_real.last_addon_message = mgr.last_addon_message;
  625. mgr_real.jpeg_message_table = mgr.jpeg_message_table;
  626. jpeg_compress_struct cinfo = new jpeg_compress_struct();
  627. cinfo.jpeg_error_mgr = mgr_real;
  628. bool initializedOk = false;
  629. do {
  630. try {
  631. jpeg_create_compress(cinfo.raw_struct, 62, cinfo.raw_struct.Length);
  632. initializedOk = true;
  633. }
  634. catch( RetryInitializationException ex) {
  635. initializedOk = false;
  636. cinfo.switch_to_struct_size(ex.LibraryStructureSize);
  637. cinfo.jpeg_error_mgr = mgr_real;
  638. }
  639. }while( !initializedOk);
  640. jpeg_destination_mgr dmgr = new jpeg_destination_mgr();
  641. dmgr.next_output_byte = IntPtr.Zero;
  642. dmgr.free_in_buffer = 0;
  643. dmgr.init_destination = new cdeclRedirector.MethodVoidIntPtr(this.init_destination);
  644. dmgr.empty_output_buffer = new cdeclRedirector.MethodIntIntPtr(this.empty_output_buffer);
  645. dmgr.term_destination = new cdeclRedirector.MethodVoidIntPtr(this.term_destination);
  646. cinfo.jpeg_destination_mgr = dmgr;
  647. int row_width = info.Size.Width;
  648. while ((row_width & 3) != 0) row_width++;
  649. cinfo.ImageWidth = info.Size.Width;
  650. cinfo.ImageHeight = info.Size.Height;
  651. // FIXME: is it really only 24 bpp
  652. cinfo.InputComponents = bpp;
  653. cinfo.InColorSpace = J_COLOR_SPACE.JCS_RGB;
  654. jpeg_set_defaults( cinfo.raw_struct);
  655. jpeg_start_compress( cinfo.raw_struct, 1);
  656. // FIXME: is it really only 24 bpp ?
  657. row_width *= bpp;
  658. JSAMPARRAY inbuf = new JSAMPARRAY(row_width);
  659. // FIXME: analise count of color components here
  660. switch_color_bytes(info.RawImageBytes);
  661. int inputIndex = info.RawImageBytes.Length - row_width;
  662. while (cinfo.NextScanLine < cinfo.ImageHeight) {
  663. //Marshal.Copy(inbuf.JSAMPLES[0], info.RawImageBytes, outputIndex, cinfo.Stride);
  664. Marshal.Copy(info.RawImageBytes, inputIndex, inbuf.JSAMPLE0, row_width);
  665. //inputIndex += info.Size.Width * 3;
  666. inputIndex -= row_width;
  667. jpeg_write_scanlines(cinfo.raw_struct, ref inbuf, 1 /*inbuf.JSAMPLES.Length*/);
  668. }
  669. jpeg_finish_compress(cinfo.raw_struct);
  670. jpeg_destroy_compress(cinfo.raw_struct);
  671. // FIXME: analise count of color components here
  672. // put them back
  673. switch_color_bytes(info.RawImageBytes);
  674. return true;
  675. }
  676. }
  677. }