JPEGCodec.cs 27 KB

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